From c44e171dbc802ddefc736b463a7635ca396bbc23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yusuf=20G=C3=BCrdo=C4=9Fan?= Date: Tue, 8 Sep 2026 07:40:36 +0300 Subject: [PATCH 001/568] feat(agent): add Sofya search tool (#19323) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add Sofya web search tool — returns full page content (not snippets). Modeled on You.com. Configurable depth (basic/snippets), top N, and per-call params. --------- Co-authored-by: Claude Opus 5 Co-authored-by: Jin Hai --- agent/tools/sofya.py | 290 ++++++++++++ test/unit_test/agent/tools/test_sofya_unit.py | 412 ++++++++++++++++++ web/src/assets/svg/sofya.svg | 9 + web/src/components/operator-icon.tsx | 1 + web/src/constants/agent.tsx | 1 + web/src/locales/en.ts | 9 + web/src/locales/zh.ts | 9 + .../node/dropdown/accordion-operators.tsx | 1 + web/src/pages/agent/constant/index.tsx | 24 + .../agent/form-sheet/form-config-map.tsx | 4 + .../agent-form/tool-popover/tool-command.tsx | 1 + web/src/pages/agent/form/sofya-form/index.tsx | 108 +++++ .../pages/agent/form/tool-form/constant.tsx | 2 + .../agent/form/tool-form/sofya-form/index.tsx | 35 ++ web/src/pages/agent/hooks/use-add-node.ts | 2 + .../hooks/use-agent-tool-initial-values.ts | 2 + .../agent/log-sheet/tool-timeline-item.tsx | 1 + .../utils/clear-sensitive-fields.test.ts | 37 ++ .../agent/utils/clear-sensitive-fields.ts | 6 +- 19 files changed, 953 insertions(+), 1 deletion(-) create mode 100644 agent/tools/sofya.py create mode 100644 test/unit_test/agent/tools/test_sofya_unit.py create mode 100644 web/src/assets/svg/sofya.svg create mode 100644 web/src/pages/agent/form/sofya-form/index.tsx create mode 100644 web/src/pages/agent/form/tool-form/sofya-form/index.tsx diff --git a/agent/tools/sofya.py b/agent/tools/sofya.py new file mode 100644 index 00000000000..e7b8a6417a8 --- /dev/null +++ b/agent/tools/sofya.py @@ -0,0 +1,290 @@ +# +# 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. +# +import logging +import os +import time +from abc import ABC + +import requests + +from agent.tools.base import ToolBase, ToolMeta, ToolParamBase +from common.connection_utils import timeout + +SOFYA_SEARCH_URL = "https://sofya.co/v1/search" +# Sofya returns at most 20 results per search. +SOFYA_MAX_RESULTS = 20 +# "basic" fetches the result pages and returns their content; "snippets" +# returns the search snippets only, which is faster and cheaper. +SOFYA_SEARCH_DEPTHS = ["basic", "snippets"] +SOFYA_DEFAULT_SEARCH_DEPTH = "basic" +SOFYA_TOPICS = ["general", "news"] +SOFYA_DEFAULT_TOPIC = "general" +# Sofya also accepts a date range for freshness. Only the named windows are +# offered here, so the value can be checked against a fixed list. +SOFYA_FRESHNESS_ANY = "any" +SOFYA_FRESHNESS_VALUES = [SOFYA_FRESHNESS_ANY, "day", "week", "month", "year"] +# Statuses worth another attempt. Anything else (bad request, bad key, no +# credits) will fail the same way again, so it is returned at once. +SOFYA_RETRY_STATUSES = {429, 500, 502, 503, 504} + + +def _search(api_key: str, payload: dict, timeout_s: int = 30) -> dict: + """POST a search to Sofya and return the decoded body.""" + headers = { + "Authorization": f"Bearer {(api_key or '').strip()}", + "Content-Type": "application/json", + "Accept": "application/json", + # Identifies RAGFlow to Sofya. + "User-Agent": "RAGFlow sofya-integration/infiniflow-ragflow", + } + response = requests.post(SOFYA_SEARCH_URL, headers=headers, json=payload, timeout=timeout_s) + response.raise_for_status() + return response.json() + + +def _is_transient(error: Exception) -> bool: + """Whether a failed request might succeed if repeated.""" + if isinstance(error, requests.HTTPError): + response = getattr(error, "response", None) + return getattr(response, "status_code", None) in SOFYA_RETRY_STATUSES + return isinstance(error, requests.RequestException) + + +def _search_depth(value) -> str: + """Normalize the node's search depth. + + This one is set in the node config rather than by the caller, so an unknown + value falls back to the default instead of failing the run. + """ + depth = str(value or "").strip().lower() + if depth in SOFYA_SEARCH_DEPTHS: + return depth + if depth: + logging.warning(f"Sofya search depth {depth} is not supported, using {SOFYA_DEFAULT_SEARCH_DEPTH}") + return SOFYA_DEFAULT_SEARCH_DEPTH + + +def _topic(value) -> str: + """Normalize a topic. Blank means the default, anything else must be known.""" + topic = str(value or "").strip().lower() + if not topic: + return SOFYA_DEFAULT_TOPIC + if topic not in SOFYA_TOPICS: + raise ValueError("Topic {} is not supported, it should be in {}".format(topic, SOFYA_TOPICS)) + return topic + + +def _freshness(value) -> str: + """Normalize a freshness value to a Sofya window, or "" for no limit. + + Blank and `any` both mean no restriction. Anything else has to be one of the + named windows, because the value is forwarded to Sofya as-is. + """ + freshness = str(value or "").strip().lower() + if not freshness or freshness == SOFYA_FRESHNESS_ANY: + return "" + if freshness not in SOFYA_FRESHNESS_VALUES: + raise ValueError("Freshness {} is not supported, it should be in {}".format(freshness, SOFYA_FRESHNESS_VALUES)) + return freshness + + +def _max_results(value, fallback) -> int: + """Result count: the caller's if it gave one, else the node's Top N. + + A blank or unparseable caller value is treated as "not given" so a bad + argument falls back rather than failing the run. + """ + for candidate in (value, fallback): + try: + count = int(candidate) + except (TypeError, ValueError): + continue + return min(max(1, count), SOFYA_MAX_RESULTS) + return 1 + + +def _result_content(result: dict) -> str: + """Prefer the page content, falling back to the search snippet. + + `content` carries the text of the result page and is empty when the page + was not read; `description` is the search snippet. Either can be missing, so + a result with no text at all returns "" and is dropped rather than stored as + a blank chunk. + """ + content = " ".join(str(result.get("content") or "").split()) + if content: + return content + return " ".join(str(result.get("description") or "").split()) + + +def _results(data, top_n: int) -> list[dict]: + """Pull the result list out of the response body.""" + if not isinstance(data, dict): + return [] + results = data.get("results") + if not isinstance(results, list): + return [] + return [r for r in results if isinstance(r, dict)][:top_n] + + +class SofyaSearchParam(ToolParamBase): + """ + Define the Sofya search component parameters. + """ + + def __init__(self): + self.meta: ToolMeta = { + "name": "sofya_search", + "description": """ +Sofya is a web search API for AI agents. It returns the content of the result +pages, not just a snippet, so results carry usable context without a separate +fetch. An API key is required. +When searching: + - Use a focused query of the most important terms (and synonyms). + - Use the news topic for current events, and the general topic otherwise. + - Optionally restrict results by how recently they were published. + """, + "parameters": { + "query": { + "type": "string", + "description": "The search keywords to execute with Sofya. The keywords should be the most important words/terms(includes synonyms) from the original request.", + "default": "{sys.query}", + "required": True, + }, + "topic": { + "type": "string", + "description": "default:'general'. The category of the search. 'news' searches news sources and suits current events; 'general' is a broader web search.", + "enum": SOFYA_TOPICS, + "default": SOFYA_DEFAULT_TOPIC, + "required": False, + }, + "freshness": { + "type": "string", + "description": "default:'any'. Restrict results by recency. One of 'day', 'week', 'month', 'year', or 'any' for no limit.", + "enum": SOFYA_FRESHNESS_VALUES, + "default": SOFYA_FRESHNESS_ANY, + "required": False, + }, + "max_results": { + "type": "integer", + "description": "Number of results to return, 1 to 20. Leave it out to use the Top N set on the node.", + "default": "", + "required": False, + }, + }, + } + super().__init__() + self.api_key = "" + self.search_depth = SOFYA_DEFAULT_SEARCH_DEPTH + self.top_n = 10 + + def check(self): + self.check_empty(self.api_key, "Sofya API key") + self.check_valid_value(self.search_depth, "Sofya search depth should be in 'basic/snippets'", ["basic", "snippets"]) + self.check_positive_integer(self.top_n, "Top N") + + def get_input_form(self) -> dict[str, dict]: + return { + "query": { + "name": "Query", + "type": "line", + }, + "topic": { + "name": "Topic", + "type": "options", + "value": SOFYA_DEFAULT_TOPIC, + "options": SOFYA_TOPICS, + }, + "freshness": { + "name": "Freshness", + "type": "options", + "value": SOFYA_FRESHNESS_ANY, + "options": SOFYA_FRESHNESS_VALUES, + }, + } + + +class SofyaSearch(ToolBase, ABC): + component_name = "SofyaSearch" + + @timeout(int(os.environ.get("COMPONENT_EXEC_TIMEOUT", 12))) + def _invoke(self, **kwargs): + if self.check_if_canceled("SofyaSearch processing"): + return + + if not kwargs.get("query"): + self.set_output("formalized_content", "") + return "" + + search_depth = _search_depth(self._param.search_depth) + top_n = _max_results(kwargs.get("max_results"), self._param.top_n) + payload = { + "query": kwargs["query"], + "search_depth": search_depth, + "max_results": top_n, + "topic": _topic(kwargs.get("topic")), + } + freshness = _freshness(kwargs.get("freshness")) + if freshness: + payload["freshness"] = freshness + + logging.info(f"SofyaSearch: starting search (search_depth={search_depth}, max_results={top_n})") + last_e = None + attempts = self._param.max_retries + 1 + for attempt in range(attempts): + if self.check_if_canceled("SofyaSearch processing"): + logging.info("SofyaSearch: cancelled before request") + return + + try: + data = _search(self._param.api_key, payload) + if self.check_if_canceled("SofyaSearch processing"): + logging.info("SofyaSearch: cancelled after request") + return + + results = _results(data, top_n) + self._retrieve_chunks( + results, + get_title=lambda r: str(r.get("title") or ""), + get_url=lambda r: str(r.get("url") or ""), + get_content=_result_content, + ) + self.set_output("json", results) + logging.info(f"SofyaSearch: returned {len(results)} results") + return self.output("formalized_content") + except Exception as e: + if self.check_if_canceled("SofyaSearch processing"): + return + + # Only the exception type is recorded, so the query and the key + # stay out of the log whatever the error message holds. + last_e = e + logging.error(f"Sofya error: {type(e).__name__}") + if not _is_transient(e): + break + if attempt < attempts - 1: + time.sleep(self._param.delay_after_error) + + if last_e: + return f"Sofya error: {type(last_e).__name__}" + + assert False, self.output() + + def thoughts(self) -> str: + return """ +Keywords: {} +Looking for the most relevant articles. + """.format(self.get_input().get("query", "-_-!")) diff --git a/test/unit_test/agent/tools/test_sofya_unit.py b/test/unit_test/agent/tools/test_sofya_unit.py new file mode 100644 index 00000000000..8a8d6567cc0 --- /dev/null +++ b/test/unit_test/agent/tools/test_sofya_unit.py @@ -0,0 +1,412 @@ +# +# 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. +# + +import agent.tools.sofya as sofya_module +from agent.tools.sofya import SofyaSearch, SofyaSearchParam + +SEARCH_URL = "https://sofya.co/v1/search" + + +class _FakeResponse: + def __init__(self, payload, status_code=200): + self._payload = payload + self.status_code = status_code + self.url = SEARCH_URL + + def json(self): + return self._payload + + def raise_for_status(self): + if self.status_code >= 400: + raise sofya_module.requests.HTTPError( + f"{self.status_code} Client Error for url: {self.url}", + response=self, + ) + + +def _make_tool(api_key="sofya-key"): + tool = SofyaSearch.__new__(SofyaSearch) + param = SofyaSearchParam() + param.api_key = api_key + param.delay_after_error = 0 + param.max_retries = 0 + tool._param = param + tool.check_if_canceled = lambda *args, **kwargs: False + + captured = {} + outputs = {} + + def fake_retrieve(results, get_title, get_url, get_content): + captured["references"] = [{"title": get_title(item), "url": get_url(item), "content": get_content(item)} for item in results] + outputs["formalized_content"] = "FORMALIZED" + + tool._retrieve_chunks = fake_retrieve + tool.set_output = lambda key, value: outputs.__setitem__(key, value) + tool.output = lambda key=None: outputs.get(key) if key else outputs + return tool, captured, outputs + + +def _payload(): + return { + "results": [ + { + "url": "https://example.com/a", + "title": "A", + "description": "Snippet for A.", + "content": "Page text for A.", + }, + { + "url": "https://example.com/b", + "title": "B", + "description": "Snippet for B.", + "content": "", + }, + ] + } + + +def _capture_post(monkeypatch, response=None): + calls = [] + + def fake_post(url, headers=None, json=None, timeout=None): + calls.append({"url": url, "headers": headers, "json": json}) + return response if response is not None else _FakeResponse(_payload()) + + monkeypatch.setattr(sofya_module.requests, "post", fake_post) + return calls + + +def test_search_posts_the_query_with_a_bearer_key(monkeypatch): + calls = _capture_post(monkeypatch) + tool, _captured, outputs = _make_tool(api_key=" sofya-key ") + + tool._invoke(query="What is RAGFlow?") + + assert calls[0]["url"] == SEARCH_URL + assert calls[0]["headers"]["Authorization"] == "Bearer sofya-key" + assert calls[0]["json"]["query"] == "What is RAGFlow?" + assert outputs["formalized_content"] == "FORMALIZED" + + +def test_requests_identify_ragflow(monkeypatch): + calls = _capture_post(monkeypatch) + tool, _captured, _outputs = _make_tool() + + tool._invoke(query="q") + + assert calls[0]["headers"]["User-Agent"] == "RAGFlow sofya-integration/infiniflow-ragflow" + + +def test_page_content_is_preferred_over_the_snippet(monkeypatch): + _capture_post(monkeypatch) + tool, captured, outputs = _make_tool() + + tool._invoke(query="q") + + assert captured["references"] == [ + {"title": "A", "url": "https://example.com/a", "content": "Page text for A."}, + # B has no page content, so its snippet is used. + {"title": "B", "url": "https://example.com/b", "content": "Snippet for B."}, + ] + assert len(outputs["json"]) == 2 + + +def test_non_string_result_fields_do_not_raise(monkeypatch): + payload = {"results": [{"url": 42, "title": True, "content": 7, "description": None}]} + _capture_post(monkeypatch, _FakeResponse(payload)) + tool, captured, _outputs = _make_tool() + + tool._invoke(query="q") + + assert captured["references"] == [{"title": "True", "url": "42", "content": "7"}] + + +def test_whitespace_only_content_falls_back_to_the_snippet(monkeypatch): + payload = {"results": [{"url": "https://example.com/c", "title": "C", "content": " ", "description": " Snippet for C. "}]} + _capture_post(monkeypatch, _FakeResponse(payload)) + tool, captured, _outputs = _make_tool() + + tool._invoke(query="q") + + assert captured["references"] == [{"title": "C", "url": "https://example.com/c", "content": "Snippet for C."}] + + +def test_a_result_with_no_text_at_all_yields_no_content(monkeypatch): + payload = {"results": [{"url": "https://example.com/d", "title": "D", "content": " ", "description": " "}]} + _capture_post(monkeypatch, _FakeResponse(payload)) + tool, captured, _outputs = _make_tool() + + tool._invoke(query="q") + + # An empty content is dropped by _retrieve_chunks rather than stored blank. + assert captured["references"] == [{"title": "D", "url": "https://example.com/d", "content": ""}] + + +def test_a_results_field_that_is_not_a_list_yields_nothing(monkeypatch): + _capture_post(monkeypatch, _FakeResponse({"results": None})) + tool, captured, _outputs = _make_tool() + + tool._invoke(query="q") + + assert captured["references"] == [] + + +def test_the_node_top_n_is_used_when_the_caller_gives_no_count(monkeypatch): + calls = _capture_post(monkeypatch) + tool, captured, _outputs = _make_tool() + tool._param.top_n = 1 + + tool._invoke(query="q") + + assert calls[0]["json"]["max_results"] == 1 + assert [r["title"] for r in captured["references"]] == ["A"] + + +def test_a_caller_supplied_count_wins_over_the_node_top_n(monkeypatch): + calls = _capture_post(monkeypatch) + tool, _captured, _outputs = _make_tool() + tool._param.top_n = 10 + + tool._invoke(query="q", max_results=3) + + assert calls[0]["json"]["max_results"] == 3 + + +def test_the_result_count_is_clamped_to_the_supported_range(monkeypatch): + calls = _capture_post(monkeypatch) + tool, _captured, _outputs = _make_tool() + + tool._invoke(query="q", max_results=500) + assert calls[0]["json"]["max_results"] == 20 + + tool._invoke(query="q", max_results=0) + assert calls[1]["json"]["max_results"] == 1 + + # An unusable argument falls back to the node's Top N. + tool._invoke(query="q", max_results="lots") + assert calls[2]["json"]["max_results"] == tool._param.top_n + + +def test_an_unknown_search_depth_falls_back_to_the_default(monkeypatch, caplog): + calls = _capture_post(monkeypatch) + tool, _captured, _outputs = _make_tool() + tool._param.search_depth = "advanced" + + with caplog.at_level("WARNING"): + tool._invoke(query="q") + + assert calls[0]["json"]["search_depth"] == "basic" + assert "advanced" in caplog.text + + +def test_the_search_depth_is_forwarded_when_it_is_supported(monkeypatch): + calls = _capture_post(monkeypatch) + tool, _captured, _outputs = _make_tool() + tool._param.search_depth = "snippets" + + tool._invoke(query="q") + + assert calls[0]["json"]["search_depth"] == "snippets" + + +def test_freshness_is_forwarded_only_when_a_window_is_set(monkeypatch): + calls = _capture_post(monkeypatch) + tool, _captured, _outputs = _make_tool() + + tool._invoke(query="q", freshness="week") + assert calls[0]["json"]["freshness"] == "week" + + # Blank and `any` both mean no restriction. + tool._invoke(query="q", freshness="") + assert "freshness" not in calls[1]["json"] + + tool._invoke(query="q", freshness="any") + assert "freshness" not in calls[2]["json"] + + +def test_an_unsupported_freshness_is_rejected_before_the_request(monkeypatch): + calls = _capture_post(monkeypatch) + tool, _captured, _outputs = _make_tool() + + try: + tool._invoke(query="q", freshness="decade") + except ValueError as e: + assert "decade" in str(e) + assert calls == [] + return + raise AssertionError("expected an unsupported freshness to raise") + + +def test_an_unsupported_topic_is_rejected_before_the_request(monkeypatch): + calls = _capture_post(monkeypatch) + tool, _captured, _outputs = _make_tool() + + try: + tool._invoke(query="q", topic="sports") + except ValueError as e: + assert "sports" in str(e) + assert calls == [] + return + raise AssertionError("expected an unsupported topic to raise") + + +def test_the_topic_defaults_to_general(monkeypatch): + calls = _capture_post(monkeypatch) + tool, _captured, _outputs = _make_tool() + + tool._invoke(query="q") + assert calls[0]["json"]["topic"] == "general" + + tool._invoke(query="q", topic="news") + assert calls[1]["json"]["topic"] == "news" + + +def test_the_published_schema_restricts_the_enums(): + properties = SofyaSearchParam().get_meta()["function"]["parameters"]["properties"] + + assert properties["topic"]["enum"] == ["general", "news"] + assert properties["freshness"]["enum"] == ["any", "day", "week", "month", "year"] + + +def test_blank_query_short_circuits(monkeypatch): + calls = _capture_post(monkeypatch) + tool, _captured, outputs = _make_tool() + + assert tool._invoke(query="") == "" + assert calls == [] + assert outputs["formalized_content"] == "" + + +def test_failures_never_log_the_query_or_the_key(monkeypatch, caplog): + _capture_post(monkeypatch, _FakeResponse({}, status_code=402)) + tool, _captured, _outputs = _make_tool(api_key="sofya-secret") + + with caplog.at_level("ERROR"): + result = tool._invoke(query="my private query") + + assert "my private query" not in caplog.text + assert "sofya-secret" not in caplog.text + assert "my private query" not in str(result) + assert "HTTPError" in str(result) + + +def _capture_sleep(monkeypatch): + """Record the retry delays without patching the stdlib for other threads.""" + slept = [] + + class _Clock: + @staticmethod + def sleep(seconds): + slept.append(seconds) + + monkeypatch.setattr(sofya_module, "time", _Clock) + return slept + + +def test_a_failed_final_attempt_does_not_sleep(monkeypatch): + """The delay only buys something when another attempt follows it.""" + _capture_post(monkeypatch, _FakeResponse({}, status_code=402)) + slept = _capture_sleep(monkeypatch) + tool, _captured, _outputs = _make_tool() + tool._param.max_retries = 0 + tool._param.delay_after_error = 5 + + tool._invoke(query="q") + + assert slept == [] + + +def test_transient_failures_are_retried_with_a_delay(monkeypatch): + calls = _capture_post(monkeypatch, _FakeResponse({}, status_code=503)) + slept = _capture_sleep(monkeypatch) + tool, _captured, _outputs = _make_tool() + tool._param.max_retries = 2 + tool._param.delay_after_error = 5 + + tool._invoke(query="q") + + assert len(calls) == 3 + # Two gaps between three attempts, and nothing after the last one. + assert slept == [5, 5] + + +def test_non_transient_failures_are_not_retried(monkeypatch): + """A bad key or no credits fails the same way every time, so ask once.""" + calls = _capture_post(monkeypatch, _FakeResponse({}, status_code=402)) + slept = _capture_sleep(monkeypatch) + tool, _captured, _outputs = _make_tool() + tool._param.max_retries = 2 + tool._param.delay_after_error = 5 + + result = tool._invoke(query="q") + + assert len(calls) == 1 + assert slept == [] + assert "HTTPError" in str(result) + + +def test_network_errors_are_retried(monkeypatch): + slept = _capture_sleep(monkeypatch) + attempts = [] + + def failing_post(url, headers=None, json=None, timeout=None): + attempts.append(url) + raise sofya_module.requests.ConnectionError("connection reset") + + monkeypatch.setattr(sofya_module.requests, "post", failing_post) + tool, _captured, _outputs = _make_tool() + tool._param.max_retries = 1 + tool._param.delay_after_error = 2 + + result = tool._invoke(query="q") + + assert len(attempts) == 2 + assert slept == [2] + assert "ConnectionError" in str(result) + + +def test_param_check_requires_an_api_key(): + param = SofyaSearchParam() + + try: + param.check() + except Exception: + return + raise AssertionError("expected check() to reject a blank API key") + + +def test_param_check_rejects_an_unknown_search_depth(): + param = SofyaSearchParam() + param.api_key = "sofya-key" + param.search_depth = "advanced" + + try: + param.check() + except Exception: + return + raise AssertionError("expected check() to reject an unknown search depth") + + +def test_param_check_rejects_a_non_positive_top_n(): + param = SofyaSearchParam() + param.api_key = "sofya-key" + param.top_n = 0 + + try: + param.check() + except Exception: + return + raise AssertionError("expected check() to reject top_n=0") diff --git a/web/src/assets/svg/sofya.svg b/web/src/assets/svg/sofya.svg new file mode 100644 index 00000000000..400aa726729 --- /dev/null +++ b/web/src/assets/svg/sofya.svg @@ -0,0 +1,9 @@ + + Sofya + + + + + + + diff --git a/web/src/components/operator-icon.tsx b/web/src/components/operator-icon.tsx index 021d28d228a..ff52e29325c 100644 --- a/web/src/components/operator-icon.tsx +++ b/web/src/components/operator-icon.tsx @@ -73,6 +73,7 @@ export const SVGIconMap = { [Operator.SearXNG]: 'searxng', [Operator.KeenableSearch]: 'keenable', [Operator.YouComSearch]: 'youcom', + [Operator.SofyaSearch]: 'sofya', [Operator.TavilyExtract]: 'tavily', [Operator.TavilySearch]: 'tavily', [Operator.QueritContents]: 'querit', diff --git a/web/src/constants/agent.tsx b/web/src/constants/agent.tsx index 4adccf304fc..fd81020f4b3 100644 --- a/web/src/constants/agent.tsx +++ b/web/src/constants/agent.tsx @@ -119,6 +119,7 @@ export enum Operator { BGPT = 'BGPT', KeenableSearch = 'KeenableSearch', YouComSearch = 'YouComSearch', + SofyaSearch = 'SofyaSearch', DocGenerator = 'DocGenerator', Browser = 'Browser', Placeholder = 'Placeholder', diff --git a/web/src/locales/en.ts b/web/src/locales/en.ts index 86d665914f7..da5341ce1ad 100644 --- a/web/src/locales/en.ts +++ b/web/src/locales/en.ts @@ -2781,6 +2781,15 @@ Best for: Documents with flowing, contextually connected content — such as boo youComFreshnessMonth: 'Past month', youComFreshnessYear: 'Past year', youComApiKeyTip: 'Optional. Leave blank to use the keyless free tier.', + sofyaSearch: 'Sofya', + sofyaSearchDescription: + 'A web search component powered by Sofya. Results carry the content of each result page, or only its search snippet, depending on the search depth. An API Key is required.', + sofyaSearchDepth: 'Search depth', + sofyaSearchDepthTip: + 'Basic returns the content of each result page. Snippets returns the search snippets only, which is faster and costs less.', + sofyaSearchDepthBasic: 'Page content', + sofyaSearchDepthSnippets: 'Snippets only', + sofyaApiKeyTip: 'Required. Create an API Key at sofya.co.', docGenerator: 'Doc Generator', docGeneratorDescription: `Generate a file from Markdown content.`, browser: 'Browser', diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.ts index a78098d8859..9ecb5daabb1 100644 --- a/web/src/locales/zh.ts +++ b/web/src/locales/zh.ts @@ -2405,6 +2405,15 @@ NER:使用 spaCy NER 和基于规则的关键词提取来抽取 Entities 和 R youComFreshnessMonth: '一个月内', youComFreshnessYear: '一年内', youComApiKeyTip: '可选。留空则使用免密钥的免费额度。', + sofyaSearch: 'Sofya', + sofyaSearchDescription: + '基于 Sofya 的网络搜索组件。根据搜索深度,结果附带结果页面的正文内容或仅附带搜索摘要。需要配置 API Key。', + sofyaSearchDepth: '搜索深度', + sofyaSearchDepthTip: + 'Basic 返回每条结果页面的正文内容;Snippets 只返回搜索摘要,速度更快、消耗更少。', + sofyaSearchDepthBasic: '页面正文', + sofyaSearchDepthSnippets: '仅摘要', + sofyaApiKeyTip: '必填。请在 sofya.co 申请 API Key。', docGenerator: '文档生成器', docGeneratorDescription: `从 Markdown 内容生成文件。`, browser: 'Browser', diff --git a/web/src/pages/agent/canvas/node/dropdown/accordion-operators.tsx b/web/src/pages/agent/canvas/node/dropdown/accordion-operators.tsx index 3e44bc01da9..813d5e30780 100644 --- a/web/src/pages/agent/canvas/node/dropdown/accordion-operators.tsx +++ b/web/src/pages/agent/canvas/node/dropdown/accordion-operators.tsx @@ -127,6 +127,7 @@ export function AccordionOperators({ Operator.SearXNG, Operator.KeenableSearch, Operator.YouComSearch, + Operator.SofyaSearch, Operator.DocGenerator, Operator.Browser, ]} diff --git a/web/src/pages/agent/constant/index.tsx b/web/src/pages/agent/constant/index.tsx index 702edf88054..ec806fbb768 100644 --- a/web/src/pages/agent/constant/index.tsx +++ b/web/src/pages/agent/constant/index.tsx @@ -220,6 +220,28 @@ export const initialYouComValues = { }, }; +export enum SofyaSearchDepth { + Basic = 'basic', + Snippets = 'snippets', +} + +export const initialSofyaValues = { + api_key: '', + query: AgentGlobals.SysQuery, + search_depth: SofyaSearchDepth.Basic, + top_n: 10, + outputs: { + formalized_content: { + value: '', + type: 'string', + }, + json: { + value: [], + type: 'Array', + }, + }, +}; + export const initialKeenableValues = { api_key: '', query: AgentGlobals.SysQuery, @@ -775,6 +797,7 @@ export const RestrictedUpstreamMap = { [Operator.SearXNG]: [Operator.Begin, Operator.Retrieval], [Operator.KeenableSearch]: [Operator.Begin, Operator.Retrieval], [Operator.YouComSearch]: [Operator.Begin, Operator.Retrieval], + [Operator.SofyaSearch]: [Operator.Begin, Operator.Retrieval], [Operator.ExeSQL]: [Operator.Begin], [Operator.Switch]: [Operator.Begin], [Operator.WenCai]: [Operator.Begin], @@ -832,6 +855,7 @@ export const NodeMap = { [Operator.SearXNG]: 'ragNode', [Operator.KeenableSearch]: 'ragNode', [Operator.YouComSearch]: 'ragNode', + [Operator.SofyaSearch]: 'ragNode', [Operator.ExeSQL]: 'ragNode', [Operator.Switch]: 'switchNode', [Operator.WenCai]: 'ragNode', diff --git a/web/src/pages/agent/form-sheet/form-config-map.tsx b/web/src/pages/agent/form-sheet/form-config-map.tsx index d3072dd82a4..eba7cd74961 100644 --- a/web/src/pages/agent/form-sheet/form-config-map.tsx +++ b/web/src/pages/agent/form-sheet/form-config-map.tsx @@ -21,6 +21,7 @@ import InvokeForm from '../form/invoke-form'; import IterationForm from '../form/iteration-form'; import IterationStartForm from '../form/iteration-start-from'; import KeenableForm from '../form/keenable-form'; +import SofyaForm from '../form/sofya-form'; import YouComForm from '../form/youcom-form'; import ListOperationsForm from '../form/list-operations-form'; import LoopForm from '../form/loop-form'; @@ -82,6 +83,9 @@ export const FormConfigMap = { [Operator.YouComSearch]: { component: YouComForm, }, + [Operator.SofyaSearch]: { + component: SofyaForm, + }, [Operator.Wikipedia]: { component: WikipediaForm, }, diff --git a/web/src/pages/agent/form/agent-form/tool-popover/tool-command.tsx b/web/src/pages/agent/form/agent-form/tool-popover/tool-command.tsx index d93a215f0bd..3cc7f0655b7 100644 --- a/web/src/pages/agent/form/agent-form/tool-popover/tool-command.tsx +++ b/web/src/pages/agent/form/agent-form/tool-popover/tool-command.tsx @@ -31,6 +31,7 @@ const Menus = [ Operator.SearXNG, Operator.KeenableSearch, Operator.YouComSearch, + Operator.SofyaSearch, Operator.YahooFinance, Operator.PubMed, Operator.BGPT, diff --git a/web/src/pages/agent/form/sofya-form/index.tsx b/web/src/pages/agent/form/sofya-form/index.tsx new file mode 100644 index 00000000000..68090f0b962 --- /dev/null +++ b/web/src/pages/agent/form/sofya-form/index.tsx @@ -0,0 +1,108 @@ +import { FormContainer } from '@/components/form-container'; +import { TopNFormField } from '@/components/top-n-item'; +import { + Form, + FormControl, + FormField, + FormItem, + FormLabel, + FormMessage, +} from '@/components/ui/form'; +import { RAGFlowSelect } from '@/components/ui/select'; +import { useTranslate } from '@/hooks/common-hooks'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { memo, useMemo } from 'react'; +import { useForm, useFormContext } from 'react-hook-form'; +import { z } from 'zod'; +import { SofyaSearchDepth, initialSofyaValues } from '../../constant'; +import { useFormValues } from '../../hooks/use-form-values'; +import { useWatchFormChange } from '../../hooks/use-watch-form-change'; +import { INextOperatorForm } from '../../interface'; +import { buildOutputList } from '../../utils/build-output-list'; +import { ApiKeyField } from '../components/api-key-field'; +import { FormWrapper } from '../components/form-wrapper'; +import { Output } from '../components/output'; +import { QueryVariable } from '../components/query-variable'; + +// Search depth is a user-facing word, so each option carries its own key rather +// than deriving an English label from the enum value. +const SofyaSearchDepthLabelKeys: Record = { + [SofyaSearchDepth.Basic]: 'sofyaSearchDepthBasic', + [SofyaSearchDepth.Snippets]: 'sofyaSearchDepthSnippets', +}; + +export const SofyaFormPartialSchema = { + api_key: z.string().optional(), + search_depth: z.string().optional(), + top_n: z.coerce.number(), +}; + +const FormSchema = z.object({ + query: z.string(), + ...SofyaFormPartialSchema, +}); + +export function SofyaWidgets() { + const { t } = useTranslate('flow'); + const form = useFormContext(); + + const searchDepthOptions = useMemo( + () => + Object.values(SofyaSearchDepth).map((x) => ({ + value: x, + label: t(SofyaSearchDepthLabelKeys[x]), + })), + [t], + ); + + return ( + <> + + ( + + + {t('sofyaSearchDepth')} + + + + + + + )} + /> + + + ); +} + +const SofyaOutputList = buildOutputList(initialSofyaValues.outputs); + +function SofyaForm({ node }: INextOperatorForm) { + const defaultValues = useFormValues(initialSofyaValues, node); + + const form = useForm>({ + defaultValues, + resolver: zodResolver(FormSchema), + }); + + useWatchFormChange(node?.id, form); + + return ( +
+ + + + + + +
+ +
+
+ ); +} + +export default memo(SofyaForm); diff --git a/web/src/pages/agent/form/tool-form/constant.tsx b/web/src/pages/agent/form/tool-form/constant.tsx index 8be86f58b23..936e14e0b9c 100644 --- a/web/src/pages/agent/form/tool-form/constant.tsx +++ b/web/src/pages/agent/form/tool-form/constant.tsx @@ -9,6 +9,7 @@ import GithubForm from './github-form'; import GoogleForm from './google-form'; import GoogleScholarForm from './google-scholar-form'; import KeenableForm from './keenable-form'; +import SofyaForm from './sofya-form'; import YouComForm from './youcom-form'; import PubMedForm from './pubmed-form'; import QueritForm from './querit-form'; @@ -44,4 +45,5 @@ export const ToolFormConfigMap = { [Operator.SearXNG]: SearXNGForm, [Operator.KeenableSearch]: KeenableForm, [Operator.YouComSearch]: YouComForm, + [Operator.SofyaSearch]: SofyaForm, }; diff --git a/web/src/pages/agent/form/tool-form/sofya-form/index.tsx b/web/src/pages/agent/form/tool-form/sofya-form/index.tsx new file mode 100644 index 00000000000..27d80ddb8ea --- /dev/null +++ b/web/src/pages/agent/form/tool-form/sofya-form/index.tsx @@ -0,0 +1,35 @@ +import { FormContainer } from '@/components/form-container'; +import { Form } from '@/components/ui/form'; +import { zodResolver } from '@hookform/resolvers/zod'; +import { memo } from 'react'; +import { useForm } from 'react-hook-form'; +import { z } from 'zod'; +import { FormWrapper } from '../../components/form-wrapper'; +import { SofyaFormPartialSchema, SofyaWidgets } from '../../sofya-form'; +import { useValues } from '../use-values'; +import { useWatchFormChange } from '../use-watch-change'; + +function SofyaForm() { + const values = useValues(); + + const FormSchema = z.object(SofyaFormPartialSchema); + + const form = useForm>({ + defaultValues: values, + resolver: zodResolver(FormSchema), + }); + + useWatchFormChange(form); + + return ( +
+ + + + + +
+ ); +} + +export default memo(SofyaForm); diff --git a/web/src/pages/agent/hooks/use-add-node.ts b/web/src/pages/agent/hooks/use-add-node.ts index 96c80cebbd8..d76f1408a88 100644 --- a/web/src/pages/agent/hooks/use-add-node.ts +++ b/web/src/pages/agent/hooks/use-add-node.ts @@ -32,6 +32,7 @@ import { initialIterationStartValues, initialIterationValues, initialKeenableValues, + initialSofyaValues, initialYouComValues, initialListOperationsValues, initialLoopValues, @@ -176,6 +177,7 @@ export const useInitializeOperatorParams = () => { [Operator.QueritSearch]: initialQueritValues, [Operator.KeenableSearch]: initialKeenableValues, [Operator.YouComSearch]: initialYouComValues, + [Operator.SofyaSearch]: initialSofyaValues, [Operator.UserFillUp]: initialUserFillUpValues, [Operator.StringTransform]: initialStringTransformValues, [Operator.TavilyExtract]: initialTavilyExtractValues, diff --git a/web/src/pages/agent/hooks/use-agent-tool-initial-values.ts b/web/src/pages/agent/hooks/use-agent-tool-initial-values.ts index 91fbd8ea085..e3145aa3bc3 100644 --- a/web/src/pages/agent/hooks/use-agent-tool-initial-values.ts +++ b/web/src/pages/agent/hooks/use-agent-tool-initial-values.ts @@ -70,6 +70,8 @@ export function useAgentToolInitialValues() { return pick(initialValues, 'api_key', 'mode', 'site', 'top_n'); case Operator.YouComSearch: return pick(initialValues, 'api_key', 'freshness', 'top_n'); + case Operator.SofyaSearch: + return pick(initialValues, 'api_key', 'search_depth', 'top_n'); default: return initialValues; diff --git a/web/src/pages/agent/log-sheet/tool-timeline-item.tsx b/web/src/pages/agent/log-sheet/tool-timeline-item.tsx index 234c0a6c736..ebb4a0ea55e 100644 --- a/web/src/pages/agent/log-sheet/tool-timeline-item.tsx +++ b/web/src/pages/agent/log-sheet/tool-timeline-item.tsx @@ -33,6 +33,7 @@ type IToolIcon = | Operator.QueritSearch | Operator.KeenableSearch | Operator.YouComSearch + | Operator.SofyaSearch | Operator.Wikipedia | Operator.YahooFinance | Operator.WenCai diff --git a/web/src/pages/agent/utils/clear-sensitive-fields.test.ts b/web/src/pages/agent/utils/clear-sensitive-fields.test.ts index 67b7e1293aa..0ccb4ae9505 100644 --- a/web/src/pages/agent/utils/clear-sensitive-fields.test.ts +++ b/web/src/pages/agent/utils/clear-sensitive-fields.test.ts @@ -5,6 +5,7 @@ jest.mock('@/constants/agent', () => ({ Google: 'Google', KeenableSearch: 'KeenableSearch', YouComSearch: 'YouComSearch', + SofyaSearch: 'SofyaSearch', BGPT: 'Bing', QueritContents: 'QueritContents', QueritSearch: 'QueritSearch', @@ -146,6 +147,42 @@ describe('clearSensitiveFields', () => { expect(dsl.tools[0].params.api_key).toBe('ydc-tool-secret'); }); + it('clears a Sofya key from a canvas node and from a tool record', () => { + const dsl = { + graph: { + nodes: [ + { + data: { + label: Operator.SofyaSearch, + form: { + api_key: 'sofya-graph-secret', + search_depth: 'basic', + }, + }, + }, + ], + }, + tools: [ + { + component_name: Operator.SofyaSearch, + params: { + api_key: 'sofya-tool-secret', + top_n: 10, + }, + }, + ], + }; + + const sanitized = clearSensitiveFields(dsl); + + expect(sanitized.graph.nodes[0].data.form.api_key).toBe(''); + expect(sanitized.graph.nodes[0].data.form.search_depth).toBe('basic'); + expect(sanitized.tools[0].params.api_key).toBe(''); + expect(sanitized.tools[0].params.top_n).toBe(10); + expect(dsl.graph.nodes[0].data.form.api_key).toBe('sofya-graph-secret'); + expect(dsl.tools[0].params.api_key).toBe('sofya-tool-secret'); + }); + it('does not change standalone graph export behavior for other tools', () => { const dsl = { graph: { diff --git a/web/src/pages/agent/utils/clear-sensitive-fields.ts b/web/src/pages/agent/utils/clear-sensitive-fields.ts index 8fc8f10ec42..795090d6bb0 100644 --- a/web/src/pages/agent/utils/clear-sensitive-fields.ts +++ b/web/src/pages/agent/utils/clear-sensitive-fields.ts @@ -7,6 +7,7 @@ const apiKeyOperators = [ Operator.Google, Operator.KeenableSearch, Operator.YouComSearch, + Operator.SofyaSearch, Operator.BGPT, Operator.QueritContents, Operator.QueritSearch, @@ -15,7 +16,10 @@ const apiKeyOperators = [ // Canvas nodes carry the operator under `data.label` and the key under // `data.form.api_key`, so a graph export has to be sanitized separately from the // agent-tool records above. -const nodeLabelApiKeyOperators: string[] = [Operator.YouComSearch]; +const nodeLabelApiKeyOperators: string[] = [ + Operator.YouComSearch, + Operator.SofyaSearch, +]; function isQueritOperator(value: unknown) { if (typeof value !== 'string') { From e53e5de0cb93eb0d5f93993fe33015192816965a Mon Sep 17 00:00:00 2001 From: jay77721 <164177721+jay77721@users.noreply.github.com> Date: Tue, 8 Sep 2026 12:53:49 +0800 Subject: [PATCH 002/568] fix(parser): recover text_box and nested table/list text in office IR (#19319) --- internal/parser/parser/docx_ir.go | 46 +++++++------- internal/parser/parser/docx_ir_test.go | 77 +++++++++++++++++++++++ internal/parser/parser/pptx_ir.go | 13 ++++ internal/parser/parser/pptx_ir_test.go | 85 ++++++++++++++++++++++++++ internal/parser/parser/pptx_parser.go | 11 ++-- 5 files changed, 206 insertions(+), 26 deletions(-) diff --git a/internal/parser/parser/docx_ir.go b/internal/parser/parser/docx_ir.go index c5a84e22916..71286bea472 100644 --- a/internal/parser/parser/docx_ir.go +++ b/internal/parser/parser/docx_ir.go @@ -73,7 +73,11 @@ func (e docxIRElement) contentRuns() []docxIRRun { return runs } -// contentBlocks decodes Content as block-level elements (text_box type). +// contentBlocks decodes Content as block-level elements (text_box type, +// list-item content, or table-cell content). Blocks may be plain paragraphs +// or compound elements (table, list, nested text_box); callers flatten each +// block via docxElementText so non-paragraph blocks are not silently +// dropped. func (e docxIRElement) contentBlocks() []docxIRElement { var blocks []docxIRElement if len(e.Content) > 0 { @@ -84,7 +88,7 @@ func (e docxIRElement) contentBlocks() []docxIRElement { // docxIRListItem represents one item in an ordered/unordered list. type docxIRListItem struct { - Content []docxIRElement `json:"content"` // block-level content (typically a single Paragraph) + Content []docxIRElement `json:"content"` // block-level content (typically a single Paragraph; may also hold table/list/text_box) Nested *docxIRList `json:"nested,omitempty"` // optional nested sub-list; null/absent when none } @@ -106,7 +110,7 @@ type docxIRRow struct { } type docxIRCell struct { - Content []docxIRElement `json:"content"` // nested paragraphs inside table cell + Content []docxIRElement `json:"content"` // block-level content (typically paragraphs; may also hold list/table) } // joinDOCXIRRuns concatenates inline runs into plain text. Hard line @@ -126,18 +130,16 @@ func joinDOCXIRRuns(runs []docxIRRun) string { } // extractTextFromListItem extracts the plain text content from a list item. -// Each list item contains block-level elements (typically a Paragraph), -// whose text runs are concatenated. Nested sub-lists (multi-level -// bullets/numbered items) are decoded and recursed so their text is not -// silently dropped. Mirrors office_oxide ir::ListItem { content, nested }. +// Each block in the item is flattened via docxElementText so non-paragraph +// blocks (e.g. a table nested in a list item) are not silently dropped. +// Nested sub-lists (multi-level bullets/numbered items) are decoded and +// recursed so their text is not silently dropped. +// Mirrors office_oxide ir::ListItem { content, nested }. func extractTextFromListItem(item docxIRListItem) string { var parts []string for _, el := range item.Content { - if el.Type == "paragraph" || el.Type == "heading" { - t := joinDOCXIRRuns(el.contentRuns()) - if t != "" { - parts = append(parts, t) - } + if t := strings.TrimSpace(docxElementText(el, "\n")); t != "" { + parts = append(parts, t) } } if item.Nested != nil { @@ -154,16 +156,15 @@ func extractTextFromListItem(item docxIRListItem) string { } // extractTextFromBlockElements extracts text from a slice of block-level -// elements (paragraphs/headings), used by text_box and other compound -// element types. +// elements (e.g. the content of a text_box). Each block is flattened via +// docxElementText so non-paragraph blocks (e.g. a table wrapped in a +// text_box, as office_oxide emits for grouped slide shapes) are not +// silently dropped. func extractTextFromBlockElements(blocks []docxIRElement) string { var parts []string for _, el := range blocks { - if el.Type == "paragraph" || el.Type == "heading" { - t := joinDOCXIRRuns(el.contentRuns()) - if t != "" { - parts = append(parts, t) - } + if t := strings.TrimSpace(docxElementText(el, "\n")); t != "" { + parts = append(parts, t) } } if len(parts) == 0 { @@ -172,12 +173,13 @@ func extractTextFromBlockElements(blocks []docxIRElement) string { return strings.TrimSpace(strings.Join(parts, "\n")) } -// joinCellText concatenates all paragraph texts inside a table cell, -// joined by newlines. +// joinCellText concatenates all block texts inside a table cell, joined by +// newlines. Each block is flattened via docxElementText so non-paragraph +// blocks (e.g. a nested list) are not silently dropped. func joinCellText(cell docxIRCell) string { var parts []string for _, el := range cell.Content { - if text := joinDOCXIRRuns(el.contentRuns()); text != "" { + if text := strings.TrimSpace(docxElementText(el, "\n")); text != "" { parts = append(parts, text) } } diff --git a/internal/parser/parser/docx_ir_test.go b/internal/parser/parser/docx_ir_test.go index 416f6899b9d..48b7b9196e5 100644 --- a/internal/parser/parser/docx_ir_test.go +++ b/internal/parser/parser/docx_ir_test.go @@ -244,6 +244,83 @@ func TestExtractTextFromListItem_NestedNull(t *testing.T) { } } +// TestExtractTextFromListItem_NestedTable verifies that a table nested +// inside a list item's content is flattened, not silently dropped. The old +// path only recognized paragraph/heading blocks in item.Content. +func TestExtractTextFromListItem_NestedTable(t *testing.T) { + irJSON := `{"sections":[{"elements":[ + {"type":"list","items":[ + {"content":[ + {"type":"paragraph","content":[{"type":"text","text":"before"}]}, + {"type":"table","rows":[ + {"cells":[ + {"content":[{"type":"paragraph","content":[{"type":"text","text":"c1"}]}]}, + {"content":[{"type":"paragraph","content":[{"type":"text","text":"c2"}]}]} + ]} + ]} + ]} + ]} + ]}]}` + sections := buildDOCXJSONSections(irJSON) + if len(sections) != 1 { + t.Fatalf("expected 1 section, got %d: %+v", len(sections), sections) + } + if got := sections[0]["text"]; got != "before\nc1\nc2" { + t.Errorf("list item with nested table text = %q, want %q", got, "before\nc1\nc2") + } +} + +// TestJoinCellText_NestedList verifies that a list nested inside a table +// cell is flattened, not silently dropped. The old path only recognized +// paragraph runs in cell.Content. +func TestJoinCellText_NestedList(t *testing.T) { + irJSON := `{"sections":[{"elements":[ + {"type":"table","rows":[ + {"cells":[ + {"content":[ + {"type":"paragraph","content":[{"type":"text","text":"head"}]}, + {"type":"list","items":[ + {"content":[{"type":"paragraph","content":[{"type":"text","text":"li1"}]}]}, + {"content":[{"type":"paragraph","content":[{"type":"text","text":"li2"}]}]} + ]} + ]} + ]} + ]} + ]}]}` + var ir docxIRDocument + if err := json.Unmarshal([]byte(irJSON), &ir); err != nil { + t.Fatalf("unmarshal IR: %v", err) + } + cell := ir.Sections[0].Elements[0].Rows[0].Cells[0] + if got := joinCellText(cell); got != "head\nli1\nli2" { + t.Errorf("joinCellText(nested list) = %q, want %q", got, "head\nli1\nli2") + } +} + +// TestBuildDOCXJSONSections_TextBoxTable verifies end-to-end that a table +// wrapped in a text_box (the shape office_oxide emits for grouped slide +// shapes, and a legal DOCX text-box shape) survives into the section +// output. Mirrors the PPTX bwbd.pptx regression at the DOCX layer. +func TestBuildDOCXJSONSections_TextBoxTable(t *testing.T) { + irJSON := `{"sections":[{"elements":[ + {"type":"text_box","content":[ + {"type":"table","rows":[ + {"cells":[ + {"content":[{"type":"paragraph","content":[{"type":"text","text":"Q1"}]}]}, + {"content":[{"type":"paragraph","content":[{"type":"text","text":"A1"}]}]} + ]} + ]} + ]} + ]}]}` + sections := buildDOCXJSONSections(irJSON) + if len(sections) != 1 { + t.Fatalf("expected 1 section, got %d: %+v", len(sections), sections) + } + if got := sections[0]["text"]; got != "Q1\nA1" { + t.Errorf("text_box table text = %q, want %q", got, "Q1\nA1") + } +} + // TestBuildDOCXJSONSections_NestedList verifies end-to-end that a // multi-level list survives into the section output with all levels. func TestBuildDOCXJSONSections_NestedList(t *testing.T) { diff --git a/internal/parser/parser/pptx_ir.go b/internal/parser/parser/pptx_ir.go index a440796ca6b..e0507e53d09 100644 --- a/internal/parser/parser/pptx_ir.go +++ b/internal/parser/parser/pptx_ir.go @@ -62,6 +62,19 @@ func buildPPTXJSONSections(irJSON string) ([]map[string]any, error) { return items, nil } +// itemsAllEmpty reports whether every item carries no extractable text. +// A deck whose IR sections all flatten to "" (e.g. text the IR walker does +// not yet cover) must fall back to PlainText instead of emitting empty +// chunks that the Tokenizer later filters, silently yielding 0 chunks. +func itemsAllEmpty(items []map[string]any) bool { + for _, it := range items { + if text, _ := it["text"].(string); strings.TrimSpace(text) != "" { + return false + } + } + return true +} + // itemsFromPlainText wraps whole-document plain text as a single JSON // item. It salvages a still-readable deck when the structured IR cannot // be used (IR serialization failure or a sectionless IR); a document diff --git a/internal/parser/parser/pptx_ir_test.go b/internal/parser/parser/pptx_ir_test.go index 0444fa25690..7e5d708df47 100644 --- a/internal/parser/parser/pptx_ir_test.go +++ b/internal/parser/parser/pptx_ir_test.go @@ -108,6 +108,61 @@ func TestBuildPPTXJSONSections(t *testing.T) { irJSON: `{"sections":[{"elements":[{"type":"image","data":"aGVsbG8="}]}]}`, wantTexts: []string{""}, }, + { + // bwbd.pptx regression: office_oxide wraps grouped slide shapes + // (graphicFrame tables) in a text_box, so the slide's text_box + // content is a table, not paragraphs. Previously flattened to "". + name: "text_box wrapping table keeps text", + irJSON: `{"sections":[{"elements":[{"type":"text_box","content":[ + {"type":"table","rows":[ + {"cells":[ + {"content":[{"type":"paragraph","content":[{"type":"text","text":"Q1"}]}]}, + {"content":[{"type":"paragraph","content":[{"type":"text","text":"A1"}]}]} + ]} + ]} + ]}]}]}`, + wantTexts: []string{"Q1\nA1"}, + }, + { + // Same flattening path with a list inside the text_box: the + // old paragraph-only walk dropped the whole block. + name: "text_box wrapping list keeps text", + irJSON: `{"sections":[{"elements":[{"type":"text_box","content":[ + {"type":"list","items":[ + {"content":[{"type":"paragraph","content":[{"type":"text","text":"li1"}]}]}, + {"content":[{"type":"paragraph","content":[{"type":"text","text":"li2"}]}]} + ]} + ]}]}]}`, + wantTexts: []string{"li1\nli2"}, + }, + { + // Nested text boxes recurse through the same walker. + name: "nested text_box keeps text", + irJSON: `{"sections":[{"elements":[{"type":"text_box","content":[ + {"type":"paragraph","content":[{"type":"text","text":"outer"}]}, + {"type":"text_box","content":[ + {"type":"paragraph","content":[{"type":"text","text":"inner"}]} + ]} + ]}]}]}`, + wantTexts: []string{"outer\ninner"}, + }, + { + // Table cell holding a list: joinCellText must recurse instead + // of reading paragraph runs only. + name: "table cell wrapping list keeps text", + irJSON: `{"sections":[{"elements":[{"type":"table","rows":[ + {"cells":[ + {"content":[ + {"type":"paragraph","content":[{"type":"text","text":"head"}]}, + {"type":"list","items":[ + {"content":[{"type":"paragraph","content":[{"type":"text","text":"li1"}]}]}, + {"content":[{"type":"paragraph","content":[{"type":"text","text":"li2"}]}]} + ]} + ]} + ]} + ]}]}]}`, + wantTexts: []string{"head\nli1\nli2"}, + }, { name: "invalid JSON", irJSON: "{not json", @@ -149,6 +204,36 @@ func TestBuildPPTXJSONSections(t *testing.T) { } } +// TestItemsAllEmpty pins the all-empty fallback gate: empty and whitespace +// items trigger the PlainText salvage, any non-empty item does not. +func TestItemsAllEmpty(t *testing.T) { + tests := []struct { + name string + items []map[string]any + want bool + }{ + {name: "nil", items: nil, want: true}, + {name: "empty", items: []map[string]any{}, want: true}, + { + name: "all empty", + items: []map[string]any{{"text": ""}, {"text": " \n "}}, + want: true, + }, + { + name: "one non-empty", + items: []map[string]any{{"text": ""}, {"text": "hello"}}, + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := itemsAllEmpty(tt.items); got != tt.want { + t.Errorf("itemsAllEmpty = %v, want %v", got, tt.want) + } + }) + } +} + // TestItemsFromPlainText pins the whole-document plain-text salvage used // when the structured IR is unusable: non-empty text becomes a single // trimmed item; blank text yields an empty, non-nil slice. diff --git a/internal/parser/parser/pptx_parser.go b/internal/parser/parser/pptx_parser.go index 149567a29d5..059cd2f97b7 100644 --- a/internal/parser/parser/pptx_parser.go +++ b/internal/parser/parser/pptx_parser.go @@ -168,10 +168,13 @@ func (p *PPTXParser) ParseWithResult(ctx context.Context, filename string, data if err != nil { return ParseResult{Err: err} } - if len(items) == 0 { - // A deck whose IR carries no sections at all: keep the - // whole-document text as a single item so a still-readable - // file yields one chunk instead of none. + if len(items) == 0 || itemsAllEmpty(items) { + // A deck whose IR carries no sections at all, or whose sections + // all flatten to empty text (text the IR walker does not cover): + // keep the whole-document text as a single item so a + // still-readable file yields content instead of none. Without + // the all-empty check, empty items flow to the Tokenizer, which + // filters them as empty text, silently yielding 0 chunks. text, perr := doc.PlainText() if perr != nil { return ParseResult{Err: fmt.Errorf("presentation plain-text: %w", perr)} From 545753e248f829ec19982e102bd6da57e5b8ae33 Mon Sep 17 00:00:00 2001 From: jay77721 <164177721+jay77721@users.noreply.github.com> Date: Tue, 8 Sep 2026 12:53:57 +0800 Subject: [PATCH 003/568] fix(memory): align extracted message document id with message_id (#19326) --- internal/service/memory_extractor.go | 34 +++------------- internal/service/memory_extractor_test.go | 49 ++++++----------------- 2 files changed, 18 insertions(+), 65 deletions(-) diff --git a/internal/service/memory_extractor.go b/internal/service/memory_extractor.go index 67273cbac52..fc63fa879db 100644 --- a/internal/service/memory_extractor.go +++ b/internal/service/memory_extractor.go @@ -36,7 +36,6 @@ package service import ( "context" - "crypto/sha256" "encoding/json" "errors" "fmt" @@ -247,30 +246,20 @@ func (s *MemoryMessageService) extractByLLM(ctx context.Context, mem *CreateMemo // logical message fields are set here; the doc engine maps them to // storage fields (including tokenization) at insert time. func buildExtractedMessage(messageID, sourceID int64, memoryID string, msg MemoryMessage, item extractedMemory, now time.Time) map[string]any { - validAt, hasExplicitValidAt := normalizeMemoryTime(item.ValidAt) - if !hasExplicitValidAt { + validAt, ok := normalizeMemoryTime(item.ValidAt) + if !ok { validAt = now.Format(memoryTimeLayout) } - invalidAt, hasExplicitInvalidAt := normalizeMemoryTime(item.InvalidAt) - if strings.TrimSpace(item.InvalidAt) != "" { - if !hasExplicitInvalidAt { - invalidAt = now.Format(memoryTimeLayout) - } + invalidAt, ok := normalizeMemoryTime(item.InvalidAt) + if strings.TrimSpace(item.InvalidAt) != "" && !ok { + invalidAt = now.Format(memoryTimeLayout) } var storedInvalidAt any if invalidAt != "" { storedInvalidAt = invalidAt } - fingerprintValidAt := "" - if hasExplicitValidAt { - fingerprintValidAt = validAt - } - fingerprintInvalidAt := "" - if hasExplicitInvalidAt { - fingerprintInvalidAt = invalidAt - } return map[string]any{ - "id": extractedMessageDocumentID(memoryID, sourceID, item.MessageType, item.Content, fingerprintValidAt, fingerprintInvalidAt), + "id": fmt.Sprintf("%s_%d", memoryID, messageID), "message_id": messageID, "message_type": item.MessageType, "source_id": sourceID, @@ -286,17 +275,6 @@ func buildExtractedMessage(messageID, sourceID int64, memoryID string, msg Memor } } -// extractedMessageDocumentID returns the chunk-store id for an extracted item. -// sourceID identifies the immutable raw message, while the normalized content -// fingerprint distinguishes multiple extracts from that source. Only explicit, -// parseable timestamps participate, so a runtime fallback cannot change the -// identity on retry. Repeated task executions therefore upsert the same chunk -// instead of creating duplicates. -func extractedMessageDocumentID(memoryID string, sourceID int64, messageType, content, validAt, invalidAt string) string { - fingerprint := sha256.Sum256([]byte(strings.Join([]string{messageType, content, validAt, invalidAt}, "\x00"))) - return fmt.Sprintf("%s_%d_%x", memoryID, sourceID, fingerprint[:8]) -} - // parseMemoryExtraction ports memory.utils.msg_util.get_json_result_from_llm_response // plus the per-type flattening in extract_by_llm. Only the configured // extract types are collected; unparseable responses yield an empty list. diff --git a/internal/service/memory_extractor_test.go b/internal/service/memory_extractor_test.go index 8357b107741..fd305ffc1e6 100644 --- a/internal/service/memory_extractor_test.go +++ b/internal/service/memory_extractor_test.go @@ -99,45 +99,20 @@ func TestBuildExtractedMessageValidAtSemantics(t *testing.T) { } } -// TestBuildExtractedMessageUsesStableDocumentIDAcrossRetries ensures fallback -// timestamps do not become part of the chunk-store identity. A retry may run -// at a different time and allocate a new logical message id, but it must still -// overwrite the same extracted document. -func TestBuildExtractedMessageUsesStableDocumentIDAcrossRetries(t *testing.T) { +// TestBuildExtractedMessageUsesStandardDocumentID ensures extracted items +// use the standard memoryID_messageID identity expected by GetMessageContent. +func TestBuildExtractedMessageUsesStandardDocumentID(t *testing.T) { msg := MemoryMessage{UserID: "u1", AgentID: "a1", SessionID: "s1"} - firstAttempt := time.Date(2026, 8, 20, 10, 5, 0, 0, time.Local) - retryAttempt := firstAttempt.Add(10 * time.Second) - - for _, test := range []struct { - name string - item extractedMemory - }{ - { - name: "omitted valid at", - item: extractedMemory{MessageType: "fact", Content: "likes coffee"}, - }, - { - name: "invalid timestamps", - item: extractedMemory{ - MessageType: "fact", - Content: "likes coffee", - ValidAt: "not a timestamp", - InvalidAt: "also not a timestamp", - }, - }, - } { - t.Run(test.name, func(t *testing.T) { - first := buildExtractedMessage(8, 42, "mem-1", msg, test.item, firstAttempt) - retry := buildExtractedMessage(9, 42, "mem-1", msg, test.item, retryAttempt) + now := time.Date(2026, 8, 20, 10, 5, 0, 0, time.Local) + item := extractedMemory{ + MessageType: "fact", + Content: "likes coffee", + } - firstID, ok := first["id"].(string) - if !ok || firstID == "" { - t.Fatalf("first extracted message id = %#v, want a stable non-empty string", first["id"]) - } - if got, ok := retry["id"].(string); !ok || got != firstID { - t.Fatalf("retry extracted message id = %#v, want %q", retry["id"], firstID) - } - }) + extracted := buildExtractedMessage(8, 42, "mem-1", msg, item, now) + gotID, ok := extracted["id"].(string) + if !ok || gotID != "mem-1_8" { + t.Fatalf("extracted message id = %#v, want %q", extracted["id"], "mem-1_8") } } From 6de46a233c884bbc898b0cacc7ebed1391d47b3d Mon Sep 17 00:00:00 2001 From: xugangqiang Date: Tue, 8 Sep 2026 12:54:10 +0800 Subject: [PATCH 004/568] feat(deepdoc): switch in-process Go backend from .onnx to FlatBuffer (.ort) models (#19318) --- build.sh | 12 ++- internal/common/environments.go | 27 +++--- internal/deepdoc/native/det_core.go | 2 +- internal/deepdoc/native/dla.go | 2 +- .../deepdoc/native/native_integration_test.go | 26 +++--- internal/deepdoc/native/ocr_rec.go | 6 +- internal/deepdoc/native/ort_model_test.go | 90 +++++++++++++++++++ internal/deepdoc/native/tsr.go | 2 +- 8 files changed, 138 insertions(+), 29 deletions(-) create mode 100644 internal/deepdoc/native/ort_model_test.go diff --git a/build.sh b/build.sh index ba2a43a2670..739dea347f3 100755 --- a/build.sh +++ b/build.sh @@ -681,11 +681,21 @@ run_native_tests() { # in Go, which the detector covers. CGO_ENABLED=1 is required for both the build # and the race runtime. run_native_integration_tests() { + # Optional isolation: NATIVE_TEST_RUN forwards a -run filter and + # NATIVE_TEST_V adds -v so a single native test can be exercised in + # isolation (e.g. `NATIVE_TEST_RUN='TestNativeLoadsOrtModels$' NATIVE_TEST_V=1`). + local native_run_filter=() + if [ -n "${NATIVE_TEST_RUN:-}" ]; then + native_run_filter+=(-run "${NATIVE_TEST_RUN}") + fi + if [ -n "${NATIVE_TEST_V:-}" ]; then + native_run_filter+=(-v) + fi print_section "Running native integration tests (golden/comparison, no race)" ( cd "$PROJECT_ROOT" && \ GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \ CGO_ENABLED=1 \ - go test -tags "cgo static integration fetch_testdata" -count=1 ./internal/deepdoc/native/... ) + go test -tags "cgo static integration fetch_testdata" -count=1 "${native_run_filter[@]}" ./internal/deepdoc/native/... ) print_section "Running native integration concurrency tests (race detector on)" ( cd "$PROJECT_ROOT" && \ diff --git a/internal/common/environments.go b/internal/common/environments.go index a54b3b37d05..16bf2b31a95 100644 --- a/internal/common/environments.go +++ b/internal/common/environments.go @@ -226,19 +226,26 @@ const ( ) // DeepDocModelFiles is the single source of truth for the weights the -// in-process (Go) DeepDoc backend and the Python DeepDoc service both -// require. cmd/ resolves the model directory against it; infnative -// validates file presence against it. Order is insignificant (callers do -// set-membership checks); keep it stable so logs and diffs stay readable. +// in-process (Go) DeepDoc backend requires to serve. The Go backend consumes +// the FlatBuffer (.ort) serialization — the static ONNX Runtime build linked +// into the Go binary supports .ort only, not the protobuf .onnx format. The +// Python DeepDoc service keeps the legacy .onnx files and lists them +// independently (see deepdoc/server/download_deps.py), so this slice must NOT +// re-add the .onnx names; it is the Go presence check, not a shared list. +// cmd/ resolves the model directory against it; the native analyzer validates +// file presence against it via HasModelFiles. Order is insignificant (callers +// do set-membership checks); keep it stable so logs and diffs stay readable. // // External consumers that re-list these names must stay in sync: -// - .github/workflows/deepdoc-drift.yml (MODEL_FILES) -// - deepdoc/server/download_deps.py (FILES) +// - ragflow_deps/download_deps.py snapshots the whole InfiniFlow/deepdoc repo +// (so .ort lands in the model dir automatically — no FILES edit needed); +// - deepdoc/server/download_deps.py (the Python-only Dockerfile_deepdoc_oss +// image) keeps the .onnx list and must NOT be changed to .ort. var DeepDocModelFiles = []string{ - "det.onnx", - "layout.onnx", - "tsr.onnx", - "rec.onnx", + "det.ort", + "layout.ort", + "tsr.ort", + "rec.ort", "ocr.res", } diff --git a/internal/deepdoc/native/det_core.go b/internal/deepdoc/native/det_core.go index 960f72a9e38..0e6f7160763 100644 --- a/internal/deepdoc/native/det_core.go +++ b/internal/deepdoc/native/det_core.go @@ -102,7 +102,7 @@ func getDetSession(modelPath string, rh, rw int64) (*session, func(), error) { // extraction uses the pure-Go connected-components backend. func RunDet(ctx context.Context, modelDir string, img *Image) (DetResult, error) { blob, rh, rw, sh, sw := detPreprocess(img) - sess, release, e := getDetSession(filepath.Join(modelDir, "det.onnx"), int64(rh), int64(rw)) + sess, release, e := getDetSession(filepath.Join(modelDir, "det.ort"), int64(rh), int64(rw)) if e != nil { return DetResult{}, e } diff --git a/internal/deepdoc/native/dla.go b/internal/deepdoc/native/dla.go index e8147596ce5..856ff1f1dd2 100644 --- a/internal/deepdoc/native/dla.go +++ b/internal/deepdoc/native/dla.go @@ -59,7 +59,7 @@ func RunDLA(ctx context.Context, modelDir string, img *Image) (DLAResult, error) blob, sf := dlaPreprocess(img) // 0 → all cores, matching deepdoc's Python onnxruntime for bit-stable // parity (no contour extraction in the DLA Run path). - sess, release, err := getModelSession(filepath.Join(modelDir, "layout.onnx"), "images", + sess, release, err := getModelSession(filepath.Join(modelDir, "layout.ort"), "images", []int64{1, 3, dlaInputSize, dlaInputSize}, "output0", []int64{1, dlaMaxBoxes, 6}, 0) if err != nil { diff --git a/internal/deepdoc/native/native_integration_test.go b/internal/deepdoc/native/native_integration_test.go index 0c655d0df16..cb23a526952 100644 --- a/internal/deepdoc/native/native_integration_test.go +++ b/internal/deepdoc/native/native_integration_test.go @@ -2,13 +2,15 @@ package native -// Integration tests run the real ONNX models on the committed test crops and -// compare the Go output against golden JSON produced by the Python reference -// scripts (ref_dla.py / ref_tsr.py / ref_ocr_rec.py). They require MODEL_DIR -// (the DeepDoc model directory: layout.onnx, tsr.onnx, rec.onnx, ocr.res) and a -// usable ONNX Runtime. ONNX Runtime is linked statically (libonnxruntime.a) -// and resolved via dlopen(NULL) from the running binary, so no ORT_LIB / .so -// is needed. +// Integration tests run the real FlatBuffer (.ort) models on the committed test +// crops and compare the Go output against golden JSON produced by the Python +// reference scripts (ref_dla.py / ref_tsr.py / ref_ocr_rec.py). They require +// MODEL_DIR (the DeepDoc model directory: layout.ort, tsr.ort, rec.ort, ocr.res) +// and a usable ONNX Runtime. ONNX Runtime is linked statically +// (libonnxruntime.a) and resolved via dlopen(NULL) from the running binary, so +// no ORT_LIB / .so is needed. The Go backend consumes .ort only (the static +// build drops the protobuf .onnx parser); the .onnx weights remain on the +// Python side. // // Run with: // MODEL_DIR=... go test -tags integration ./native/... @@ -68,11 +70,11 @@ func skipIfNoModels(t *testing.T) { // and regenerate every golden fixture against the new snapshot in the same // change (see /tmp/gen_corpus.py and ref_*.py). var modelSnapshotHashes = map[string]string{ - "det.onnx": "30a86f5731181461d08021402766601e4302a9b9b9666be8aff402696339cdff", - "layout.onnx": "de401c03ee30b1c120416dc06f0705237f0c36d3cdb692c9bfefe8a8f98a4b70", - "tsr.onnx": "1585f88015c60209f16a079a26d944afca790ab7022fe7d0574113ccb9a6f9b4", - "rec.onnx": "1c7cf60de2afd728d512f4190cf37455092b45f06175365c6fc58d8cd7e2a68b", - "ocr.res": "28b2362ad4ab2dc38769aa72feb535e3a9ddb3fd2a7585a05920e6393b1dc7f7", + "det.ort": "fd62614cbae0b073aa203b2393081e641826ecfc85414669458506d91e23c095", + "layout.ort": "55e3e5743ba2f2a03879578ac818089afa32bdedda51159d340bc2eec968b030", + "tsr.ort": "24930ee6d025dc8e5c17587713d74a7d665d3ca8a464df015afb6e939af0d2f7", + "rec.ort": "a6eb83a8943d2dca6de8e1393420904bddd4dded455d72ca177ade63b56533d0", + "ocr.res": "28b2362ad4ab2dc38769aa72feb535e3a9ddb3fd2a7585a05920e6393b1dc7f7", } func sha256File(path string) (string, error) { diff --git a/internal/deepdoc/native/ocr_rec.go b/internal/deepdoc/native/ocr_rec.go index a4532a1ae6b..e2bb8083a08 100644 --- a/internal/deepdoc/native/ocr_rec.go +++ b/internal/deepdoc/native/ocr_rec.go @@ -118,7 +118,7 @@ func RunOCRRecBatchReal(ctx context.Context, modelDir string, imgs []*Image) ([] // 0 → all cores, matching deepdoc's Python onnxruntime for bit-stable // parity (no contour extraction in the OCR-rec Run path). - sess, release, err := getRecSession(filepath.Join(modelDir, "rec.onnx"), "x", + sess, release, err := getRecSession(filepath.Join(modelDir, "rec.ort"), "x", []int64{int64(n), 3, recH, int64(imgW)}, "softmax_11.tmp_0", 0) if err != nil { return nil, err @@ -161,7 +161,7 @@ func recognizeLine(ctx context.Context, modelDir string, img *Image, maxWhRatio blob := ocrRecPreprocess(img, resizedW, imgW) // 0 → all cores, matching deepdoc's Python onnxruntime for bit-stable // parity (no contour extraction in the OCR-rec Run path). - sess, release, err := getRecSession(filepath.Join(modelDir, "rec.onnx"), "x", + sess, release, err := getRecSession(filepath.Join(modelDir, "rec.ort"), "x", []int64{recMaxBatch, 3, recH, int64(imgW)}, "softmax_11.tmp_0", 0) if err != nil { return OCRRecResult{}, err @@ -289,7 +289,7 @@ func (r OCRRecResult) Wire() string { return string(out) } -// recSession runs rec.onnx, whose output sequence length is dynamic: it scales +// recSession runs rec.ort, whose output sequence length is dynamic: it scales // with the input width (≈ width/8), so a fixed-shape AdvancedSession cannot be // pre-sized per width and even a width-matched session would still emit a // varying seq length. Instead we use a DynamicAdvancedSession and pass a nil diff --git a/internal/deepdoc/native/ort_model_test.go b/internal/deepdoc/native/ort_model_test.go new file mode 100644 index 00000000000..cfd7eae144e --- /dev/null +++ b/internal/deepdoc/native/ort_model_test.go @@ -0,0 +1,90 @@ +//go:build cgo && integration + +package native + +import ( + "image" + "image/color" + "io" + "os" + "path/filepath" + "testing" +) + +// TestNativeLoadsOrtModels proves the Go in-process DeepDoc backend consumes the +// FlatBuffer (.ort) model format, while the Python DeepDoc service keeps the +// legacy .onnx files. This is the contract: Go loads .ort, Python loads .onnx. +// +// It stages a model directory containing ONLY the .ort weights (mirroring a +// Go-only deployment where the Python .onnx copy is absent) and runs every +// recognizer against it. Each recognizer MUST succeed: before the loader is +// switched to .ort, get*Session opens det.onnx/layout.onnx/tsr.onnx/rec.onnx — +// which are absent, so the run errors and this test is RED until the switch +// lands. After the switch the loader opens det.ort/layout.ort/tsr.ort/rec.ort, +// which are present, so every recognizer runs to completion and the test goes +// GREEN. +func TestNativeLoadsOrtModels(t *testing.T) { + skipIfNoModels(t) + src := os.Getenv("MODEL_DIR") + + ortOnly := t.TempDir() + for _, name := range []string{"det.ort", "layout.ort", "tsr.ort", "rec.ort", "ocr.res"} { + if err := copyFile(filepath.Join(src, name), filepath.Join(ortOnly, name)); err != nil { + t.Fatalf("stage %s: %v", name, err) + } + } + + if err := InitORT(); err != nil { + t.Fatalf("InitORT: %v", err) + } + + img := solidImage(256, 256) + nimg, err := FromImage(img) + if err != nil { + t.Fatalf("FromImage: %v", err) + } + + // Det must load det.ort (not det.onnx) and run to completion. + if _, e := RunDet(t.Context(), ortOnly, nimg); e != nil { + t.Fatalf("RunDet must load det.ort and succeed on the .ort-only directory, got: %v", e) + } + // Layout/DLA must load layout.ort. + if _, e := RunDLA(t.Context(), ortOnly, nimg); e != nil { + t.Fatalf("RunDLA must load layout.ort and succeed on the .ort-only directory, got: %v", e) + } + // TSR must load tsr.ort. + if _, e := RunTSR(t.Context(), ortOnly, nimg); e != nil { + t.Fatalf("RunTSR must load tsr.ort and succeed on the .ort-only directory, got: %v", e) + } + // OCR-rec must load rec.ort. + if _, e := RunOCRRec(t.Context(), ortOnly, nimg); e != nil { + t.Fatalf("RunOCRRec must load rec.ort and succeed on the .ort-only directory, got: %v", e) + } +} + +// solidImage returns a w×h mid-gray RGBA image so preprocessing has +// non-degenerate input without depending on fetched test fixtures. +func solidImage(w, h int) *image.RGBA { + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + img.Set(x, y, color.Gray{Y: 128}) + } + } + return img +} + +func copyFile(src, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + out, err := os.Create(dst) + if err != nil { + return err + } + defer out.Close() + _, err = io.Copy(out, in) + return err +} diff --git a/internal/deepdoc/native/tsr.go b/internal/deepdoc/native/tsr.go index be37be7a59b..99f7d490e20 100644 --- a/internal/deepdoc/native/tsr.go +++ b/internal/deepdoc/native/tsr.go @@ -46,7 +46,7 @@ func RunTSR(ctx context.Context, modelDir string, img *Image) (TSRResult, error) blob, sf := tsrPreprocess(img) // 0 → all cores, matching deepdoc's Python onnxruntime for bit-stable // parity (no contour extraction in the TSR Run path). - sess, release, err := getModelSession(filepath.Join(modelDir, "tsr.onnx"), "images", + sess, release, err := getModelSession(filepath.Join(modelDir, "tsr.ort"), "images", []int64{1, 3, tsrInputSize, tsrInputSize}, "output0", []int64{1, 11, tsrCandidates}, 0) if err != nil { From 7b01906d459beaf3295c674dae1c1114ebde9ccf Mon Sep 17 00:00:00 2001 From: buua436 Date: Tue, 8 Sep 2026 13:23:28 +0800 Subject: [PATCH 005/568] fix: filter structure alteration by document products (#19346) --- api/apps/services/dataset_api_service.py | 25 +++++++++- .../test_dataset_api_service_list_datasets.py | 46 +++++++++++++++++++ 2 files changed, 70 insertions(+), 1 deletion(-) diff --git a/api/apps/services/dataset_api_service.py b/api/apps/services/dataset_api_service.py index 69cc48960af..f454142001c 100644 --- a/api/apps/services/dataset_api_service.py +++ b/api/apps/services/dataset_api_service.py @@ -2479,6 +2479,26 @@ async def _current_chunk_doc_ids(index_nm, dataset_id: str, doc_ids: set[str]) - ) +async def _current_structure_product_doc_ids(index_nm, dataset_id: str, kind: str, doc_ids: set[str]) -> set[str]: + """Return documents that have produced a document-scoped structure graph.""" + if not doc_ids: + return set() + stored_kinds = sorted(_ALTERATION_ELIGIBLE_TEMPLATE_KINDS.get(kind) or {kind}) + return await _involved_doc_ids_paged( + index_nm, + dataset_id, + { + "doc_id": sorted(doc_ids), + "scope_kwd": ["doc"], + "knowledge_graph_kwd": ["entity", "relation"], + "compilation_template_kind_kwd": stored_kinds, + }, + "doc_id", + from_list=False, + raise_on_error=True, + ) + + async def _involved_doc_ids_for_kind(index_nm, dataset_id: str, kind: str, tenant_id: str, wiki_map_state: dict | None = None) -> set: """Gather the doc ids baked into the compiled product for ``kind``.""" if kind == "wiki": @@ -2575,11 +2595,14 @@ async def _get_alteration(dataset_id: str, tenant_id: str, kind: str): eligible_before_chunk_filter = len(eligible_doc_ids) chunk_doc_ids = await _current_chunk_doc_ids(index_nm, dataset_id, eligible_doc_ids) eligible_doc_ids &= chunk_doc_ids + product_doc_ids = await _current_structure_product_doc_ids(index_nm, dataset_id, kind, eligible_doc_ids) + eligible_doc_ids &= product_doc_ids logging.debug( - "alteration: structure chunk eligibility kind=%s kb=%s before=%d after=%d", + "alteration: structure eligibility kind=%s kb=%s before=%d after_chunks=%d after_products=%d", kind, dataset_id, eligible_before_chunk_filter, + len(chunk_doc_ids), len(eligible_doc_ids), ) wiki_map_state = None diff --git a/test/unit_test/api/apps/services/test_dataset_api_service_list_datasets.py b/test/unit_test/api/apps/services/test_dataset_api_service_list_datasets.py index 8e021165efd..d04f7a9e734 100644 --- a/test/unit_test/api/apps/services/test_dataset_api_service_list_datasets.py +++ b/test/unit_test/api/apps/services/test_dataset_api_service_list_datasets.py @@ -503,6 +503,52 @@ async def _paged(*_args, **_kwargs): await module._current_chunk_doc_ids("tenant-index", "kb-1", {"doc-1"}) +@pytest.mark.asyncio +async def test_current_structure_product_doc_ids_only_returns_document_scoped_products(monkeypatch): + module, _, _ = _load_list_datasets_module( + monkeypatch, + kbs=[], + parsing_status_by_kb={}, + ) + + captured = {} + + async def _paged(_index, dataset_id, condition, field, from_list, *, raise_on_error): + captured.update(dataset_id=dataset_id, condition=condition, field=field, from_list=from_list) + assert raise_on_error is True + return {"doc-with-product"} + + monkeypatch.setattr(module, "_involved_doc_ids_paged", _paged) + + result = await module._current_structure_product_doc_ids( + "tenant-index", + "kb-1", + "graph", + {"doc-with-product", "doc-without-product"}, + ) + + assert result == {"doc-with-product"} + assert captured == { + "dataset_id": "kb-1", + "condition": { + "doc_id": ["doc-with-product", "doc-without-product"], + "scope_kwd": ["doc"], + "knowledge_graph_kwd": ["entity", "relation"], + "compilation_template_kind_kwd": ["knowledge_graph"], + }, + "field": "doc_id", + "from_list": False, + } + + await module._current_structure_product_doc_ids( + "tenant-index", + "kb-1", + "tree", + {"doc-with-product"}, + ) + assert captured["condition"]["compilation_template_kind_kwd"] == ["page_index", "tree"] + + @pytest.mark.asyncio async def test_wiki_involved_ids_use_active_map_state_when_pages_are_missing(monkeypatch): """Use MAP provenance even when a participating document has no page row.""" From 042d11f9efa90849a8857cd67d0d888478d883d3 Mon Sep 17 00:00:00 2001 From: chanx <1243304602@qq.com> Date: Tue, 8 Sep 2026 13:23:31 +0800 Subject: [PATCH 006/568] fix(web): disable textarea resizing in agent note node (#19349) --- web/src/pages/agent/canvas/node/note-node/index.tsx | 1 + 1 file changed, 1 insertion(+) diff --git a/web/src/pages/agent/canvas/node/note-node/index.tsx b/web/src/pages/agent/canvas/node/note-node/index.tsx index 67649a4effb..9293c4fb118 100644 --- a/web/src/pages/agent/canvas/node/note-node/index.tsx +++ b/web/src/pages/agent/canvas/node/note-node/index.tsx @@ -106,6 +106,7 @@ function NoteNode({ - - - - )} - /> + + + )} {mode === AgentDialogueMode.Webhook && } {mode !== AgentDialogueMode.Webhook && ( From 347d0827a0fe1ce1f5f2bf98d053701345fc9493 Mon Sep 17 00:00:00 2001 From: euvre <93761161+euvre@users.noreply.github.com> Date: Thu, 10 Sep 2026 01:22:43 -0700 Subject: [PATCH 072/568] fix(ingestion): allow re-parsing a document whose parse was canceled at progress 0 (#19258) --- .../ingestion/service/ingestion_service.go | 73 +++++++- internal/service/ingestion_task_service.go | 164 +++++++++++++++++- .../service/ingestion_task_service_test.go | 103 ++++++++++- 3 files changed, 319 insertions(+), 21 deletions(-) diff --git a/internal/ingestion/service/ingestion_service.go b/internal/ingestion/service/ingestion_service.go index f82719fe94a..921341f3225 100644 --- a/internal/ingestion/service/ingestion_service.go +++ b/internal/ingestion/service/ingestion_service.go @@ -695,10 +695,31 @@ func (e *Ingestor) executeTaskWithHeartbeat(ctx context.Context, taskCtx *taskpk }) } -// markStopped transitions the task to STOPPED (terminal). It first calls -// RequestStop to handle RUNNING → STOPPING, then MarkStopped for the final -// STOPPING → STOPPED transition. Finally it cleans up the Redis cancel flag -// so that a future retry of the same task does not immediately re-cancel. +// ownsTaskRun reports whether the calling run still owns the task: a newer +// run (created by a supersede/re-parse) bumps the run counter, so a mismatch +// means this run's terminal write must be skipped. A run whose counter could +// not be read (myRun <= 0) conservatively keeps ownership. Uses a detached +// context: it is called from failure/cancel paths whose context is typically +// already cancelled. +func (e *Ingestor) ownsTaskRun(taskID string, myRun int) bool { + if myRun <= 0 { + return true + } + ctx, cancel := context.WithTimeout(context.WithoutCancel(e.ctx), 2*time.Second) + defer cancel() + current, ok := e.ingestionTaskSvc.CurrentRunCount(ctx, taskID) + if !ok { + return true + } + return current == myRun +} + +// markStopped transitions the task to STOPPED (terminal). A RUNNING task +// first goes through RequestStop (RUNNING → STOPPING); a STOPPING task is +// settled directly; any other status (terminal, or CREATED/SCHEDULED because +// a supersede re-armed the task for a newer run) is treated as settled with +// nothing to finalize. Finally it cleans up the Redis cancel flag so that a +// future retry of the same task does not immediately re-cancel. // The caller's context is detached before touching the DB: markStopped runs // on failure/cancel/shutdown paths whose context is typically already // cancelled, and a contaminated context would make the terminal write fail @@ -706,10 +727,29 @@ func (e *Ingestor) executeTaskWithHeartbeat(ctx context.Context, taskCtx *taskpk func (e *Ingestor) markStopped(ctx context.Context, taskID string) bool { ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer cancel() - if _, err := e.ingestionTaskSvc.RequestStop(ctx, taskID); err != nil { - common.Error(fmt.Sprintf("markStopped: RequestStop task %s: %v", taskID, err), err) + // Only a RUNNING/STOPPING task still belongs to this run. A task in + // CREATED/SCHEDULED here was re-armed for a newer run by a supersede + // (re-parse of a canceled document); finalizing it would kill the + // replacement run before it starts, so treat it as already settled. + // Terminal statuses need no work either. + task, err := e.ingestionTaskSvc.GetTask(ctx, taskID) + if err != nil { + common.Error(fmt.Sprintf("markStopped: load task %s: %v", taskID, err), err) return false } + switch task.Status { + case common.RUNNING: + if _, err := e.ingestionTaskSvc.RequestStop(ctx, taskID); err != nil { + common.Error(fmt.Sprintf("markStopped: RequestStop task %s: %v", taskID, err), err) + return false + } + case common.STOPPING: + default: + // COMPLETED/STOPPED/FAILED: already terminal. CREATED/SCHEDULED: + // re-armed by a newer run - nothing this run may finalize. + common.Info(fmt.Sprintf("markStopped: task %s is %s; nothing to finalize for this run", taskID, task.Status)) + return true + } if err := e.ingestionTaskSvc.MarkStopped(ctx, taskID); err != nil { common.Error(fmt.Sprintf("markStopped: MarkStopped task %s: %v", taskID, err), err) return false @@ -772,6 +812,11 @@ func (e *Ingestor) runTask(ctx context.Context, task *entity.IngestionTask) bool } return ok } + // Capture this run's counter: if a re-parse supersedes this run (the task + // is force-finalized and re-armed while this worker is still inside a + // non-cancellable section), a newer run bumps the counter and this run + // must not overwrite the newer run's terminal state or document progress. + myRun, _ := e.ingestionTaskSvc.CurrentRunCount(dbCtx, task.ID) checkpointExists := e.checkpointExists if checkpointExists == nil { checkpointExists = canvas.RedisCheckpointExists @@ -819,6 +864,10 @@ func (e *Ingestor) runTask(ctx context.Context, task *entity.IngestionTask) bool return false } common.Info(fmt.Sprintf("Task %s cancelled during pipeline", task.ID)) + if !e.ownsTaskRun(task.ID, myRun) { + common.Info(fmt.Sprintf("Task %s run %d superseded by a newer run; skip cancel finalize", task.ID, myRun)) + return true + } e.markCancelProgress(task) stopped := e.markStopped(ctx, task.ID) if stopped { @@ -828,6 +877,10 @@ func (e *Ingestor) runTask(ctx context.Context, task *entity.IngestionTask) bool } if errors.Is(err, context.DeadlineExceeded) { common.Info(fmt.Sprintf("Task %s timed out during pipeline", task.ID)) + if !e.ownsTaskRun(task.ID, myRun) { + common.Info(fmt.Sprintf("Task %s run %d superseded by a newer run; skip timeout finalize", task.ID, myRun)) + return true + } e.markTimeoutProgress(task) ok := e.markFailed(ctx, task.ID) if ok { @@ -836,6 +889,10 @@ func (e *Ingestor) runTask(ctx context.Context, task *entity.IngestionTask) bool return ok } common.Error(fmt.Sprintf("Task %s failed", task.ID), err) + if !e.ownsTaskRun(task.ID, myRun) { + common.Info(fmt.Sprintf("Task %s run %d superseded by a newer run; skip failure finalize", task.ID, myRun)) + return true + } ok := e.markFailed(ctx, task.ID) if ok { e.recordTerminalPipelineLog(ctx, task, string(entity.TaskStatusFail)) @@ -843,6 +900,10 @@ func (e *Ingestor) runTask(ctx context.Context, task *entity.IngestionTask) bool return ok } + if !e.ownsTaskRun(task.ID, myRun) { + common.Info(fmt.Sprintf("Task %s run %d superseded by a newer run; skip completion", task.ID, myRun)) + return true + } if err := e.completeTask(ctx, task.ID); err != nil { common.Error(fmt.Sprintf("Task %s update status failed", task.ID), err) return false diff --git a/internal/service/ingestion_task_service.go b/internal/service/ingestion_task_service.go index 8395578ed08..3bd3f6babfb 100644 --- a/internal/service/ingestion_task_service.go +++ b/internal/service/ingestion_task_service.go @@ -46,15 +46,20 @@ type IngestionTaskService struct { ingestionTaskDAO *dao.IngestionTaskDAO ingestionTaskLogDAO *dao.IngestionTaskLogDAO taskPublisher TaskPublisher + // supersedeTerminalWait bounds how long supersedeAndRetryTask waits for a + // live worker to finalize a requested stop before force-finalizing the + // task. Overridable so tests do not pay the full production wait. + supersedeTerminalWait time.Duration } func NewIngestionTaskService() *IngestionTaskService { return &IngestionTaskService{ - documentDAO: dao.NewDocumentDAO(), - userDAO: dao.NewUserDAO(), - ingestionTaskDAO: dao.NewIngestionTaskDAO(), - ingestionTaskLogDAO: dao.NewIngestionTaskLogDAO(), - taskPublisher: NewMessageQueueTaskPublisher(), + documentDAO: dao.NewDocumentDAO(), + userDAO: dao.NewUserDAO(), + ingestionTaskDAO: dao.NewIngestionTaskDAO(), + ingestionTaskLogDAO: dao.NewIngestionTaskLogDAO(), + taskPublisher: NewMessageQueueTaskPublisher(), + supersedeTerminalWait: defaultSupersedeTerminalWait, } } @@ -341,7 +346,7 @@ func validateTransition(from, to string) error { if to == common.STOPPED { return nil } - case common.FAILED, common.STOPPED: + case common.FAILED, common.STOPPED, common.COMPLETED: if to == common.CREATED { return nil } @@ -397,7 +402,7 @@ func (s *IngestionTaskService) CreateAndEnqueue(ctx context.Context, task *entit return nil, err } return s.markScheduledAfterPublish(ctx, existing.ID) - case common.FAILED, common.STOPPED: + case common.FAILED, common.STOPPED, common.COMPLETED: originalStatus := existing.Status existing, err = s.transition(ctx, existing.ID, common.CREATED) if err != nil { @@ -415,6 +420,8 @@ func (s *IngestionTaskService) CreateAndEnqueue(ctx context.Context, task *entit return nil, err } return s.markScheduledAfterPublish(ctx, existing.ID) + case common.SCHEDULED, common.RUNNING, common.STOPPING: + return s.supersedeAndRetryTask(ctx, existing) default: return nil, fmt.Errorf("document id %s already exists, status: %s, task id: %s", task.DocumentID, existing.Status, existing.ID) } @@ -433,6 +440,141 @@ func (s *IngestionTaskService) CreateAndEnqueue(ctx context.Context, task *entit return s.markScheduledAfterPublish(ctx, created.ID) } +// defaultSupersedeTerminalWait bounds how long a re-parse request waits for a +// live worker to finalize a requested stop before force-finalizing the task. +// A live worker observes the stop (Redis cancel flag polled every 3s, plus the +// DB STOPPING fallback) well within this window; only a worker stuck in a +// non-cancellable section or a dead worker exceeds it. +const defaultSupersedeTerminalWait = 8 * time.Second + +const supersedePollInterval = 250 * time.Millisecond + +// supersedeAndRetryTask finalizes an in-flight ingestion task +// (SCHEDULED/RUNNING/STOPPING) and re-queues it for a fresh parse, mirroring +// the Python /documents/ingest endpoint, which accepts a parse request +// regardless of the previous task's in-flight state. Without this, a document +// whose task lingers in a non-terminal state — for example a parse canceled at +// progress 0 whose worker died before finalizing the stop (e.g. the service +// restarted mid-parse), or a scheduled task whose queue message was lost — +// could never be re-parsed: every attempt failed with "document id ... already +// exists, status: ...". +// +// For a task a worker may still be executing (RUNNING/STOPPING) the stop is +// requested first and the worker gets a bounded window to finalize on its own; +// a live worker settles within its 3s cancel poll. Only when that window +// expires is the task force-finalized. In every case the Redis cancel flag is +// cleared before the re-arm: the replacement run's pre-start cancel check +// (Ingestor.executeTask) reads the same flag and would abort the fresh parse +// before it starts, silently reproducing the "cannot re-parse" symptom. +func (s *IngestionTaskService) supersedeAndRetryTask(ctx context.Context, existing *entity.IngestionTask) (*entity.IngestionTask, error) { + inFlightStatus := existing.Status + if inFlightStatus == common.RUNNING { + // RequestStop moves RUNNING→STOPPING and sets the Redis cancel flag so + // a live worker aborts at its next cancellation checkpoint. + if _, err := s.RequestStop(ctx, existing.ID); err != nil { + // The worker may have finalized (stopped/completed/failed) + // concurrently; a terminal task is still supersedeable below. + refreshed, refreshErr := s.GetTask(ctx, existing.ID) + if refreshErr != nil || !isTerminalTaskStatus(refreshed.Status) { + return nil, fmt.Errorf("stop in-flight task %s before re-parse: %w", existing.ID, err) + } + existing = refreshed + } + } + if existing.Status == common.RUNNING || existing.Status == common.STOPPING { + final := s.awaitTerminalTask(ctx, existing.ID) + if final == nil { + var err error + if final, err = s.forceTerminalTask(ctx, existing.ID); err != nil { + return nil, fmt.Errorf("finalize in-flight task %s (%s) before re-parse: %w", existing.ID, inFlightStatus, err) + } + } + existing = final + } + if existing.Status == common.CREATED || existing.Status == common.SCHEDULED { + // Never claimed (or freshly re-armed by a concurrent request): no + // worker can be executing it, so finalize it immediately. + var err error + if existing, err = s.transition(ctx, existing.ID, common.STOPPED); err != nil { + return nil, fmt.Errorf("finalize in-flight task %s (%s) before re-parse: %w", existing.ID, inFlightStatus, err) + } + } + if !isTerminalTaskStatus(existing.Status) { + return nil, fmt.Errorf("task %s is in unexpected status %s before re-parse", existing.ID, existing.Status) + } + // The superseded run is final, so any leftover Redis cancel flag is stale + // for the replacement run (see the doc comment). + clearCancelFlag(ctx, existing.ID) + retried, err := s.transition(ctx, existing.ID, common.CREATED) + if err != nil { + return nil, fmt.Errorf("re-arm superseded task %s for re-parse: %w", existing.ID, err) + } + if err = s.enqueueTask(retried.ID); err != nil { + if rollbackErr := s.rollbackRetriedTask(ctx, retried.ID, existing.Status); rollbackErr != nil { + return nil, fmt.Errorf("enqueue task %s: %w (rollback failed: %w)", retried.ID, err, rollbackErr) + } + return nil, err + } + return s.markScheduledAfterPublish(ctx, retried.ID) +} + +// awaitTerminalTask polls the task until it reaches a terminal status or the +// supersede wait budget expires. Returns the terminal task, or nil on timeout. +func (s *IngestionTaskService) awaitTerminalTask(ctx context.Context, taskID string) *entity.IngestionTask { + wait := s.supersedeTerminalWait + if wait <= 0 { + wait = defaultSupersedeTerminalWait + } + deadline := time.Now().Add(wait) + for { + task, err := s.GetTask(ctx, taskID) + if err == nil && isTerminalTaskStatus(task.Status) { + return task + } + if time.Now().After(deadline) { + return nil + } + select { + case <-ctx.Done(): + return nil + case <-time.After(supersedePollInterval): + } + } +} + +// forceTerminalTask drives a task that missed its bounded stop window to a +// terminal state: STOPPING→STOPPED directly; RUNNING via RequestStop first (a +// worker may still be inside a non-cancellable section — the flag that sets is +// cleared by the caller right after the finalize, and the worker's late +// terminal write is skipped by its run-count ownership check in the Ingestor); +// CREATED/SCHEDULED→STOPPED because no worker is executing them. +func (s *IngestionTaskService) forceTerminalTask(ctx context.Context, taskID string) (*entity.IngestionTask, error) { + task, err := s.GetTask(ctx, taskID) + if err != nil { + return nil, err + } + switch task.Status { + case common.STOPPING, common.CREATED, common.SCHEDULED: + return s.transition(ctx, taskID, common.STOPPED) + case common.RUNNING: + if _, err = s.RequestStop(ctx, taskID); err != nil { + if refreshed, refreshErr := s.GetTask(ctx, taskID); refreshErr == nil && isTerminalTaskStatus(refreshed.Status) { + return refreshed, nil + } + return nil, err + } + return s.transition(ctx, taskID, common.STOPPED) + case common.COMPLETED, common.STOPPED, common.FAILED: + return task, nil + default: + return nil, fmt.Errorf("task %s has unsupported status %s", taskID, task.Status) + } +} + +func isTerminalTaskStatus(status string) bool { + return status == common.COMPLETED || status == common.STOPPED || status == common.FAILED +} + func (s *IngestionTaskService) rollbackRetriedTask(ctx context.Context, taskID, status string) error { updated, err := s.ingestionTaskDAO.UpdateStatusIfCurrent(ctx, dao.DB, taskID, common.CREATED, status) if err != nil { @@ -546,6 +688,14 @@ func (s *IngestionTaskService) AggregateTaskProgress(ctx context.Context, taskID return s.ingestionTaskLogDAO.AggregateProgress(ctx, dao.DB, taskID, total) } +// CurrentRunCount returns the run counter of the most recent started run for +// the task. Workers capture it right after IncrementRunCount and use it to +// detect that their run was superseded (a newer run bumped the counter) +// before writing terminal state. +func (s *IngestionTaskService) CurrentRunCount(ctx context.Context, taskID string) (int, bool) { + return s.lastRunCount(ctx, taskID) +} + // lastRunCount scans all task logs (newest first) for a run_count entry, // skipping component-progress rows whose Checkpoint is empty. It returns // the counter and whether one was found. diff --git a/internal/service/ingestion_task_service_test.go b/internal/service/ingestion_task_service_test.go index 0820046c16d..d444e57faf3 100644 --- a/internal/service/ingestion_task_service_test.go +++ b/internal/service/ingestion_task_service_test.go @@ -5,6 +5,7 @@ import ( "strings" "sync" "testing" + "time" "ragflow/internal/common" "ragflow/internal/dao" @@ -810,21 +811,107 @@ func TestIngestionTaskServiceScheduleCreatedTasksContinuesAfterPublishFailure(t } } -func TestIngestionTaskServiceCreateAndEnqueueRejectsActiveExistingTask(t *testing.T) { +func TestIngestionTaskServiceCreateAndEnqueueSupersedesInFlightTask(t *testing.T) { + for _, tc := range []struct { + name string + existing string + wantStatus string + }{ + { + // A parse canceled at progress 0 whose worker has not finalized the + // stop yet leaves the task in STOPPING; re-parsing waits a bounded + // window for the worker, then force-finalizes and re-queues. + name: "stopping", + existing: common.STOPPING, + wantStatus: common.SCHEDULED, + }, + { + // A task queued but never claimed by a worker (e.g. its queue + // message was lost) must not block re-parsing either. + name: "scheduled", + existing: common.SCHEDULED, + wantStatus: common.SCHEDULED, + }, + { + // A task whose worker died mid-run stays RUNNING with no owner; + // re-parsing must stop it (the only RUNNING→CREATED path in the + // transition table is RUNNING→STOPPING→STOPPED→CREATED) and queue + // a fresh run. + name: "running", + existing: common.RUNNING, + wantStatus: common.SCHEDULED, + }, + } { + t.Run(tc.name, func(t *testing.T) { + db := setupServiceTestDB(t) + pushServiceDB(t, db) + insertTestIngestionTaskWithStatus(t, "task-1", "user-1", "doc-1", "kb-1", tc.existing) + + publisher := &recordingTaskPublisher{} + svc := NewIngestionTaskService() + svc.taskPublisher = publisher + // No live worker in the test: do not pay the full production + // window before force-finalizing the in-flight task. + svc.supersedeTerminalWait = 50 * time.Millisecond + + task, err := svc.CreateAndEnqueue(t.Context(), &entity.IngestionTask{ + DocumentID: "doc-1", + UserID: "user-1", + DatasetID: "kb-1", + Status: common.CREATED, + }) + if err != nil { + t.Fatalf("CreateAndEnqueue failed: %v", err) + } + + if task.ID != "task-1" { + t.Fatalf("task ID = %q, want task-1 (superseded in place)", task.ID) + } + if task.Status != tc.wantStatus { + t.Fatalf("status = %q, want %q", task.Status, tc.wantStatus) + } + if len(publisher.messages) != 1 || publisher.messages[0].TaskID != task.ID { + t.Fatalf("unexpected published messages: %+v", publisher.messages) + } + + reloaded, err := dao.NewIngestionTaskDAO().GetByDocumentID(t.Context(), db, "doc-1") + if err != nil { + t.Fatalf("reload task: %v", err) + } + if reloaded == nil || reloaded.Status != tc.wantStatus { + t.Fatalf("expected superseded task to be re-queued, task=%+v", reloaded) + } + }) + } +} + +// TestIngestionTaskServiceCreateAndEnqueueRearmsCompletedTask locks in that a +// document whose previous parse COMPLETED can be re-parsed without first +// deleting its ingestion task: the terminal task row is re-armed in place, +// mirroring the FAILED/STOPPED handling. +func TestIngestionTaskServiceCreateAndEnqueueRearmsCompletedTask(t *testing.T) { db := setupServiceTestDB(t) pushServiceDB(t, db) - insertTestIngestionTaskWithStatus(t, "task-1", "user-1", "doc-1", "kb-1", common.SCHEDULED) + insertTestIngestionTaskWithStatus(t, "task-1", "user-1", "doc-1", "kb-1", common.COMPLETED) + publisher := &recordingTaskPublisher{} svc := NewIngestionTaskService() svc.taskPublisher = publisher - ctx := t.Context() - _, err := svc.CreateAndEnqueue(ctx, &entity.IngestionTask{DocumentID: "doc-1", UserID: "user-1", DatasetID: "kb-1", Status: common.CREATED}) - if err == nil { - t.Fatal("expected CreateAndEnqueue to reject existing created task") + task, err := svc.CreateAndEnqueue(t.Context(), &entity.IngestionTask{ + DocumentID: "doc-1", + UserID: "user-1", + DatasetID: "kb-1", + Status: common.CREATED, + }) + if err != nil { + t.Fatalf("CreateAndEnqueue failed: %v", err) + } + if task.ID != "task-1" || task.Status != common.SCHEDULED { + t.Fatalf("task = %s/%s, want task-1/SCHEDULED", task.ID, task.Status) } - if len(publisher.messages) != 0 { - t.Fatalf("expected no published messages, got %+v", publisher.messages) + if len(publisher.messages) != 1 || publisher.messages[0].TaskID != task.ID { + t.Fatalf("unexpected published messages: %+v", publisher.messages) } } From a1261c810608f1c2e7b420dd269cdfa2f4470522 Mon Sep 17 00:00:00 2001 From: Wang Qi Date: Thu, 10 Sep 2026 16:34:09 +0800 Subject: [PATCH 073/568] [Refactor] Use regex to do hightlight (#19488) --- common/doc_store/es_conn_base.py | 21 ++------ common/doc_store/infinity_conn_base.py | 51 ++++--------------- rag/nlp/search.py | 17 ++----- .../rag/nlp/test_gaussdb_retrieval.py | 1 + 4 files changed, 18 insertions(+), 72 deletions(-) diff --git a/common/doc_store/es_conn_base.py b/common/doc_store/es_conn_base.py index e745a697b3f..6bdb3bdea81 100644 --- a/common/doc_store/es_conn_base.py +++ b/common/doc_store/es_conn_base.py @@ -28,7 +28,7 @@ from common.file_utils import get_project_base_directory from common.misc_utils import convert_bytes from common.doc_store.doc_store_base import DocStoreConnection, OrderByExpr, MatchExpr -from rag.nlp import is_english, rag_tokenizer +from rag.nlp import rag_tokenizer from common import settings ATTEMPT_TIME = 2 @@ -323,25 +323,10 @@ def get_fields(self, res, fields: list[str]) -> dict[str, dict]: def get_highlight(self, res, keywords: list[str], field_name: str): ans = {} + pattern = re.compile("|".join(re.escape(w) for w in sorted(filter(None, keywords), key=len, reverse=True)), re.IGNORECASE) if any(keywords) else None for d in res["hits"]["hits"]: - highlights = d.get("highlight") - if not highlights: - continue - txt = "...".join([a for a in list(highlights.items())[0][1]]) - if not is_english(txt.split()): - ans[d["_id"]] = txt - continue - txt = d["_source"][field_name] - txt = re.sub(r"[\r\n]", " ", txt, flags=re.IGNORECASE | re.MULTILINE) - txt_list = [] - for t in re.split(r"[.?!;\n]", txt): - for w in keywords: - t = re.sub(r"(^|[ .?/'\"\(\)!,:;-])(%s)([ .?/'\"\(\)!,:;-])" % re.escape(w), r"\1\2\3", t, flags=re.IGNORECASE | re.MULTILINE) - if not re.search(r"[^<>]+", t, flags=re.IGNORECASE | re.MULTILINE): - continue - txt_list.append(t) - ans[d["_id"]] = "...".join(txt_list) if txt_list else "...".join([a for a in list(highlights.items())[0][1]]) + ans[d["_id"]] = pattern.sub(lambda match: f"{match.group(0)}", txt) if pattern else txt return ans diff --git a/common/doc_store/infinity_conn_base.py b/common/doc_store/infinity_conn_base.py index 59e5051aecf..07c9ce3cb0a 100644 --- a/common/doc_store/infinity_conn_base.py +++ b/common/doc_store/infinity_conn_base.py @@ -32,7 +32,6 @@ from common import settings from common.doc_store.doc_store_base import DocStoreConnection, MatchExpr, OrderByExpr from common.file_utils import get_project_base_directory -from rag.nlp import is_english # Concurrent CREATE/DROP TABLE on the same Infinity instance can race on # Infinity's RocksDB-backed catalog counters (e.g. ``db|1|next_table_id``). @@ -788,55 +787,23 @@ def get_fields(self, res: tuple[pd.DataFrame, int] | pd.DataFrame, fields: list[ raise NotImplementedError("Not implemented") def get_highlight(self, res: tuple[pd.DataFrame, int] | pd.DataFrame, keywords: list[str], field_name: str): - # Extract DataFrame from result if isinstance(res, tuple): df, _ = res else: df = res - if df.empty or field_name not in df.columns: - return {} - - ans = {} - num_rows = len(res) - column_id = res["id"] - if field_name not in res: - if field_name == "content_with_weight" and "content" in res: + if field_name not in df: + if field_name == "content_with_weight" and "content" in df: field_name = "content" else: return {} - for i in range(num_rows): - id = column_id[i] - txt = res[field_name][i] - if re.search(r"[^<>]+", txt, flags=re.IGNORECASE | re.MULTILINE): - ans[id] = txt - continue - txt = re.sub(r"[\r\n]", " ", txt, flags=re.IGNORECASE | re.MULTILINE) - txt_list = [] - for t in re.split(r"[.?!;\n]", txt): - if is_english([t]): - for w in keywords: - t = re.sub( - r"(^|[ .?/'\"\(\)!,:;-])(%s)([ .?/'\"\(\)!,:;-])" % re.escape(w), - r"\1\2\3", - t, - flags=re.IGNORECASE | re.MULTILINE, - ) - else: - for w in sorted(keywords, key=len, reverse=True): - t = re.sub( - re.escape(w), - f"{w}", - t, - flags=re.IGNORECASE | re.MULTILINE, - ) - if not re.search(r"[^<>]+", t, flags=re.IGNORECASE | re.MULTILINE): - continue - txt_list.append(t) - if txt_list: - ans[id] = "...".join(txt_list) - else: - ans[id] = txt + if df.empty: + return {} + + ans = {} + pattern = re.compile("|".join(re.escape(w) for w in sorted(filter(None, keywords), key=len, reverse=True)), re.IGNORECASE) if any(keywords) else None + for id, txt in zip(df["id"], df[field_name]): + ans[id] = pattern.sub(lambda match: f"{match.group(0)}", txt) if pattern else txt return ans def get_aggregation(self, res: tuple[pd.DataFrame, int] | pd.DataFrame, field_name: str): diff --git a/rag/nlp/search.py b/rag/nlp/search.py index cd07f6b9180..22baac4160d 100644 --- a/rag/nlp/search.py +++ b/rag/nlp/search.py @@ -231,11 +231,7 @@ async def search(self, req, idx_names: str | list[str], kb_ids: list[str], emb_m total = self.dataStore.get_total(res) logging.debug("Dealer.search TOTAL: {}".format(total)) else: - highlightFields = ["content_ltks", "title_tks"] - if not highlight: - highlightFields = [] - elif isinstance(highlight, list): - highlightFields = highlight + highlightFields = [] matchText, keywords = self.qryr.question(qst, min_match=(0.3 if min_match else 0)) if emb_mdl is None: matchExprs = [matchText] if matchText else [] @@ -309,9 +305,9 @@ async def search(self, req, idx_names: str | list[str], kb_ids: list[str], emb_m logging.debug(f"TOTAL: {total}") ids = self.dataStore.get_doc_ids(res) keywords = list(kwds) - highlight = self.dataStore.get_highlight(res, keywords, "content_with_weight") + highlightDic = self.dataStore.get_highlight(res, keywords, "content_with_weight") if highlight else {} aggs = self.dataStore.get_aggregation(res, "docnm_kwd") - return self.SearchResult(total=total, ids=ids, query_vector=q_vec, aggregation=aggs, highlight=highlight, field=self.dataStore.get_fields(res, src + ["_score"]), keywords=keywords) + return self.SearchResult(total=total, ids=ids, query_vector=q_vec, aggregation=aggs, highlight=highlightDic, field=self.dataStore.get_fields(res, src + ["_score"]), keywords=keywords) @staticmethod def trans2floats(txt): @@ -784,11 +780,8 @@ async def retrieval( "mom_id": chunk.get("mom_id", ""), "row_id": chunk.get("row_id()"), } - if highlight and sres.highlight: - if id in sres.highlight: - d["highlight"] = remove_redundant_spaces(sres.highlight[id]) - else: - d["highlight"] = d["content_with_weight"] + if id in sres.highlight: + d["highlight"] = sres.highlight[id] ranks["chunks"].append(d) if aggs: diff --git a/test/unit_test/rag/nlp/test_gaussdb_retrieval.py b/test/unit_test/rag/nlp/test_gaussdb_retrieval.py index 3a887d5cc9a..057684293bf 100644 --- a/test/unit_test/rag/nlp/test_gaussdb_retrieval.py +++ b/test/unit_test/rag/nlp/test_gaussdb_retrieval.py @@ -488,6 +488,7 @@ async def fake_search(req, *_args, **_kwargs): total=2, ids=["term-low", "term-zero"], query_vector=[0.1, 0.2], + highlight={}, field={ "term-low": retrieval_chunk(0.1, "doc-low", "Low"), "term-zero": retrieval_chunk(0.0, "doc-zero", "Zero"), From 7090ca834bda64b5edeb1bbb19a504cb1343e6a7 Mon Sep 17 00:00:00 2001 From: euvre <93761161+euvre@users.noreply.github.com> Date: Thu, 10 Sep 2026 01:56:32 -0700 Subject: [PATCH 074/568] fix(go): stop masking document preview failures as "document not found" and add tenant access check (#19348) --- internal/handler/document.go | 26 +++- internal/handler/document_test.go | 65 +++++++- internal/service/document/document.go | 10 ++ .../service/document/document_artifact.go | 22 ++- internal/service/document/document_test.go | 139 +++++++++++++++++- .../document-preview/txt-preview.tsx | 32 ++++ 6 files changed, 281 insertions(+), 13 deletions(-) diff --git a/internal/handler/document.go b/internal/handler/document.go index bd2570a6f6e..cb4ad6f9f48 100644 --- a/internal/handler/document.go +++ b/internal/handler/document.go @@ -70,7 +70,7 @@ type documentServiceIface interface { DeleteDocumentAllMetadata(ctx context.Context, docID string) error GetDocumentMetadataByID(ctx context.Context, docID string) (map[string]interface{}, error) GetDocumentArtifact(ctx context.Context, filename, userID string) (*document.ArtifactResponse, error) - GetDocumentPreview(ctx context.Context, docID string) (*document.DocumentPreview, error) + GetDocumentPreview(ctx context.Context, userID, docID string) (*document.DocumentPreview, error) UploadLocalDocuments(ctx context.Context, kb *entity.Knowledgebase, tenantID string, files []*multipart.FileHeader, parentPath string, parserConfigOverride map[string]interface{}) ([]map[string]interface{}, []string) UploadWebDocument(ctx context.Context, kb *entity.Knowledgebase, tenantID, name, url string) (map[string]interface{}, common.ErrorCode, error) UploadEmptyDocument(ctx context.Context, kb *entity.Knowledgebase, tenantID, name string) (map[string]interface{}, common.ErrorCode, error) @@ -255,6 +255,12 @@ func (h *DocumentHandler) GetDocumentArtifact(c *gin.Context) { } func (h *DocumentHandler) GetDocumentPreview(c *gin.Context) { + user, errorCode, errorMessage := GetUser(c) + if errorCode != common.CodeSuccess { + common.ErrorWithCode(c, errorCode, errorMessage) + return + } + docID := c.Param("id") if docID == "" { @@ -263,9 +269,23 @@ func (h *DocumentHandler) GetDocumentPreview(c *gin.Context) { } ctx := c.Request.Context() - preview, err := h.documentService.GetDocumentPreview(ctx, docID) + preview, err := h.documentService.GetDocumentPreview(ctx, user.ID, docID) if err != nil { - common.ErrorWithCode(c, common.CodeDataError, "document not found") + switch { + case errors.Is(err, document.ErrPreviewDocumentNotFound): + common.ErrorWithCode(c, common.CodeDataError, "document not found") + case errors.Is(err, document.ErrPreviewFileEmpty): + common.ErrorWithCode(c, common.CodeDataError, "This file is empty.") + default: + // Surface the failure as a distinct server error (storage + // unreachable, missing object, bad address) instead of masking + // it as a missing document, while keeping the raw detail -- + // which names the object-store bucket/key -- in the server + // log only. + common.Error("GetDocumentPreview failed", err, + zap.String("doc_id", docID), zap.String("user_id", user.ID)) + common.ResponseWithCodeData(c, common.CodeServerError, nil, "Failed to load document preview") + } return } diff --git a/internal/handler/document_test.go b/internal/handler/document_test.go index b795ea2e13b..8fa26460664 100644 --- a/internal/handler/document_test.go +++ b/internal/handler/document_test.go @@ -120,9 +120,15 @@ func (f *fakeDocumentService) GetDocumentArtifact(ctx context.Context, filename, ForceAttachment: false, }, nil } -func (f *fakeDocumentService) GetDocumentPreview(ctx context.Context, docID string) (*document.DocumentPreview, error) { +func (f *fakeDocumentService) GetDocumentPreview(ctx context.Context, userID, docID string) (*document.DocumentPreview, error) { if docID == "not-found" { - return nil, fmt.Errorf("not found") + return nil, document.ErrPreviewDocumentNotFound + } + if docID == "empty-file" { + return nil, document.ErrPreviewFileEmpty + } + if docID == "storage-error" { + return nil, fmt.Errorf("read document object b/k: connection refused") } return &document.DocumentPreview{ Data: []byte("preview content"), @@ -1758,6 +1764,61 @@ func TestGetDocumentPreview_NotFound(t *testing.T) { if resp["code"] != float64(common.CodeDataError) { t.Fatalf("expected code %d, got %v", common.CodeDataError, resp["code"]) } + if resp["message"] != "document not found" { + t.Fatalf("expected message %q, got %v", "document not found", resp["message"]) + } +} + +func TestGetDocumentPreview_EmptyFile(t *testing.T) { + gin.SetMode(gin.TestMode) + h := &DocumentHandler{ + documentService: &fakeDocumentService{}, + } + c, w := setupGinContextWithUser("GET", "/api/v1/documents/empty-file/preview", "") + c.Params = gin.Params{{Key: "id", Value: "empty-file"}} + + h.GetDocumentPreview(c) + + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", w.Code) + } + var resp map[string]interface{} + json.Unmarshal(w.Body.Bytes(), &resp) + if resp["code"] != float64(common.CodeDataError) { + t.Fatalf("expected code %d, got %v", common.CodeDataError, resp["code"]) + } + if resp["message"] != "This file is empty." { + t.Fatalf("expected message %q, got %v", "This file is empty.", resp["message"]) + } +} + +func TestGetDocumentPreview_StorageErrorGenericMessage(t *testing.T) { + gin.SetMode(gin.TestMode) + h := &DocumentHandler{ + documentService: &fakeDocumentService{}, + } + c, w := setupGinContextWithUser("GET", "/api/v1/documents/storage-error/preview", "") + c.Params = gin.Params{{Key: "id", Value: "storage-error"}} + + h.GetDocumentPreview(c) + + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", w.Code) + } + var resp map[string]interface{} + json.Unmarshal(w.Body.Bytes(), &resp) + if resp["code"] != float64(common.CodeServerError) { + t.Fatalf("expected code %d, got %v", common.CodeServerError, resp["code"]) + } + msg, _ := resp["message"].(string) + if msg != "Failed to load document preview" { + t.Fatalf("expected generic message, got %v", resp["message"]) + } + // The storage detail (bucket/key, transport error) must stay in the + // server log, not in the client-visible message. + if strings.Contains(msg, "connection refused") || strings.Contains(msg, "b/k") { + t.Fatalf("storage detail leaked to client: %v", resp["message"]) + } } func TestDownloadDocument_Success(t *testing.T) { diff --git a/internal/service/document/document.go b/internal/service/document/document.go index c3208e0f560..cac341d018b 100644 --- a/internal/service/document/document.go +++ b/internal/service/document/document.go @@ -173,6 +173,16 @@ var ( ErrArtifactInvalidFilename = errors.New("invalid filename") ErrArtifactInvalidFileType = errors.New("invalid file type") ErrArtifactNotFound = errors.New("artifact not found") + + // ErrPreviewDocumentNotFound covers both "document row missing" and + // "caller may not read this document" so the preview endpoint cannot be + // used to probe foreign document IDs. Mirrors the Python preview route. + ErrPreviewDocumentNotFound = errors.New("document not found") + // ErrPreviewFileEmpty marks a document whose backing object has zero + // bytes; the handler maps it to Python's "This file is empty." + // preview response, so the sentinel text itself is never sent to + // clients. + ErrPreviewFileEmpty = errors.New("preview file empty") ) var artifactContentTypes = map[string]string{ diff --git a/internal/service/document/document_artifact.go b/internal/service/document/document_artifact.go index 935033f247b..d2fa9dd79d8 100644 --- a/internal/service/document/document_artifact.go +++ b/internal/service/document/document_artifact.go @@ -194,15 +194,25 @@ func shouldForceArtifactAttachment(ext, contentType string) bool { return ok } -func (s *DocumentService) GetDocumentPreview(ctx context.Context, docID string) (*DocumentPreview, error) { +func (s *DocumentService) GetDocumentPreview(ctx context.Context, userID, docID string) (*DocumentPreview, error) { doc, err := s.documentDAO.GetByID(ctx, dao.DB, docID) - if err != nil { - return nil, err + if err != nil || doc == nil { + return nil, ErrPreviewDocumentNotFound + } + + // Reuse KnowledgebaseDAO.Accessible — the exact rule the chunk list on + // the same page uses — so the two panels can never disagree: the owning + // tenant always, and tenant members only when the dataset's permission + // is TEAM. A denial stays indistinguishable from a missing document so + // an unauthorized caller cannot probe document IDs (mirrors Python + // DocumentService.accessible in the preview path). + if !s.kbDAO.Accessible(ctx, dao.DB, doc.KbID, userID) { + return nil, ErrPreviewDocumentNotFound } bucket, name, err := s.GetDocumentStorageAddress(ctx, doc) if err != nil { - return nil, err + return nil, fmt.Errorf("resolve storage address for document %s: %w", docID, err) } storageImpl := storage.GetStorageFactory().GetStorage() @@ -212,10 +222,10 @@ func (s *DocumentService) GetDocumentPreview(ctx context.Context, docID string) data, err := storageImpl.Get(ctx, bucket, name) if err != nil { - return nil, err + return nil, fmt.Errorf("read document object %s/%s: %w", bucket, name, err) } if len(data) == 0 { - return nil, ErrArtifactNotFound + return nil, ErrPreviewFileEmpty } fileName := "" diff --git a/internal/service/document/document_test.go b/internal/service/document/document_test.go index ca7c5785b9d..0cb58c004be 100644 --- a/internal/service/document/document_test.go +++ b/internal/service/document/document_test.go @@ -1823,9 +1823,144 @@ func TestGetDocumentPreview_DocumentNotFound(t *testing.T) { svc := testDocumentService(t) ctx := t.Context() - _, err := svc.GetDocumentPreview(ctx, "nonexistent") + _, err := svc.GetDocumentPreview(ctx, "tenant-1", "nonexistent") + if !errors.Is(err, ErrPreviewDocumentNotFound) { + t.Errorf("expected ErrPreviewDocumentNotFound, got %v", err) + } +} + +// insertTestPreviewDoc creates a doc with a name/location and seeds its blob. +func insertTestPreviewDoc(t *testing.T, db *gorm.DB, mockStorage *fakeUploadStorage, id, kbID, content string) { + t.Helper() + name := id + ".txt" + loc := id + ".txt" + doc := &entity.Document{ + ID: id, + KbID: kbID, + ParserID: "naive", + ParserConfig: entity.JSONMap{}, + Name: &name, + Location: &loc, + Suffix: "txt", + Status: sptr("1"), + } + if err := db.Create(doc).Error; err != nil { + t.Fatalf("insert test doc: %v", err) + } + if err := mockStorage.Put(context.Background(), kbID, loc, []byte(content)); err != nil { + t.Fatalf("seed preview object: %v", err) + } +} + +func useFakeStorage(t *testing.T) *fakeUploadStorage { + t.Helper() + mockStorage := newFakeUploadStorage() + factory := storage.GetStorageFactory() + origStorage := factory.GetStorage() + factory.SetStorage(mockStorage) + t.Cleanup(func() { factory.SetStorage(origStorage) }) + return mockStorage +} + +func TestGetDocumentPreview_AccessControl(t *testing.T) { + db := setupServiceTestDB(t) + pushServiceDB(t, db) + mockStorage := useFakeStorage(t) + insertTestKB(t, "kb-prev", "tenant-1", 1, 0, 0) + insertTestPreviewDoc(t, db, mockStorage, "doc-prev", "kb-prev", "preview body") + + svc := testDocumentService(t) + ctx := t.Context() + + // Dataset owner reads the original file. + p, err := svc.GetDocumentPreview(ctx, "tenant-1", "doc-prev") + if err != nil { + t.Fatalf("owner preview: %v", err) + } + if string(p.Data) != "preview body" { + t.Fatalf("unexpected body: %q", string(p.Data)) + } + + // A member of the dataset's tenant reads it too. + if err := db.Create(&entity.UserTenant{ + ID: "ut-prev", UserID: "user-2", TenantID: "tenant-1", + Role: "normal", InvitedBy: "tenant-1", Status: sptr("1"), + }).Error; err != nil { + t.Fatalf("insert user_tenant: %v", err) + } + if _, err = svc.GetDocumentPreview(ctx, "user-2", "doc-prev"); err != nil { + t.Fatalf("team member preview: %v", err) + } + + // An unrelated user gets the same answer as for a missing document. + _, err = svc.GetDocumentPreview(ctx, "tenant-2", "doc-prev") + if !errors.Is(err, ErrPreviewDocumentNotFound) { + t.Fatalf("stranger preview: expected ErrPreviewDocumentNotFound, got %v", err) + } + + // A private (ME) dataset stays owner-only even for tenant members: the + // same rule the chunk list applies via KnowledgebaseDAO.Accessible. + if err := db.Create(&entity.Knowledgebase{ + ID: "kb-prev-me", TenantID: "tenant-1", Name: "private-kb", EmbdID: "embd-1", + CreatedBy: "user-1", Permission: string(entity.TenantPermissionMe), + DocNum: 1, Status: sptr(string(entity.StatusValid)), + }).Error; err != nil { + t.Fatalf("insert private kb: %v", err) + } + insertTestPreviewDoc(t, db, mockStorage, "doc-prev-me", "kb-prev-me", "private body") + + if _, err = svc.GetDocumentPreview(ctx, "user-2", "doc-prev-me"); !errors.Is(err, ErrPreviewDocumentNotFound) { + t.Fatalf("team member on private dataset: expected ErrPreviewDocumentNotFound, got %v", err) + } + p, err = svc.GetDocumentPreview(ctx, "tenant-1", "doc-prev-me") + if err != nil { + t.Fatalf("owner preview private dataset: %v", err) + } + if string(p.Data) != "private body" { + t.Fatalf("unexpected private body: %q", string(p.Data)) + } +} + +func TestGetDocumentPreview_EmptyObject(t *testing.T) { + db := setupServiceTestDB(t) + pushServiceDB(t, db) + mockStorage := useFakeStorage(t) + insertTestKB(t, "kb-prev-empty", "tenant-1", 1, 0, 0) + insertTestPreviewDoc(t, db, mockStorage, "doc-prev-empty", "kb-prev-empty", "") + + svc := testDocumentService(t) + _, err := svc.GetDocumentPreview(t.Context(), "tenant-1", "doc-prev-empty") + if !errors.Is(err, ErrPreviewFileEmpty) { + t.Fatalf("expected ErrPreviewFileEmpty, got %v", err) + } +} + +func TestGetDocumentPreview_MissingObjectSurfacesStorageError(t *testing.T) { + db := setupServiceTestDB(t) + pushServiceDB(t, db) + useFakeStorage(t) + insertTestKB(t, "kb-prev-miss", "tenant-1", 1, 0, 0) + // Document exists but its blob was never seeded. + name := "doc.txt" + loc := "doc.txt" + if err := db.Create(&entity.Document{ + ID: "doc-prev-miss", KbID: "kb-prev-miss", ParserID: "naive", + ParserConfig: entity.JSONMap{}, Name: &name, Location: &loc, + Suffix: "txt", Status: sptr("1"), + }).Error; err != nil { + t.Fatalf("insert test doc: %v", err) + } + + svc := testDocumentService(t) + _, err := svc.GetDocumentPreview(t.Context(), "tenant-1", "doc-prev-miss") if err == nil { - t.Error("expected error for nonexistent document") + t.Fatal("expected storage read error") + } + if errors.Is(err, ErrPreviewDocumentNotFound) { + t.Fatalf("storage failure must not be masked as document not found, got %v", err) + } + if !strings.Contains(err.Error(), "kb-prev-miss") { + t.Fatalf("error should carry the storage address for diagnosis: %v", err) } } diff --git a/web/src/components/document-preview/txt-preview.tsx b/web/src/components/document-preview/txt-preview.tsx index ae2bad16696..56349ce2c00 100644 --- a/web/src/components/document-preview/txt-preview.tsx +++ b/web/src/components/document-preview/txt-preview.tsx @@ -26,6 +26,31 @@ export const TxtPreviewer = ({ className, url }: TxtPreviewerProps) => { // const url = useGetDocumentUrl(); const [loading, setLoading] = useState(false); const [data, setData] = useState(''); + + // Business errors come back as HTTP 200 JSON bodies (e.g. + // {"code":102,"message":"document not found"}). Detect that shape and + // surface the message instead of painting raw JSON as file content. + const extractBusinessError = (text: string): string | null => { + try { + const parsed = JSON.parse(text) as { + code?: unknown; + message?: unknown; + }; + if ( + parsed && + typeof parsed === 'object' && + typeof parsed.code === 'number' && + parsed.code !== 0 && + typeof parsed.message === 'string' + ) { + return parsed.message; + } + } catch { + // Plain text document content. + } + return null; + }; + const fetchTxt = async () => { setLoading(true); const res = await request(url, { @@ -38,6 +63,13 @@ export const TxtPreviewer = ({ className, url }: TxtPreviewerProps) => { }); // Handles UTF-8/UTF-16 (BOM) as well as GB2312/GBK files const text = await decodeBlobText(res.data); + const businessError = extractBusinessError(text); + if (businessError) { + message.error(businessError); + setData(''); + setLoading(false); + return; + } setData(text); setLoading(false); }; From 7e86beadd14becefd9b6cb6040f12887fcfe03d3 Mon Sep 17 00:00:00 2001 From: buua436 Date: Thu, 10 Sep 2026 17:13:57 +0800 Subject: [PATCH 075/568] fix: route navigation API through tree search (#19493) --- api/apps/services/dataset_api_service.py | 15 +- .../knowlege_compile/dataset_nav.py | 155 ++++++++++++++---- 2 files changed, 130 insertions(+), 40 deletions(-) diff --git a/api/apps/services/dataset_api_service.py b/api/apps/services/dataset_api_service.py index f454142001c..0b8c86966a1 100644 --- a/api/apps/services/dataset_api_service.py +++ b/api/apps/services/dataset_api_service.py @@ -3906,7 +3906,6 @@ async def generate_nav( # "tree" — BFS beam descent over the nav cluster tree. This is what main # branch does. Kept as the A/B baseline; drop it, and # ``search_nav_tree_descent`` with it, once a winner is settled. -_NAV_TREE_ROUTER = "chunk_agg" # Cap on how many documents a flat router hands back. The cluster beam descent # that main uses returns ~2 by construction (its per-level pruning keeps only @@ -4026,7 +4025,7 @@ async def search_dataset_layers( elif mode == "nav_cluster": return await _search_layers_nav_clusters(tenant_id, dataset_id, query, top_k, embd_mdl, search_dataset_nav, doc_scope=doc_scope) elif mode == "navigation_tree": - return await _search_layers_navigation_tree(tenant_id, dataset_id, query, top_k, embd_mdl, kb, doc_scope=doc_scope) + return await _search_layers_navigation_tree(tenant_id, dataset_id, query, top_k, embd_mdl, kb, router="tree", doc_scope=doc_scope) elif mode == "chunk": return await _search_layers_chunks(tenant_id, dataset_id, query, top_k, embd_mdl, kb, doc_scope=doc_scope) elif mode == "all": @@ -4097,14 +4096,14 @@ def _nav_label_items(items: list) -> list: return items -async def _search_layers_navigation_tree(tenant_id, dataset_id, query, top_k, embd_mdl, kb=None, *, doc_scope=None): - """Route to documents, dispatched by ``_NAV_TREE_ROUTER``. +async def _search_layers_navigation_tree(tenant_id, dataset_id, query, top_k, embd_mdl, kb=None, *, router: str = "chunk_agg", doc_scope=None): + """Route to documents using the requested navigation-tree strategy. Every strategy returns the same item shape — ``doc_id``, a 0..1 ``score``, and ``_nav`` carrying the document summary — so callers stay agnostic to which one is active. """ - if _NAV_TREE_ROUTER == "nav_doc": + if router == "nav_doc": from rag.advanced_rag.knowlege_compile.dataset_nav import search_dataset_nav items = await _nav_search_result( @@ -4121,7 +4120,7 @@ async def _search_layers_navigation_tree(tenant_id, dataset_id, query, top_k, em _nav_label_items(items) return True, {"mode": "navigation_tree", "total": len(items), "items": items} - if _NAV_TREE_ROUTER == "tree": + if router == "tree": from rag.advanced_rag.knowlege_compile.dataset_nav import search_nav_tree_descent items = await search_nav_tree_descent( @@ -4134,9 +4133,9 @@ async def _search_layers_navigation_tree(tenant_id, dataset_id, query, top_k, em ) return True, {"mode": "navigation_tree", "total": len(items), "items": items} - if _NAV_TREE_ROUTER in ("compiled_agg", "fusion"): + if router in ("compiled_agg", "fusion"): ok, payload = await _search_layers_compiled_agg(tenant_id, dataset_id, query, top_k, embd_mdl, kb, doc_scope=doc_scope) - if _NAV_TREE_ROUTER == "compiled_agg": + if router == "compiled_agg": return ok, payload # Fusion keeps going: the compiled leg ranks alongside the chunk leg. return await _search_layers_fusion(tenant_id, dataset_id, query, top_k, embd_mdl, kb, compiled=payload, doc_scope=doc_scope) diff --git a/rag/advanced_rag/knowlege_compile/dataset_nav.py b/rag/advanced_rag/knowlege_compile/dataset_nav.py index be7009f712e..e18c290ac09 100644 --- a/rag/advanced_rag/knowlege_compile/dataset_nav.py +++ b/rag/advanced_rag/knowlege_compile/dataset_nav.py @@ -84,9 +84,9 @@ # Minimum fused relevance score a nav node must reach to be returned by a # tree search. Below this, the query is treated as "not related" to the -# dataset and search_nav_tree_descent returns an empty result instead of -# falling back to an entire subtree. The dense leg contributes at most -# ``_NAV_HYBRID_DENSE_W`` (cosine ≤ 1) and the text leg at most +# dataset: no node clears the floor, so search_nav_tree_descent routes nothing +# rather than falling back to the nearest subtree. The dense leg contributes +# at most ``_NAV_HYBRID_DENSE_W`` (cosine ≤ 1) and the text leg at most # ``1 - _NAV_HYBRID_DENSE_W``, so a score below this threshold means the # query is neither semantically nor lexically close to any node. _NAV_TREE_MIN_SCORE = 0.1 @@ -1513,6 +1513,15 @@ async def search_nav_tree_descent( The search uses BFS with beam pruning — at each depth, only the *beam_width* most similar clusters are expanded further. + A query term that only appears in a ``nav_cluster`` summary (not in any + leaf's text) is still routable. Roots are routed by vector only, so such a + cluster would never enter the beam on its own; a flat lexical sweep over the + cluster level finds it independent of the beam and seeds the frontier with + it. Lexical support then propagates down the matched path, so that cluster's + documents are ranked by the usual hybrid score instead of the cluster + dumping a coverage list. When the descent yields no document at all, the + matched clusters' ``doc_ids_kwd`` coverage is routed as a last resort. + ``doc_scope`` restricts the search to a specific set of documents: both the KNN legs (exact if the engine misses the terms filter, ``_store_knn`` falls back to a full in-memory match) and the text legs apply the scope @@ -1631,6 +1640,33 @@ async def search_nav_tree_descent( if not current_level: return [] + # Seed the frontier with lexically matched clusters: they are entry points + # into branches the vector-only root routing can miss, and seeding them lets + # the descent rank their documents instead of dumping a coverage list. + lexical_hits = await _lexical_cluster_hits( + tenant_id, + kb_id, + query, + vec, + vf, + dense_w, + fields, + allowed_docs, + limit=max((top_k or 0) * 3, 20), + ) + frontier_by_name = {r.get("name"): r for r in current_level} + for r in lexical_hits[:beam_width]: + existing = frontier_by_name.get(r.get("name")) + if existing is not None: + # Already in the frontier (e.g. a root the vector leg routed to): + # fold the lexical support in so its branch inherits it instead of + # only being rescued by its coverage list. + existing["_text_score"] = max(existing.get("_text_score") or 0.0, r["_text_score"]) + existing["_score"] = max(existing.get("_score") or 0.0, r["_score"]) + else: + frontier_by_name[r.get("name")] = r + current_level.append(r) + while current_level and (top_k is None or len(collected) < top_k): next_level: list[dict] = [] @@ -1640,6 +1676,10 @@ async def search_nav_tree_descent( continue seen_nodes.add(node_name) parent_score = node.get("_score", 0.0) + # Lexical support for this subtree: the node carries the query term + # itself (seeded entry point or this level's text leg), or an + # ancestor did. + lexical_support = node.get("_lex") or node.get("_text_score") or 0.0 child_cond: dict = { "kb_id": [kb_id], @@ -1697,6 +1737,9 @@ async def search_nav_tree_descent( for c in candidates: if top_k is not None and len(collected) >= top_k: break + # A leaf is routable when the query term is supported anywhere on + # its ancestor path, not only when the leaf's own text carries it. + lexical = (c.get("_text_score") or 0.0) or lexical_support if c.get("type_kwd") == "nav_doc": doc_id = (c.get("doc_id") or "").strip() score = c["_score"] if c.get("_score") is not None else parent_score @@ -1704,13 +1747,12 @@ async def search_nav_tree_descent( continue if allowed_docs and doc_id not in allowed_docs: continue - # Tree search is driven by a keyword: a nav_doc that only - # matched by vector similarity (no lexical/keyword hit, - # i.e. ``_text_score == 0``) is unrelated to the query and - # must not surface. Vector similarity alone always yields - # a "nearest" node, so without this gate an unrelated - # keyword would return the whole nearest subtree. - if not c.get("_text_score"): + # Tree search is driven by a keyword: a nav_doc with no + # lexical support on its path is unrelated to the query and + # must not surface. Vector similarity alone always yields a + # "nearest" node, so without this gate an unrelated keyword + # would return the whole nearest subtree. + if lexical <= 0: continue # Skip low-relevance leaves: a below-threshold score means # the query is unrelated to this node, so it must not @@ -1720,6 +1762,10 @@ async def search_nav_tree_descent( seen_docs.add(doc_id) collected.append({"doc_id": doc_id, "score": round(score, 4)}) else: + # Carry the lexical support down so a matched branch keeps + # contributing documents even where the term reappears only + # in a deeper summary. + c["_lex"] = lexical next_level.append(c) if top_k is not None and len(collected) >= top_k: @@ -1728,38 +1774,83 @@ async def search_nav_tree_descent( if top_k is not None and len(collected) >= top_k: break - next_level.sort(key=lambda c: c.get("_score", 0.0), reverse=True) + # Keep lexically supported branches in the beam ahead of purely + # vector-ranked ones: the query term is what makes them relevant. + next_level.sort(key=lambda c: (bool(c.get("_lex")), c.get("_score", 0.0)), reverse=True) current_level = next_level[:beam_width] - # Fallback: collect doc_ids from terminal cluster nodes — but only when - # the terminal cluster itself is relevant (its score clears the threshold - # AND it has a lexical hit). Without this guard, an unrelated query - # (e.g. random gibberish) would always have a nearest cluster and the - # search would dump the entire subtree's documents back, defeating the - # purpose of tree search. - if not collected and current_level: - for node in current_level: - node_score = node.get("_score", 0.0) or 0.0 - if node_score < _NAV_TREE_MIN_SCORE: - continue - if not node.get("_text_score"): - continue - for did in node.get("doc_ids_kwd") or []: - did_str = str(did).strip() - if not did_str or did_str in seen_docs: - continue - if allowed_docs and did_str not in allowed_docs: - continue - seen_docs.add(did_str) - collected.append({"doc_id": did_str, "score": round(node_score, 4)}) + # Last resort: a lexically matched cluster whose documents the descent could + # not reach — no leaf children, or every child dropped by the doc scope — + # still names them in ``doc_ids_kwd``, so route that coverage list. + if not collected and lexical_hits: + for node in lexical_hits: + for did in _as_str_list(node.get("doc_ids_kwd")): if top_k is not None and len(collected) >= top_k: break + if did in seen_docs: + continue + if allowed_docs and did not in allowed_docs: + continue + seen_docs.add(did) + collected.append({"doc_id": did, "score": round(node["_score"], 4)}) if top_k is not None and len(collected) >= top_k: break return collected +async def _lexical_cluster_hits( + tenant_id: str, + kb_id: str, + query: str, + vec: list[float], + vf: str, + dense_w: float, + fields: list[str], + allowed_docs: set[str], + limit: int, +) -> list[dict]: + """Clusters whose summary carries a query term, best first. + + The descent can miss these on its own: roots are routed by vector only, so a + cluster whose summary names the query term never enters the beam unless its + whole ancestor chain ranks high on cosine. A flat lexical sweep over the + cluster level finds it regardless of the beam. Each returned row carries + ``_score`` (same fusion scale as the descent levels) and ``_text_score``, so + a caller can seed the frontier with it. + """ + condition: dict = {"type_kwd": ["nav_cluster"], "kb_id": [kb_id]} + if allowed_docs: + condition["doc_ids_kwd"] = sorted(allowed_docs) + try: + rows = await _store_text_search( + tenant_id, + kb_id, + query, + fields, + limit=limit, + extra_filter=condition, + ) + except Exception: + logging.exception("search_nav_tree_descent: cluster text sweep failed for kb=%s", kb_id) + return [] + hits: list[dict] = [] + for row in rows: + if not _in_nav_scope(row, allowed_docs): + continue + text_score = _nav_text_score(query, row) + if text_score <= 0: + continue + score = dense_w * _cosine_sim(vec, row.get(vf)) + (1.0 - dense_w) * text_score + if score < _NAV_TREE_MIN_SCORE: + continue + row["_score"] = score + row["_text_score"] = text_score + hits.append(row) + hits.sort(key=lambda r: r["_score"], reverse=True) + return hits + + def _hybrid_fuse( vec: list[float], vf: str, From e9a6397ab87f28b03abb633898e0eb76ae81dff2 Mon Sep 17 00:00:00 2001 From: buua436 Date: Thu, 10 Sep 2026 17:29:06 +0800 Subject: [PATCH 076/568] fix: support keyword search for dataset structure graphs (#19473) --- internal/handler/dataset_artifact.go | 13 +- internal/service/dataset_structure_graph.go | 164 +++++++++++++++++--- 2 files changed, 150 insertions(+), 27 deletions(-) diff --git a/internal/handler/dataset_artifact.go b/internal/handler/dataset_artifact.go index aa637b9dc76..1e615cbf395 100644 --- a/internal/handler/dataset_artifact.go +++ b/internal/handler/dataset_artifact.go @@ -282,8 +282,10 @@ func (h *DatasetArtifactHandler) GetArtifactGraph(c *gin.Context) { common.SuccessWithData(c, graph, "success") } -// ListStructures handles GET /artifacts/structure?kind= — the dataset-scope -// structure graph for a resolved kind (mirrors Python get_dataset_structure). +// ListStructures handles GET /artifacts/structure?kind=&keywords= — +// the dataset-scope structure graph for a resolved kind (mirrors Python +// get_dataset_structure). A non-empty keywords value returns the matching +// entity subgraph. // kind is REQUIRED: missing or invalid → 400 ARGUMENT_ERROR. func (h *DatasetArtifactHandler) ListStructures(c *gin.Context) { _, tenantID, _ := h.datasetOwner(c, c.Param("dataset_id")) @@ -296,7 +298,12 @@ func (h *DatasetArtifactHandler) ListStructures(c *gin.Context) { common.ErrorWithCode(c, common.CodeArgumentError, "kind is required") return } - in := service.DatasetStructureGraphInput{TenantID: tenantID, DatasetID: datasetID, Kind: kind} + in := service.DatasetStructureGraphInput{ + TenantID: tenantID, + DatasetID: datasetID, + Kind: kind, + Keywords: strings.TrimSpace(c.Query("keywords")), + } resp, err := h.svc.GetDatasetStructure(c.Request.Context(), in) if err != nil { if errors.Is(err, service.ErrInvalidStructureKind) { diff --git a/internal/service/dataset_structure_graph.go b/internal/service/dataset_structure_graph.go index 0b2afb37f0d..d735422cbb9 100644 --- a/internal/service/dataset_structure_graph.go +++ b/internal/service/dataset_structure_graph.go @@ -762,7 +762,7 @@ func (s *DatasetArtifactService) GetDocumentGraph(ctx context.Context, in Docume // keywords mode: name matching/KNN → matched entities' subgraph. if in.Keywords != "" { - bucketMeta, entities, relations, err := s.keywordSubgraph(ctx, in.TenantID, in.DatasetID, in.DocumentID, in.Keywords, templateMeta) + bucketMeta, entities, relations, err := s.keywordSubgraph(ctx, in.TenantID, in.DatasetID, in.DocumentID, in.Keywords, templateMeta, nil) if err != nil { return nil, err } @@ -877,14 +877,20 @@ type DatasetStructureGraphInput struct { TenantID string DatasetID string Kind string - Wipe bool + // Keywords selects the matching entity subgraph when non-empty. + Keywords string + Wipe bool } // DatasetStructureGraphResponse mirrors Python get_dataset_structure's // {"kind": ..., "templates": [...]}. type DatasetStructureGraphResponse struct { - Kind string `json:"kind"` - Templates []DocumentStructureGraphTemplate `json:"templates"` + Kind string `json:"kind"` + TotalEntities int `json:"total_entities"` + TotalRelations int `json:"total_relations"` + ReturnedEntities int `json:"returned_entities"` + ReturnedRelations int `json:"returned_relations"` + Templates []DocumentStructureGraphTemplate `json:"templates"` } // GetDatasetStructure returns the dataset-scope structure graph for a resolved @@ -896,7 +902,9 @@ type DatasetStructureGraphResponse struct { // _resolve_dataset_structure_kind against compilation_template_kind_kwd the same // way). It collects distinct template ids, then reads each template's dataset // entity/relation rows via buildBucket. It does NOT read kg_build_meta (write/ -// delete-side only). +// delete-side only). When Keywords is set, it returns the keyword-matched +// entity subgraph using the same BM25/KNN and relation expansion path as the +// document-level endpoint. func (s *DatasetArtifactService) GetDatasetStructure(ctx context.Context, in DatasetStructureGraphInput) (*DatasetStructureGraphResponse, error) { resolved := resolveDatasetStructureKind(in.Kind) if resolved == "" { @@ -919,13 +927,28 @@ func (s *DatasetArtifactService) GetDatasetStructure(ctx context.Context, in Dat // The resolved kind is pushed into the filter so the engine applies the // predicate instead of scanning all entity rows and discarding them in Go. metaFields := []string{"id", "compilation_template_kind_kwd", "compilation_template_ids"} + entityCountFilter := map[string]interface{}{ + "knowledge_graph_kwd": []string{"entity"}, + "scope_kwd": []string{"dataset"}, + "compilation_template_kind_kwd": []string{resolved}, + } + _, entityTotal, err := graphRowSearch(ctx, in.TenantID, in.DatasetID, []string{"id"}, entityCountFilter, nil, 0, 1, nil) + if err != nil { + return nil, err + } + relationCountFilter := map[string]interface{}{ + "knowledge_graph_kwd": []string{"relation"}, + "scope_kwd": []string{"dataset"}, + "compilation_template_kind_kwd": []string{resolved}, + } + _, relationTotal, err := graphRowSearch(ctx, in.TenantID, in.DatasetID, []string{"id"}, relationCountFilter, nil, 0, 1, nil) + if err != nil { + return nil, err + } + resp.TotalEntities = int(entityTotal) + resp.TotalRelations = int(relationTotal) for offset := 0; ; offset += 1000 { - rows, total, err := graphRowSearch(ctx, in.TenantID, in.DatasetID, metaFields, - map[string]interface{}{ - "knowledge_graph_kwd": []string{"entity"}, - "scope_kwd": []string{"dataset"}, - "compilation_template_kind_kwd": []string{resolved}, - }, nil, offset, 1000, nil) + rows, total, err := graphRowSearch(ctx, in.TenantID, in.DatasetID, metaFields, entityCountFilter, nil, offset, 1000, nil) if err != nil { return nil, err } @@ -944,6 +967,51 @@ func (s *DatasetArtifactService) GetDatasetStructure(ctx context.Context, in Dat } } + if keywords := strings.TrimSpace(in.Keywords); keywords != "" { + if len(templateIDs) == 0 { + return resp, nil + } + ids := make([]string, 0, len(templateIDs)) + for tid := range templateIDs { + ids = append(ids, tid) + } + sort.Strings(ids) + templateDAO := dao.NewCompilationTemplateDAO() + for _, tid := range ids { + templateMeta := map[string]map[string]interface{}{} + template, loadErr := templateDAO.GetTemplate(ctx, dao.DB, in.TenantID, tid) + if loadErr == nil && template != nil { + templateMeta[tid] = map[string]interface{}{ + "template_id": tid, + "template_name": template.Name, + "kind": template.Kind, + } + } + bucketMeta, entities, relations, err := s.keywordSubgraph(ctx, in.TenantID, in.DatasetID, "", keywords, templateMeta, map[string]interface{}{ + "scope_kwd": []string{"dataset"}, + "compilation_template_ids": []string{tid}, + "compilation_template_kind_kwd": []string{resolved}, + "knowledge_graph_kwd": []string{"entity"}, + }) + if err != nil { + return nil, err + } + if bucketMeta == nil || (len(entities) == 0 && len(relations) == 0) { + continue + } + resp.Templates = append(resp.Templates, DocumentStructureGraphTemplate{ + TemplateID: graphStr(bucketMeta["template_id"]), + TemplateName: graphStr(bucketMeta["template_name"]), + Kind: graphStr(bucketMeta["kind"]), + Entities: entities, + Relations: relations, + }) + resp.ReturnedEntities += len(entities) + resp.ReturnedRelations += len(relations) + } + return resp, nil + } + // Read each template's dataset entity/relation rows. for tid := range templateIDs { scope := map[string]interface{}{ @@ -965,7 +1033,10 @@ func (s *DatasetArtifactService) GetDatasetStructure(ctx context.Context, in Dat Entities: entities, Relations: relations, }) + resp.ReturnedEntities += len(entities) + resp.ReturnedRelations += len(relations) } + return resp, nil } @@ -1096,21 +1167,28 @@ func resolveGraphBucket(row map[string]interface{}, templateMeta map[string]map[ "template_id": tid, "template_name": bucketName, "kind": bucketKind, - }, map[string]interface{}{ - "doc_id": []string{documentID}, + }, graphBucketScope(documentID, map[string]interface{}{ "compilation_template_ids": []string{tid}, - } + }) } bucketID := "legacy:" + compileKwd return map[string]interface{}{ "template_id": bucketID, "template_name": "Legacy (" + compileKwd + ")", "kind": kindVal, - }, map[string]interface{}{ - "doc_id": []string{documentID}, + }, graphBucketScope(documentID, map[string]interface{}{ "compile_kwd": []string{compileKwd}, "must_not": map[string]interface{}{"exists": "compilation_template_ids"}, + }) +} + +func graphBucketScope(documentID string, scope map[string]interface{}) map[string]interface{} { + if strings.TrimSpace(documentID) != "" { + scope["doc_id"] = []string{documentID} + } else { + scope["scope_kwd"] = []string{"dataset"} } + return scope } func rowTemplateID(row map[string]interface{}) string { @@ -1206,10 +1284,12 @@ func nameMatchesQuery(node StructureGraphNode, query string) bool { } // keywordSubgraph mirrors sgc.keyword_subgraph (BM25 + KNN fallback + ancestor walk). -func (s *DatasetArtifactService) keywordSubgraph(ctx context.Context, tenantID, datasetID, documentID, keywords string, templateMeta map[string]map[string]interface{}) (map[string]interface{}, []StructureGraphNode, []StructureGraphRelation, error) { - baseEntityCond := map[string]interface{}{ - "doc_id": []string{documentID}, - "knowledge_graph_kwd": []string{"entity"}, +func (s *DatasetArtifactService) keywordSubgraph(ctx context.Context, tenantID, datasetID, documentID, keywords string, templateMeta map[string]map[string]interface{}, baseEntityCond map[string]interface{}) (map[string]interface{}, []StructureGraphNode, []StructureGraphRelation, error) { + if baseEntityCond == nil { + baseEntityCond = map[string]interface{}{ + "doc_id": []string{documentID}, + "knowledge_graph_kwd": []string{"entity"}, + } } topFields := append(append([]string{}, graphEntityFields...), "compilation_template_ids", "compile_kwd", "compilation_template_kind_kwd") @@ -1239,7 +1319,45 @@ func (s *DatasetArtifactService) keywordSubgraph(ctx context.Context, tenantID, } return out } + candidateSeen := map[string]bool{} + appendCandidate := func(candidate struct { + row map[string]interface{} + node StructureGraphNode + }) { + key := firstStringValue(candidate.row["id"]) + if key == "" { + key = strings.ToLower(strings.TrimSpace(graphStr(candidate.node["name"]))) + "\x00" + strings.ToLower(strings.TrimSpace(graphStr(candidate.node["type"]))) + } + if key != "" { + if candidateSeen[key] { + return + } + candidateSeen[key] = true + } + candidates = append(candidates, candidate) + } if textQuery != "" { + // name_kwd is a keyword field and only supports exact filtering in the + // common engine abstraction. Scan the scoped entity rows instead so + // prefix/contains matches are not limited by the BM25 candidate cap. + for offset := 0; ; offset += 1000 { + nameMap, total, err := graphRowSearch(ctx, tenantID, datasetID, topFields, baseEntityCond, nil, offset, 1000, nil) + if err != nil { + return nil, nil, nil, err + } + for _, candidate := range validTop(nameMap) { + if nameMatchesQuery(candidate.node, textQuery) { + appendCandidate(candidate) + } + } + if int64(offset+1000) >= total || len(nameMap) == 0 { + break + } + } + } + if len(candidates) == 0 && textQuery != "" { + // If no entity name matches, fall back to BM25 over the serialized + // entity content (including descriptions and other payload fields). textExpr := &types.MatchTextExpr{ Fields: []string{"content_ltks^10", "content_sm_ltks"}, MatchingText: textQuery, @@ -1250,10 +1368,8 @@ func (s *DatasetArtifactService) keywordSubgraph(ctx context.Context, tenantID, if err != nil { return nil, nil, nil, err } - for _, c := range validTop(topMap) { - if nameMatchesQuery(c.node, textQuery) { - candidates = append(candidates, c) - } + for _, candidate := range validTop(topMap) { + appendCandidate(candidate) } } // Prefer detail entities over title-typed ancestors. From 5c48dfb1fc0cf1abd8547c4e2ff44b3da304ee84 Mon Sep 17 00:00:00 2001 From: Lynn Date: Thu, 10 Sep 2026 17:54:10 +0800 Subject: [PATCH 077/568] Fix: num bind datasets in template by components (#19454) --- .../agents/template-retrieval-binding.ts | 74 ++++++++++++++----- 1 file changed, 55 insertions(+), 19 deletions(-) diff --git a/web/src/pages/agents/template-retrieval-binding.ts b/web/src/pages/agents/template-retrieval-binding.ts index 8df0925fd09..872d06bb74c 100644 --- a/web/src/pages/agents/template-retrieval-binding.ts +++ b/web/src/pages/agents/template-retrieval-binding.ts @@ -6,7 +6,10 @@ import { Operator, RetrievalFrom } from '@/pages/agent/constant'; * Retrieval params live in two views of a DSL: the canvas graph * (`graph.nodes[].data.form` / `...tools[].params`) and the components the * runtime executes (`components[].obj.params` / `...tools[].params`). Both are - * written on save, so binding helpers must keep the two views in sync. + * written on save, so binding helpers must keep the two views in sync. Counting + * helpers, however, follow the components view only — the topology the engine + * runs — so a single retrieval step mirrored in both views is never counted + * twice. */ interface RetrievalParams { retrieval_from?: string; @@ -15,56 +18,80 @@ interface RetrievalParams { kb_ids?: string[]; } -function walkRetrievalParams( +function pushRetrievalParams( + locations: Array<{ params: RetrievalParams }>, + params: unknown, +) { + if ( + params && + typeof params === 'object' && + typeof (params as RetrievalParams).retrieval_from === 'string' + ) { + locations.push({ params: params as RetrievalParams }); + } +} + +/** Retrieval steps reachable from the canvas graph view. */ +function walkGraphRetrievalParams( dsl: DSL | Record, ): Array<{ params: RetrievalParams }> { const locations: Array<{ params: RetrievalParams }> = []; - const pushParams = (params: unknown) => { - if ( - params && - typeof params === 'object' && - typeof (params as RetrievalParams).retrieval_from === 'string' - ) { - locations.push({ params: params as RetrievalParams }); - } - }; - const graph = (dsl as Record)?.graph; if (Array.isArray(graph?.nodes)) { for (const node of graph.nodes) { const label = node?.data?.label; const form = node?.data?.form; if (label === Operator.Retrieval) { - pushParams(form); + pushRetrievalParams(locations, form); } else if (label === Operator.Agent) { for (const tool of form?.tools ?? []) { if (tool?.component_name === Operator.Retrieval) { - pushParams(tool?.params); + pushRetrievalParams(locations, tool?.params); } } } } } + return locations; +} +/** Retrieval steps the runtime actually executes (topology of record). */ +function walkComponentsRetrievalParams( + dsl: DSL | Record, +): Array<{ params: RetrievalParams }> { + const locations: Array<{ params: RetrievalParams }> = []; const components = (dsl as Record)?.components; if (components && typeof components === 'object') { for (const component of Object.values(components)) { const obj = (component as Record)?.obj; if (obj?.component_name === Operator.Retrieval) { - pushParams(obj?.params); + pushRetrievalParams(locations, obj?.params); } else if (obj?.component_name === Operator.Agent) { for (const tool of obj?.params?.tools ?? []) { if (tool?.component_name === Operator.Retrieval) { - pushParams(tool?.params); + pushRetrievalParams(locations, tool?.params); } } } } } - return locations; } +/** + * Every retrieval location across both views of the DSL. Binding must write + * both the canvas graph and the executed components so a later save (which + * rebuilds components from the graph) cannot silently unbind a step. + */ +function walkRetrievalParams( + dsl: DSL | Record, +): Array<{ params: RetrievalParams }> { + return [ + ...walkGraphRetrievalParams(dsl), + ...walkComponentsRetrievalParams(dsl), + ]; +} + export interface RetrievalBindingCount { datasetCount: number; memoryCount: number; @@ -73,7 +100,10 @@ export interface RetrievalBindingCount { /** * Counts retrieval steps that explicitly source from a dataset/memory but do * not carry any binding yet. Such steps fail at runtime with a - * `dataset_ids`/`memory_ids is required` error. + * `dataset_ids`/`memory_ids is required` error. The count follows the + * `components` view — the topology the runtime executes — and only falls back + * to the graph view when the DSL has no components block, so a retrieval step + * mirrored in both views is reported once. */ export function countUnboundRetrieval( dsl: DSL | Record | undefined, @@ -83,7 +113,13 @@ export function countUnboundRetrieval( if (!dsl) { return { datasetCount, memoryCount }; } - for (const { params } of walkRetrievalParams(dsl)) { + const dslObject = dsl as Record; + const hasComponents = + !!dslObject.components && typeof dslObject.components === 'object'; + const locations = hasComponents + ? walkComponentsRetrievalParams(dslObject) + : walkGraphRetrievalParams(dslObject); + for (const { params } of locations) { if (params.retrieval_from === RetrievalFrom.Dataset) { const ids = params.dataset_ids ?? params.kb_ids; if (!Array.isArray(ids) || ids.length === 0) { From 97029b08f12653b8838b1d15ae716804e53f2914 Mon Sep 17 00:00:00 2001 From: Lynn Date: Thu, 10 Sep 2026 17:55:17 +0800 Subject: [PATCH 078/568] Fix: num token usage (#19495) --- common/token_utils.py | 12 +- internal/tokenizer/usage.go | 13 +- rag/llm/rerank_model.py | 45 ++++- .../rag/llm/test_rerank_token_count.py | 165 ++++++++++++++++++ 4 files changed, 222 insertions(+), 13 deletions(-) create mode 100644 test/unit_test/rag/llm/test_rerank_token_count.py diff --git a/common/token_utils.py b/common/token_utils.py index 391f0f3b892..a87d3299113 100644 --- a/common/token_utils.py +++ b/common/token_utils.py @@ -104,8 +104,10 @@ def record_run_token_usage(prompt_tokens: int = 0, completion_tokens: int = 0, t def usage_from_response(resp) -> dict: """Extract a {prompt_tokens, completion_tokens, total_tokens} split from an LLM response. - Handles OpenAI/OpenRouter-style ``resp.usage`` objects and dict variants. Missing - fields default to 0; ``total_tokens`` falls back to prompt+completion when absent. + Handles OpenAI/OpenRouter-style ``resp.usage`` objects and dict variants, including + the camelCase spelling (``promptTokens``/``completionTokens``/``totalTokens``) that + some providers such as Moark return. Missing fields default to 0; ``total_tokens`` + falls back to prompt+completion when absent. """ out = {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0} if resp is None: @@ -131,9 +133,9 @@ def _get(obj, *names): return int(v) return 0 - out["prompt_tokens"] = _get(usage, "prompt_tokens", "input_tokens") - out["completion_tokens"] = _get(usage, "completion_tokens", "output_tokens") - out["total_tokens"] = _get(usage, "total_tokens") + out["prompt_tokens"] = _get(usage, "prompt_tokens", "input_tokens", "promptTokens") + out["completion_tokens"] = _get(usage, "completion_tokens", "output_tokens", "completionTokens") + out["total_tokens"] = _get(usage, "total_tokens", "totalTokens") if not out["total_tokens"]: out["total_tokens"] = out["prompt_tokens"] + out["completion_tokens"] return out diff --git a/internal/tokenizer/usage.go b/internal/tokenizer/usage.go index 891c7fea0c8..ec41d973b78 100644 --- a/internal/tokenizer/usage.go +++ b/internal/tokenizer/usage.go @@ -137,9 +137,10 @@ func RecordRunTokenUsage(ctx context.Context, promptTokens, completionTokens, to } // UsageFromMap extracts a token usage split from a raw API response map. -// Handles OpenAI/OpenRouter-style resp["usage"] dicts. Missing fields -// default to 0; total_tokens falls back to prompt+completion when absent. -// Returns nil when no usage found. +// Handles OpenAI/OpenRouter-style resp["usage"] dicts, including the camelCase +// spelling (promptTokens/completionTokens/totalTokens) that some providers +// return. Missing fields default to 0; total_tokens falls back to +// prompt+completion when absent. Returns zeros when no usage found. // Mirrors Python's common.token_utils.usage_from_response(). func UsageFromMap(raw map[string]interface{}) (promptTokens, completionTokens, totalTokens int) { if raw == nil { @@ -153,9 +154,9 @@ func UsageFromMap(raw map[string]interface{}) (promptTokens, completionTokens, t if !ok { return 0, 0, 0 } - pt := getInt(usage, "prompt_tokens", "input_tokens") - ct := getInt(usage, "completion_tokens", "output_tokens") - tt := getInt(usage, "total_tokens") + pt := getInt(usage, "prompt_tokens", "input_tokens", "promptTokens") + ct := getInt(usage, "completion_tokens", "output_tokens", "completionTokens") + tt := getInt(usage, "total_tokens", "totalTokens") if tt == 0 { tt = pt + ct } diff --git a/rag/llm/rerank_model.py b/rag/llm/rerank_model.py index f4741820050..dc868a2d700 100644 --- a/rag/llm/rerank_model.py +++ b/rag/llm/rerank_model.py @@ -27,7 +27,7 @@ import requests from common.log_utils import log_exception -from common.token_utils import num_tokens_from_string, truncate, total_token_count_from_response +from common.token_utils import num_tokens_from_string, truncate, total_token_count_from_response, usage_from_response from rag.llm.mws_utils import mws_api_url, require_mws_token from rag.utils.url_utils import append_api_path, ensure_v1 @@ -37,6 +37,23 @@ raise ValueError(f"Invalid RERANK_TOKEN_LIMIT_MODE {RERANK_TOKEN_LIMIT_MODE!r}; expected 'truncate', 'passthrough', or 'raise_error'") +def _describe_rerank_usage(res) -> str: + """Describe where a rerank response keeps its token usage, for diagnostics. + + Providers disagree on the usage layout (``usage.total_tokens``, + ``usage.prompt_tokens``, ``meta.tokens``, ``meta.billed_units``, ...), and an + unmapped shape silently degrades ``token_count`` to 0. Only structural + fields are rendered here so the query and documents are never logged. + """ + if not isinstance(res, dict): + return f"response_type={type(res).__name__} (expected dict)" + usage = res.get("usage") + meta = res.get("meta") + usage_keys = sorted(usage) if isinstance(usage, dict) else usage + meta_keys = sorted(meta) if isinstance(meta, dict) else meta + return f"top_level_keys={sorted(res)}, usage={usage_keys}, meta={meta_keys}" + + class Base(ABC): def __init__(self, key, model_name, max_token=MAX_RERANK_TOKEN, **kwargs): self.max_token = max_token or MAX_RERANK_TOKEN @@ -57,6 +74,7 @@ def similarity(self, query: str, texts: List) -> Tuple[np.ndarray, int]: and must not normalize themselves. """ if not query or not texts: + logging.debug("Rerank %s short-circuits on empty input: query=%s texts=%d, returning 0 tokens", self.__class__.__name__, bool(query), len(texts) if texts else 0) return np.zeros(len(texts) if texts else 0, dtype=float), 0 if RERANK_TOKEN_LIMIT_MODE != "passthrough": query_tokens = num_tokens_from_string(query) @@ -131,7 +149,30 @@ def _compute_rank(self, query: str, texts: List) -> Tuple[np.ndarray, int]: rank[d["index"]] = d["relevance_score"] except Exception as _e: log_exception(_e, res) - return rank, total_token_count_from_response(res) + usage = usage_from_response(res) + token_count = usage["total_tokens"] + if token_count: + logging.debug( + "Rerank %s token usage from response: total_tokens=%d prompt_tokens=%d completion_tokens=%d", + self.__class__.__name__, + token_count, + usage["prompt_tokens"], + usage["completion_tokens"], + ) + else: + # Moark/GiteeAI report usage in camelCase and can still send zeros, so + # count the query and documents locally instead of reporting a + # zero-token rerank. + token_count = num_tokens_from_string(query) + sum(num_tokens_from_string(text) for text in texts) + logging.debug( + "Rerank %s response carried no usable token usage; fell back to local count=%d (model=%s endpoint=%s); response shape: %s", + self.__class__.__name__, + token_count, + self.model_name, + self.base_url, + _describe_rerank_usage(res), + ) + return rank, token_count class GreenPTRerank(JinaRerank): diff --git a/test/unit_test/rag/llm/test_rerank_token_count.py b/test/unit_test/rag/llm/test_rerank_token_count.py new file mode 100644 index 00000000000..f2396cd4f94 --- /dev/null +++ b/test/unit_test/rag/llm/test_rerank_token_count.py @@ -0,0 +1,165 @@ +# +# 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. +# +"""Regression tests for reranker token accounting. + +``JinaRerank`` and every provider that inherits it (NovitaAI, GiteeAI, +Jiekou.AI, GreenPT) report ``token_count`` from the HTTP response. The +providers disagree on the usage field names: Jina emits +``usage.total_tokens`` while GiteeAI/Moark emits OpenAI-style +``usage.prompt_tokens``/``completion_tokens`` in camelCase +(``promptTokens``/``completionTokens``/``totalTokens``). Reading the response +through the legacy ``total_token_count_from_response`` helper silently returned +0 for those shapes, so ``_compute_rank`` now goes through the shared +``usage_from_response`` helper and falls back to a local count when the +provider reports nothing usable. These tests pin every supported shape. +""" + +import logging +from unittest.mock import MagicMock, patch + +import numpy as np +import pytest + +from rag.llm.rerank_model import ( + GiteeRerank, + GreenPTRerank, + JiekouAIRerank, + JinaRerank, + NovitaRerank, +) + +pytestmark = pytest.mark.p1 + + +def _mock_post(payload): + """Patch ``requests.post`` so ``response.json()`` returns ``payload``.""" + response = MagicMock() + response.raise_for_status.return_value = None + response.json.return_value = payload + return patch("rag.llm.rerank_model.requests.post", return_value=response) + + +def _results(*scores): + return {"results": [{"index": index, "relevance_score": score} for index, score in enumerate(scores)]} + + +def _similarity(reranker, payload): + """Run ``similarity`` against a mocked response, bypassing real tokenization.""" + with _mock_post(payload), patch("rag.llm.rerank_model.num_tokens_from_string", return_value=1): + return reranker.similarity("query", ["first", "second"]) + + +def _jina(**kwargs): + return JinaRerank("key", base_url="http://example.test/rerank", **kwargs) + + +# --- Supported usage shapes ------------------------------------------------- + + +def test_jina_native_total_tokens_is_used(): + rank, tokens = _similarity(_jina(), {**_results(0.9, 0.1), "usage": {"total_tokens": 42}}) + assert tokens == 42 + assert np.allclose(rank, [0.9, 0.1]) + + +def test_openai_style_prompt_and_completion_tokens_are_summed(): + """GiteeAI/Moark omits ``total_tokens``; the count must still be reported.""" + payload = {**_results(0.9, 0.1), "usage": {"prompt_tokens": 7, "completion_tokens": 3}} + _, tokens = _similarity(_jina(), payload) + assert tokens == 10 + + +def test_openai_style_total_tokens_takes_precedence(): + payload = {**_results(0.5), "usage": {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 12}} + _, tokens = _similarity(_jina(), payload) + assert tokens == 12 + + +def test_anthropic_style_input_and_output_tokens_are_summed(): + payload = {**_results(0.5), "usage": {"input_tokens": 5, "output_tokens": 2}} + _, tokens = _similarity(_jina(), payload) + assert tokens == 7 + + +def test_camel_case_prompt_and_completion_tokens_are_summed(): + """Moark/GiteeAI spell the OpenAI fields in camelCase.""" + payload = {**_results(0.5), "usage": {"promptTokens": 7, "completionTokens": 3}} + _, tokens = _similarity(_jina(), payload) + assert tokens == 10 + + +def test_camel_case_total_tokens_takes_precedence(): + payload = {**_results(0.5), "usage": {"promptTokens": 7, "completionTokens": 3, "totalTokens": 12}} + _, tokens = _similarity(_jina(), payload) + assert tokens == 12 + + +# --- Local fallback when the provider reports nothing usable ---------------- +# +# ``_similarity`` patches ``num_tokens_from_string`` to return 1, so the local +# fallback counts the query plus the two documents as 3. + + +def test_missing_usage_falls_back_to_local_count(): + _, tokens = _similarity(_jina(), _results(0.5)) + assert tokens == 3 + + +def test_zero_valued_usage_falls_back_to_local_count(): + """The exact Moark shape: camelCase keys that still carry zeros.""" + payload = {**_results(0.5), "usage": {"totalTokens": 0, "promptTokens": 0}} + _, tokens = _similarity(_jina(), payload) + assert tokens == 3 + + +# --- Diagnostics ------------------------------------------------------------ + + +def test_unmapped_usage_falls_back_and_logs_response_shape(caplog): + """An unrecognized usage layout must be traceable without dumping content.""" + payload = {**_results(0.5), "meta": {"billed_units": {"search_units": 1}}} + with caplog.at_level(logging.DEBUG): + _, tokens = _similarity(_jina(), payload) + assert tokens == 3 + assert any("fell back to local count=3" in record.getMessage() for record in caplog.records) + assert any("meta=['billed_units']" in record.getMessage() for record in caplog.records) + + +def test_mapped_usage_logs_resolved_split(caplog): + payload = {**_results(0.5), "usage": {"prompt_tokens": 7, "completion_tokens": 3}} + with caplog.at_level(logging.DEBUG): + _, tokens = _similarity(_jina(), payload) + assert tokens == 10 + assert any("total_tokens=10 prompt_tokens=7 completion_tokens=3" in record.getMessage() for record in caplog.records) + + +# --- Every Jina-family provider inherits the fix ---------------------------- + + +@pytest.mark.parametrize( + ("factory", "kwargs"), + [ + (JinaRerank, {"base_url": "http://example.test/rerank"}), + (NovitaRerank, {}), + (GiteeRerank, {}), + (JiekouAIRerank, {}), + (GreenPTRerank, {}), + ], +) +def test_jina_family_providers_count_openai_style_usage(factory, kwargs): + payload = {**_results(0.4, 0.6), "usage": {"prompt_tokens": 11, "completion_tokens": 4}} + _, tokens = _similarity(factory("key", "test-model", **kwargs), payload) + assert tokens == 15 From 5bd80b3455b6670cd07e0cd09c8a08a5ada6bee7 Mon Sep 17 00:00:00 2001 From: Liu An Date: Thu, 10 Sep 2026 18:35:02 +0800 Subject: [PATCH 079/568] Docs: Update version references to v0.27.2 in READMEs and docs (#19501) - Update version tags in README files (including translations) from v0.27.1 to v0.27.2 - Modify Docker image references and documentation to reflect new version - Update version badges and image descriptions - Maintain consistency across all language variants of README files --- README.md | 6 +++--- README_ar.md | 6 +++--- README_fr.md | 6 +++--- README_id.md | 6 +++--- README_ja.md | 6 +++--- README_ko.md | 6 +++--- README_pt_br.md | 6 +++--- README_ru.md | 6 +++--- README_tr.md | 6 +++--- README_tzh.md | 6 +++--- README_zh.md | 6 +++--- admin/client/README.md | 2 +- admin/client/pyproject.toml | 2 +- admin/client/uv.lock | 2 +- docker/.env | 6 +++--- docker/README.md | 2 +- docs/administrator/admin/ragflow_cli.md | 4 ++-- .../configurations/configurations.md | 2 +- .../migration/database_schema_and_migration.md | 2 +- docs/administrator/upgrade_ragflow.mdx | 10 +++++----- docs/develop/build_docker_image.mdx | 2 +- docs/faq.mdx | 6 +++--- docs/quickstart.mdx | 6 +++--- helm/values.yaml | 2 +- pyproject.toml | 2 +- sdk/python/pyproject.toml | 2 +- sdk/python/uv.lock | 2 +- test/README.md | 2 +- tools/scripts/README.md | 18 +++++++++--------- tools/scripts/db_schema_sync.py | 16 ++++++++-------- tools/scripts/mysql_migration.py | 10 +++++----- tools/scripts/run_migrations.sh | 2 +- uv.lock | 2 +- 33 files changed, 85 insertions(+), 85 deletions(-) diff --git a/README.md b/README.md index 0fbbff183aa..3418232ddb2 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ Static Badge - docker pull infiniflow/ragflow:v0.27.1 + docker pull infiniflow/ragflow:v0.27.2 Latest Release @@ -193,12 +193,12 @@ releases! 🌟 > All Docker images are built for x86 platforms. We don't currently offer Docker images for ARM64. > If you are on an ARM64 platform, follow [this guide](https://ragflow.io/docs/dev/build_docker_image) to build a Docker image compatible with your system. -> The command below downloads the `v0.27.1` edition of the RAGFlow Docker image. See the following table for descriptions of different RAGFlow editions. To download a RAGFlow edition different from `v0.27.1`, update the `RAGFLOW_IMAGE` variable accordingly in **docker/.env** before using `docker compose` to start the server. +> The command below downloads the `v0.27.2` edition of the RAGFlow Docker image. See the following table for descriptions of different RAGFlow editions. To download a RAGFlow edition different from `v0.27.2`, update the `RAGFLOW_IMAGE` variable accordingly in **docker/.env** before using `docker compose` to start the server. ```bash cd ragflow/docker - git checkout v0.27.1 + git checkout v0.27.2 # Optional: use a stable tag (see releases: https://github.com/infiniflow/ragflow/releases) # This step ensures the **entrypoint.sh** file in the code matches the Docker image version. diff --git a/README_ar.md b/README_ar.md index f78763bf240..3ca48a90c03 100644 --- a/README_ar.md +++ b/README_ar.md @@ -26,7 +26,7 @@ Static Badge - docker pull infiniflow/ragflow:v0.27.1 + docker pull infiniflow/ragflow:v0.27.2 Latest Release @@ -194,12 +194,12 @@ > جميع الصور Docker مصممة لمنصات x86. لا نعرض حاليًا صور Docker لـ ARM64. > إذا كنت تستخدم نظامًا أساسيًا ARM64، فاتبع [هذا الدليل](https://ragflow.io/docs/dev/build_docker_image) لإنشاء صورة Docker متوافقة مع نظامك. -> يقوم الأمر أدناه بتنزيل إصدار `v0.27.1` من الصورة RAGFlow Docker. راجع الجدول التالي للحصول على أوصاف لإصدارات RAGFlow المختلفة. لتنزيل إصدار RAGFlow مختلف عن `v0.27.1`، قم بتحديث المتغير `RAGFLOW_IMAGE` وفقًا لذلك في **docker/.env** قبل استخدام `docker compose` لبدء تشغيل الخادم. +> يقوم الأمر أدناه بتنزيل إصدار `v0.27.2` من الصورة RAGFlow Docker. راجع الجدول التالي للحصول على أوصاف لإصدارات RAGFlow المختلفة. لتنزيل إصدار RAGFlow مختلف عن `v0.27.2`، قم بتحديث المتغير `RAGFLOW_IMAGE` وفقًا لذلك في **docker/.env** قبل استخدام `docker compose` لبدء تشغيل الخادم. ```bash cd ragflow/docker - git checkout v0.27.1 + git checkout v0.27.2 # Optional: use a stable tag (see releases: https://github.com/infiniflow/ragflow/releases) # This step ensures the **entrypoint.sh** file in the code matches the Docker image version. diff --git a/README_fr.md b/README_fr.md index ee3ce023c50..4cd20b76a95 100644 --- a/README_fr.md +++ b/README_fr.md @@ -26,7 +26,7 @@ Badge statique - docker pull infiniflow/ragflow:v0.27.1 + docker pull infiniflow/ragflow:v0.27.2 Dernière version @@ -191,12 +191,12 @@ Essayez notre service cloud sur [https://cloud.ragflow.io](https://cloud.ragflow > Toutes les images Docker sont construites pour les plateformes x86. Nous ne proposons pas actuellement d'images Docker pour ARM64. > Si vous êtes sur une plateforme ARM64, suivez [ce guide](https://ragflow.io/docs/dev/build_docker_image) pour construire une image Docker compatible avec votre système. -> La commande ci-dessous télécharge l'édition `v0.27.1` de l'image Docker RAGFlow. Consultez le tableau suivant pour les descriptions des différentes éditions de RAGFlow. Pour télécharger une édition de RAGFlow différente de `v0.27.1`, mettez à jour la variable `RAGFLOW_IMAGE` dans **docker/.env** avant d'utiliser `docker compose` pour démarrer le serveur. +> La commande ci-dessous télécharge l'édition `v0.27.2` de l'image Docker RAGFlow. Consultez le tableau suivant pour les descriptions des différentes éditions de RAGFlow. Pour télécharger une édition de RAGFlow différente de `v0.27.2`, mettez à jour la variable `RAGFLOW_IMAGE` dans **docker/.env** avant d'utiliser `docker compose` pour démarrer le serveur. ```bash cd ragflow/docker - git checkout v0.27.1 + git checkout v0.27.2 # Optionnel : utiliser un tag stable (voir les versions : https://github.com/infiniflow/ragflow/releases) # Cette étape garantit que le fichier **entrypoint.sh** dans le code correspond à la version de l'image Docker. diff --git a/README_id.md b/README_id.md index 7921378511f..6a6f2c45092 100644 --- a/README_id.md +++ b/README_id.md @@ -26,7 +26,7 @@ Lencana Daring - docker pull infiniflow/ragflow:v0.27.1 + docker pull infiniflow/ragflow:v0.27.2 Rilis Terbaru @@ -192,12 +192,12 @@ Coba layanan cloud kami di [https://cloud.ragflow.io](https://cloud.ragflow.io). > Semua gambar Docker dibangun untuk platform x86. Saat ini, kami tidak menawarkan gambar Docker untuk ARM64. > Jika Anda menggunakan platform ARM64, [silakan gunakan panduan ini untuk membangun gambar Docker yang kompatibel dengan sistem Anda](https://ragflow.io/docs/dev/build_docker_image). -> Perintah di bawah ini mengunduh edisi v0.27.1 dari gambar Docker RAGFlow. Silakan merujuk ke tabel berikut untuk deskripsi berbagai edisi RAGFlow. Untuk mengunduh edisi RAGFlow yang berbeda dari v0.27.1, perbarui variabel RAGFLOW_IMAGE di docker/.env sebelum menggunakan docker compose untuk memulai server. +> Perintah di bawah ini mengunduh edisi v0.27.2 dari gambar Docker RAGFlow. Silakan merujuk ke tabel berikut untuk deskripsi berbagai edisi RAGFlow. Untuk mengunduh edisi RAGFlow yang berbeda dari v0.27.2, perbarui variabel RAGFLOW_IMAGE di docker/.env sebelum menggunakan docker compose untuk memulai server. ```bash cd ragflow/docker - git checkout v0.27.1 + git checkout v0.27.2 # Opsional: gunakan tag stabil (lihat releases: https://github.com/infiniflow/ragflow/releases) # This steps ensures the **entrypoint.sh** file in the code matches the Docker image version. diff --git a/README_ja.md b/README_ja.md index b6cc89571d0..775b7ea7c16 100644 --- a/README_ja.md +++ b/README_ja.md @@ -26,7 +26,7 @@ Static Badge - docker pull infiniflow/ragflow:v0.27.1 + docker pull infiniflow/ragflow:v0.27.2 Latest Release @@ -173,12 +173,12 @@ > 現在、公式に提供されているすべての Docker イメージは x86 アーキテクチャ向けにビルドされており、ARM64 用の Docker イメージは提供されていません。 > ARM64 アーキテクチャのオペレーティングシステムを使用している場合は、[このドキュメント](https://ragflow.io/docs/dev/build_docker_image)を参照して Docker イメージを自分でビルドしてください。 -> 以下のコマンドは、RAGFlow Docker イメージの v0.27.1 エディションをダウンロードします。異なる RAGFlow エディションの説明については、以下の表を参照してください。v0.27.1 とは異なるエディションをダウンロードするには、docker/.env ファイルの RAGFLOW_IMAGE 変数を適宜更新し、docker compose を使用してサーバーを起動してください。 +> 以下のコマンドは、RAGFlow Docker イメージの v0.27.2 エディションをダウンロードします。異なる RAGFlow エディションの説明については、以下の表を参照してください。v0.27.2 とは異なるエディションをダウンロードするには、docker/.env ファイルの RAGFLOW_IMAGE 変数を適宜更新し、docker compose を使用してサーバーを起動してください。 ```bash cd ragflow/docker - git checkout v0.27.1 + git checkout v0.27.2 # 任意: 安定版タグを利用 (一覧: https://github.com/infiniflow/ragflow/releases) # この手順は、コード内の entrypoint.sh ファイルが Docker イメージのバージョンと一致していることを確認します。 diff --git a/README_ko.md b/README_ko.md index 68fd6d69911..10d1ac1556b 100644 --- a/README_ko.md +++ b/README_ko.md @@ -26,7 +26,7 @@ Static Badge - docker pull infiniflow/ragflow:v0.27.1 + docker pull infiniflow/ragflow:v0.27.2 Latest Release @@ -175,12 +175,12 @@ > 모든 Docker 이미지는 x86 플랫폼을 위해 빌드되었습니다. 우리는 현재 ARM64 플랫폼을 위한 Docker 이미지를 제공하지 않습니다. > ARM64 플랫폼을 사용 중이라면, [시스템과 호환되는 Docker 이미지를 빌드하려면 이 가이드를 사용해 주세요](https://ragflow.io/docs/dev/build_docker_image). - > 아래 명령어는 RAGFlow Docker 이미지의 v0.27.1 버전을 다운로드합니다. 다양한 RAGFlow 버전에 대한 설명은 다음 표를 참조하십시오. v0.27.1와 다른 RAGFlow 버전을 다운로드하려면, docker/.env 파일에서 RAGFLOW_IMAGE 변수를 적절히 업데이트한 후 docker compose를 사용하여 서버를 시작하십시오. + > 아래 명령어는 RAGFlow Docker 이미지의 v0.27.2 버전을 다운로드합니다. 다양한 RAGFlow 버전에 대한 설명은 다음 표를 참조하십시오. v0.27.2와 다른 RAGFlow 버전을 다운로드하려면, docker/.env 파일에서 RAGFLOW_IMAGE 변수를 적절히 업데이트한 후 docker compose를 사용하여 서버를 시작하십시오. ```bash cd ragflow/docker - git checkout v0.27.1 + git checkout v0.27.2 # Optional: use a stable tag (see releases: https://github.com/infiniflow/ragflow/releases) # 이 단계는 코드의 entrypoint.sh 파일이 Docker 이미지 버전과 일치하도록 보장합니다. diff --git a/README_pt_br.md b/README_pt_br.md index 695bcd61a36..75d65c7a654 100644 --- a/README_pt_br.md +++ b/README_pt_br.md @@ -26,7 +26,7 @@ Badge Estático - docker pull infiniflow/ragflow:v0.27.1 + docker pull infiniflow/ragflow:v0.27.2 Última Release @@ -191,12 +191,12 @@ Experimente o nosso serviço na nuvem em [https://cloud.ragflow.io](https://clou > Todas as imagens Docker são construídas para plataformas x86. Atualmente, não oferecemos imagens Docker para ARM64. > Se você estiver usando uma plataforma ARM64, por favor, utilize [este guia](https://ragflow.io/docs/dev/build_docker_image) para construir uma imagem Docker compatível com o seu sistema. - > O comando abaixo baixa a edição`v0.27.1` da imagem Docker do RAGFlow. Consulte a tabela a seguir para descrições de diferentes edições do RAGFlow. Para baixar uma edição do RAGFlow diferente da `v0.27.1`, atualize a variável `RAGFLOW_IMAGE` conforme necessário no **docker/.env** antes de usar `docker compose` para iniciar o servidor. + > O comando abaixo baixa a edição`v0.27.2` da imagem Docker do RAGFlow. Consulte a tabela a seguir para descrições de diferentes edições do RAGFlow. Para baixar uma edição do RAGFlow diferente da `v0.27.2`, atualize a variável `RAGFLOW_IMAGE` conforme necessário no **docker/.env** antes de usar `docker compose` para iniciar o servidor. ```bash cd ragflow/docker - git checkout v0.27.1 + git checkout v0.27.2 # Opcional: use uma tag estável (veja releases: https://github.com/infiniflow/ragflow/releases) # Esta etapa garante que o arquivo entrypoint.sh no código corresponda à versão da imagem do Docker. diff --git a/README_ru.md b/README_ru.md index 823bc83b4c8..d6807a6cfa3 100644 --- a/README_ru.md +++ b/README_ru.md @@ -26,7 +26,7 @@ Static Badge - docker pull infiniflow/ragflow:v0.27.1 + docker pull infiniflow/ragflow:v0.27.2 Последний релиз @@ -191,12 +191,12 @@ > Все образы собраны под x86. Образов для ARM64 пока нет. > Если вы на ARM64, следуйте [этому руководству](https://ragflow.io/docs/dev/build_docker_image), чтобы собрать образ самостоятельно. -> Команда ниже скачивает образ `v0.27.1`. Чтобы использовать другую версию, измените `RAGFLOW_IMAGE` в файле **docker/.env** перед запуском. +> Команда ниже скачивает образ `v0.27.2`. Чтобы использовать другую версию, измените `RAGFLOW_IMAGE` в файле **docker/.env** перед запуском. ```bash cd ragflow/docker - git checkout v0.27.1 + git checkout v0.27.2 # Опционально: используйте стабильный тег (см. релизы) # Это гарантирует, что entrypoint.sh соответствует версии образа. diff --git a/README_tr.md b/README_tr.md index a7a47ae0fdf..e8f51fee862 100644 --- a/README_tr.md +++ b/README_tr.md @@ -26,7 +26,7 @@ Çevrimiçi Demo - docker pull infiniflow/ragflow:v0.27.1 + docker pull infiniflow/ragflow:v0.27.2 Son Sürüm @@ -192,12 +192,12 @@ Bulut hizmetimizi [https://cloud.ragflow.io](https://cloud.ragflow.io) adresinde > Tüm Docker imajları x86 platformları için oluşturulmuştur. Şu anda ARM64 için Docker imajı sunmuyoruz. > ARM64 platformundaysanız, sisteminizle uyumlu bir Docker imajı oluşturmak için [bu kılavuzu](https://ragflow.io/docs/dev/build_docker_image) takip edin. -> Aşağıdaki komut RAGFlow Docker imajının `v0.27.1` sürümünü indirir. Farklı RAGFlow sürümleri için aşağıdaki tabloya bakın. `v0.27.1` dışında bir sürüm indirmek için, `docker compose` ile sunucuyu başlatmadan önce **docker/.env** dosyasındaki `RAGFLOW_IMAGE` değişkenini güncelleyin. +> Aşağıdaki komut RAGFlow Docker imajının `v0.27.2` sürümünü indirir. Farklı RAGFlow sürümleri için aşağıdaki tabloya bakın. `v0.27.2` dışında bir sürüm indirmek için, `docker compose` ile sunucuyu başlatmadan önce **docker/.env** dosyasındaki `RAGFLOW_IMAGE` değişkenini güncelleyin. ```bash cd ragflow/docker - git checkout v0.27.1 + git checkout v0.27.2 # İsteğe bağlı: Kararlı bir etiket kullanın (sürümler: https://github.com/infiniflow/ragflow/releases) # Bu adım, koddaki **entrypoint.sh** dosyasının Docker imaj sürümüyle eşleşmesini sağlar. diff --git a/README_tzh.md b/README_tzh.md index 5dc06fa0695..799c449b0a9 100644 --- a/README_tzh.md +++ b/README_tzh.md @@ -26,7 +26,7 @@ Static Badge - docker pull infiniflow/ragflow:v0.27.1 + docker pull infiniflow/ragflow:v0.27.2 Latest Release @@ -192,12 +192,12 @@ > 所有 Docker 映像檔都是為 x86 平台建置的。目前,我們不提供 ARM64 平台的 Docker 映像檔。 > 如果您使用的是 ARM64 平台,請使用 [這份指南](https://ragflow.io/docs/dev/build_docker_image) 來建置適合您系統的 Docker 映像檔。 -> 執行以下指令會自動下載 RAGFlow Docker 映像 `v0.27.1`。請參考下表查看不同 Docker 發行版的說明。如需下載不同於 `v0.27.1` 的 Docker 映像,請在執行 `docker compose` 啟動服務之前先更新 **docker/.env** 檔案內的 `RAGFLOW_IMAGE` 變數。 +> 執行以下指令會自動下載 RAGFlow Docker 映像 `v0.27.2`。請參考下表查看不同 Docker 發行版的說明。如需下載不同於 `v0.27.2` 的 Docker 映像,請在執行 `docker compose` 啟動服務之前先更新 **docker/.env** 檔案內的 `RAGFLOW_IMAGE` 變數。 ```bash cd ragflow/docker - git checkout v0.27.1 + git checkout v0.27.2 # 可選:使用穩定版標籤(查看發佈:https://github.com/infiniflow/ragflow/releases) # 此步驟確保程式碼中的 entrypoint.sh 檔案與 Docker 映像版本一致。 diff --git a/README_zh.md b/README_zh.md index 67ffbdd433d..7afa5875852 100644 --- a/README_zh.md +++ b/README_zh.md @@ -26,7 +26,7 @@ Static Badge - docker pull infiniflow/ragflow:v0.27.1 + docker pull infiniflow/ragflow:v0.27.2 Latest Release @@ -193,12 +193,12 @@ > 请注意,目前官方提供的所有 Docker 镜像均基于 x86 架构构建,并不提供基于 ARM64 的 Docker 镜像。 > 如果你的操作系统是 ARM64 架构,请参考[这篇文档](https://ragflow.io/docs/dev/build_docker_image)自行构建 Docker 镜像。 - > 运行以下命令会自动下载 RAGFlow Docker 镜像 `v0.27.1`。请参考下表查看不同 Docker 发行版的描述。如需下载不同于 `v0.27.1` 的 Docker 镜像,请在运行 `docker compose` 启动服务之前先更新 **docker/.env** 文件内的 `RAGFLOW_IMAGE` 变量。 + > 运行以下命令会自动下载 RAGFlow Docker 镜像 `v0.27.2`。请参考下表查看不同 Docker 发行版的描述。如需下载不同于 `v0.27.2` 的 Docker 镜像,请在运行 `docker compose` 启动服务之前先更新 **docker/.env** 文件内的 `RAGFLOW_IMAGE` 变量。 ```bash cd ragflow/docker - git checkout v0.27.1 + git checkout v0.27.2 # 可选:使用稳定版本标签(查看发布:https://github.com/infiniflow/ragflow/releases) # 这一步确保代码中的 entrypoint.sh 文件与 Docker 镜像的版本保持一致。 diff --git a/admin/client/README.md b/admin/client/README.md index ceb86f90469..4cfabc5dc12 100644 --- a/admin/client/README.md +++ b/admin/client/README.md @@ -48,7 +48,7 @@ It consists of a server-side Service and a command-line client (CLI), both imple 1. Ensure the Admin Service is running. 2. Install ragflow-cli. ```bash - pip install ragflow-cli==0.27.1 + pip install ragflow-cli==0.27.2 ``` 3. Launch the CLI client: ```bash diff --git a/admin/client/pyproject.toml b/admin/client/pyproject.toml index c441be4ea28..926b704503b 100644 --- a/admin/client/pyproject.toml +++ b/admin/client/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "ragflow-cli" -version = "0.27.1" +version = "0.27.2" description = "Admin Service's client of [RAGFlow](https://github.com/infiniflow/ragflow). The Admin Service provides user management and system monitoring. " authors = [{ name = "Lynn", email = "lynn_inf@hotmail.com" }] license = { text = "Apache License, Version 2.0" } diff --git a/admin/client/uv.lock b/admin/client/uv.lock index 7696e36543c..27b0f960ae3 100644 --- a/admin/client/uv.lock +++ b/admin/client/uv.lock @@ -159,7 +159,7 @@ wheels = [ [[package]] name = "ragflow-cli" -version = "0.27.1" +version = "0.27.2" source = { virtual = "." } dependencies = [ { name = "beartype" }, diff --git a/docker/.env b/docker/.env index 67ecec39657..a933326bfd1 100644 --- a/docker/.env +++ b/docker/.env @@ -255,11 +255,11 @@ API_PROXY_SCHEME=python # use pure python server deployment ALLOW_ANY_HOST=0 # The RAGFlow Docker image to download. v0.22+ doesn't include embedding models. -RAGFLOW_IMAGE=infiniflow/ragflow:v0.27.1 +RAGFLOW_IMAGE=infiniflow/ragflow:v0.27.2 # If you cannot download the RAGFlow Docker image: -# RAGFLOW_IMAGE=swr.cn-north-4.myhuaweicloud.com/infiniflow/ragflow:v0.27.1 -# RAGFLOW_IMAGE=registry.cn-hangzhou.aliyuncs.com/infiniflow/ragflow:v0.27.1 +# RAGFLOW_IMAGE=swr.cn-north-4.myhuaweicloud.com/infiniflow/ragflow:v0.27.2 +# RAGFLOW_IMAGE=registry.cn-hangzhou.aliyuncs.com/infiniflow/ragflow:v0.27.2 # # - For the `nightly` edition, uncomment either of the following: # RAGFLOW_IMAGE=swr.cn-north-4.myhuaweicloud.com/infiniflow/ragflow:nightly diff --git a/docker/README.md b/docker/README.md index 41f1ce9bf16..3f0288b103f 100644 --- a/docker/README.md +++ b/docker/README.md @@ -90,7 +90,7 @@ The [.env](./.env) file contains important environment variables for Docker. - `SVR_HTTP_PORT` The port used to expose RAGFlow's HTTP API service to the host machine, allowing **external** access to the service running inside the Docker container. Defaults to `9380`. - `RAGFLOW_IMAGE` - The Docker image edition. Defaults to `infiniflow/ragflow:v0.27.1`. The RAGFlow Docker image does not include embedding models. + The Docker image edition. Defaults to `infiniflow/ragflow:v0.27.2`. The RAGFlow Docker image does not include embedding models. > [!TIP] diff --git a/docs/administrator/admin/ragflow_cli.md b/docs/administrator/admin/ragflow_cli.md index ac81561a726..7a7df76375a 100644 --- a/docs/administrator/admin/ragflow_cli.md +++ b/docs/administrator/admin/ragflow_cli.md @@ -18,9 +18,9 @@ The RAGFlow CLI is a command-line-based system administration tool that offers a 2. Install ragflow-cli. ```bash - pipx install ragflow-cli==0.27.1 + pipx install ragflow-cli==0.27.2 ``` - > You can also use `uv`, a tool for managing virtual environments and packages, to install RAGFlow CLI: `uv tool install ragflow-cli@0.27.1`. + > You can also use `uv`, a tool for managing virtual environments and packages, to install RAGFlow CLI: `uv tool install ragflow-cli@0.27.2`. 3. Launch the CLI client: diff --git a/docs/administrator/configurations/configurations.md b/docs/administrator/configurations/configurations.md index e2408f8d86c..7982e55992f 100644 --- a/docs/administrator/configurations/configurations.md +++ b/docs/administrator/configurations/configurations.md @@ -103,7 +103,7 @@ RAGFlow utilizes MinIO as its object storage solution, leveraging its scalabilit - `SVR_HTTP_PORT` The port used to expose RAGFlow's HTTP API service to the host machine, allowing **external** access to the service running inside the Docker container. Defaults to `9380`. - `RAGFLOW_IMAGE` - The Docker image edition. Defaults to `infiniflow/ragflow:v0.27.1` (the RAGFlow Docker image without embedding models). + The Docker image edition. Defaults to `infiniflow/ragflow:v0.27.2` (the RAGFlow Docker image without embedding models). :::tip NOTE If you cannot download the RAGFlow Docker image, try the following mirrors. diff --git a/docs/administrator/migration/database_schema_and_migration.md b/docs/administrator/migration/database_schema_and_migration.md index ec27ff49993..8dba51813dc 100644 --- a/docs/administrator/migration/database_schema_and_migration.md +++ b/docs/administrator/migration/database_schema_and_migration.md @@ -45,7 +45,7 @@ The [db_schema_sync.py](https://github.com/infiniflow/ragflow/blob/main/tools/sc ### Key Functions - **Change detection**: Compares Python model definitions in `api/db/db_models.py` against the live database to identify new tables, added fields, or type mismatches. -- **Migration generation**: Automatically creates Python migration files (containing `migrate()` and `rollback()` logic) in version-specific directories (e.g., `tools/migrate/v0_27_1/`). +- **Migration generation**: Automatically creates Python migration files (containing `migrate()` and `rollback()` logic) in version-specific directories (e.g., `tools/migrate/v0_27_2/`). - **Schema auditing**: Provides a `--diff` command to view structural discrepancies without applying changes. - **Execution management**: Applies pending migrations to the database to bring it up to date with the current software version. - **Safety controls**: Prevents accidental data loss by requiring an explicit `--drop` flag to generate `DROP COLUMN` statements for removed fields. diff --git a/docs/administrator/upgrade_ragflow.mdx b/docs/administrator/upgrade_ragflow.mdx index 67f4b5bdb03..fe0c5fc29dc 100644 --- a/docs/administrator/upgrade_ragflow.mdx +++ b/docs/administrator/upgrade_ragflow.mdx @@ -64,16 +64,16 @@ To upgrade RAGFlow, you must upgrade **both** your code **and** your Docker imag git pull ``` -3. Switch to the latest, officially published release, e.g., `v0.27.1`: +3. Switch to the latest, officially published release, e.g., `v0.27.2`: ```bash - git checkout -f v0.27.1 + git checkout -f v0.27.2 ``` 4. Update **ragflow/docker/.env**: ```bash - RAGFLOW_IMAGE=infiniflow/ragflow:v0.27.1 + RAGFLOW_IMAGE=infiniflow/ragflow:v0.27.2 ``` 5. Update the RAGFlow image and restart RAGFlow: @@ -94,10 +94,10 @@ No, you do not need to. Upgrading RAGFlow in itself will *not* remove your uploa 1. From an environment with Internet access, pull the required Docker image. 2. Save the Docker image to a **.tar** file. ```bash - docker save -o ragflow.v0.27.1.tar infiniflow/ragflow:v0.27.1 + docker save -o ragflow.v0.27.2.tar infiniflow/ragflow:v0.27.2 ``` 3. Copy the **.tar** file to the target server. 4. Load the **.tar** file into Docker: ```bash - docker load -i ragflow.v0.27.1.tar + docker load -i ragflow.v0.27.2.tar ``` diff --git a/docs/develop/build_docker_image.mdx b/docs/develop/build_docker_image.mdx index 73b8bd8323a..9f1fd5bb693 100644 --- a/docs/develop/build_docker_image.mdx +++ b/docs/develop/build_docker_image.mdx @@ -52,7 +52,7 @@ After building the infiniflow/ragflow:nightly image, you are ready to launch a f 1. Edit Docker Compose Configuration -Open the `docker/.env` file. Find the `RAGFLOW_IMAGE` setting and change the image reference from `infiniflow/ragflow:v0.27.1` to `infiniflow/ragflow:nightly` to use the pre-built image. +Open the `docker/.env` file. Find the `RAGFLOW_IMAGE` setting and change the image reference from `infiniflow/ragflow:v0.27.2` to `infiniflow/ragflow:nightly` to use the pre-built image. 2. Launch the Service diff --git a/docs/faq.mdx b/docs/faq.mdx index 9d865efd6c3..cbc6c29ed70 100644 --- a/docs/faq.mdx +++ b/docs/faq.mdx @@ -147,12 +147,12 @@ When debugging your chat assistant, you can use AI search as a reference to veri --- -### Get a `Request error 404: undefined` when upgrading to v0.27.1 +### Get a `Request error 404: undefined` when upgrading to v0.27.2 To resolve this issue, do either of the following: -- Pull the latest source code from the [main branch](https://github.com/infiniflow/ragflow), then pull and start the v0.27.1 image. -- Update `RAGFLOW_IMAGE` from `infiniflow/ragflow:latest` to `infiniflow/ragflow:v0.27.1` in the [.env file](https://github.com/infiniflow/ragflow/blob/main/docker/.env), then restart the service. +- Pull the latest source code from the [main branch](https://github.com/infiniflow/ragflow), then pull and start the v0.27.2 image. +- Update `RAGFLOW_IMAGE` from `infiniflow/ragflow:latest` to `infiniflow/ragflow:v0.27.2` in the [.env file](https://github.com/infiniflow/ragflow/blob/main/docker/.env), then restart the service. ### How to build the RAGFlow image from scratch? diff --git a/docs/quickstart.mdx b/docs/quickstart.mdx index 7894b242f1e..c2e3da2fb91 100644 --- a/docs/quickstart.mdx +++ b/docs/quickstart.mdx @@ -49,7 +49,7 @@ This section provides instructions on setting up the RAGFlow server on Linux. If `vm.max_map_count`. This value sets the maximum number of memory map areas a process may have. Its default value is 65530. While most applications require fewer than a thousand maps, reducing this value can result in abnormal behaviors, and the system will throw out-of-memory errors when a process reaches the limitation. - RAGFlow v0.27.1 uses Elasticsearch or [Infinity](https://github.com/infiniflow/infinity) for multiple recall. Setting the value of `vm.max_map_count` correctly is crucial to the proper functioning of the Elasticsearch component. + RAGFlow v0.27.2 uses Elasticsearch or [Infinity](https://github.com/infiniflow/infinity) for multiple recall. Setting the value of `vm.max_map_count` correctly is crucial to the proper functioning of the Elasticsearch component. bool: def version_to_dirname(version: str) -> str: - """Convert version string to valid directory name (e.g., 'v0.27.1' -> 'v0_27_1')""" + """Convert version string to valid directory name (e.g., 'v0.27.2' -> 'v0_27_2')""" return version.replace(".", "_") @@ -843,19 +843,19 @@ def main(): epilog=""" Examples: # List all migrations - python db_schema_sync.py --list --host localhost --port 3306 --user root --password xxx --database rag_flow --version v0.27.1 + python db_schema_sync.py --list --host localhost --port 3306 --user root --password xxx --database rag_flow --version v0.27.2 # Create migration from model changes - python db_schema_sync.py --create --host localhost --port 3306 --user root --password xxx --database rag_flow --version v0.27.1 + python db_schema_sync.py --create --host localhost --port 3306 --user root --password xxx --database rag_flow --version v0.27.2 # Create migration including dropped fields (destructive!) - python db_schema_sync.py --create --drop --host localhost --port 3306 --user root --password xxx --database rag_flow --version v0.27.1 + python db_schema_sync.py --create --drop --host localhost --port 3306 --user root --password xxx --database rag_flow --version v0.27.2 # Run all pending migrations - python db_schema_sync.py --migrate --host localhost --port 3306 --user root --password xxx --database rag_flow --version v0.27.1 + python db_schema_sync.py --migrate --host localhost --port 3306 --user root --password xxx --database rag_flow --version v0.27.2 # Show schema differences - python db_schema_sync.py --diff --host localhost --port 3306 --user root --password xxx --database rag_flow --version v0.27.1 + python db_schema_sync.py --diff --host localhost --port 3306 --user root --password xxx --database rag_flow --version v0.27.2 """, ) @@ -867,7 +867,7 @@ def main(): parser.add_argument("--database", type=str, required=True, help="MySQL database name") # Version option - parser.add_argument("--version", "-v", type=str, required=True, help="Version number in format vxx.xx.xx (e.g., v0.27.1)") + parser.add_argument("--version", "-v", type=str, required=True, help="Version number in format vxx.xx.xx (e.g., v0.27.2)") # Action options parser.add_argument("--list", "-l", action="store_true", help="List all migrations") @@ -883,7 +883,7 @@ def main(): # Validate version format if not validate_version(args.version): - logger.error(f"Invalid version format: {args.version}. Expected format: vxx.xx.xx (e.g., v0.27.1)") + logger.error(f"Invalid version format: {args.version}. Expected format: vxx.xx.xx (e.g., v0.27.2)") sys.exit(1) # Validate at least one action is specified diff --git a/tools/scripts/mysql_migration.py b/tools/scripts/mysql_migration.py index 0565bc5b64a..05217a91605 100644 --- a/tools/scripts/mysql_migration.py +++ b/tools/scripts/mysql_migration.py @@ -2149,10 +2149,10 @@ def main(): python mysql_migration.py --list-stages # Check whether migration is needed for a target version - python mysql_migration.py --check-database-version --database-version v0.27.1 --config /path/to/config.yaml + python mysql_migration.py --check-database-version --database-version v0.27.2 --config /path/to/config.yaml # Mark database version separately - python mysql_migration.py --mark-database-version --database-version v0.27.1 --config /path/to/config.yaml + python mysql_migration.py --mark-database-version --database-version v0.27.2 --config /path/to/config.yaml # Dry run (default - check only, no write) with config file python mysql_migration.py --stages tenant_model_provider --config /path/to/config.yaml @@ -2166,11 +2166,11 @@ def main(): # Execute full migration (create tables and migrate data) python mysql_migration.py --stages tenant_model_provider --config /path/to/config.yaml --execute - # Execute migration only when database version is lower than v0.27.1 - python mysql_migration.py --stages tenant_model_provider --config /path/to/config.yaml --execute --database-version v0.27.1 + # Execute migration only when database version is lower than v0.27.2 + python mysql_migration.py --stages tenant_model_provider --config /path/to/config.yaml --execute --database-version v0.27.2 # Execute migration and mark the database version when all stages succeed - python mysql_migration.py --stages tenant_model_provider,tenant_model_instance,tenant_model,model_id_config --config /path/to/config.yaml --execute --database-version v0.27.1 --mark-database-version-on-success + python mysql_migration.py --stages tenant_model_provider,tenant_model_instance,tenant_model,model_id_config --config /path/to/config.yaml --execute --database-version v0.27.2 --mark-database-version-on-success # Normalize legacy model IDs in stored configs python mysql_migration.py --stages model_id_config --config /path/to/config.yaml --execute diff --git a/tools/scripts/run_migrations.sh b/tools/scripts/run_migrations.sh index f35298288ec..f2a91d9adef 100755 --- a/tools/scripts/run_migrations.sh +++ b/tools/scripts/run_migrations.sh @@ -55,7 +55,7 @@ echo "Running model provider table migrations..." --stages tenant_model_seeding,model_type_merge,tenant_model_id_migration \ --config "$CONFIG" \ --execute \ - --database-version "v0.27.1" \ + --database-version "v0.27.2" \ --mark-database-version-on-success echo "Model provider table migrations completed." diff --git a/uv.lock b/uv.lock index 54e7ee97772..9221a8c7ecc 100644 --- a/uv.lock +++ b/uv.lock @@ -8169,7 +8169,7 @@ wheels = [ [[package]] name = "ragflow" -version = "0.27.1" +version = "0.27.2" source = { virtual = "." } dependencies = [ { name = "agentrun-sdk" }, From a024bea0cd93f39e6652a42bf84dd20c55bc560b Mon Sep 17 00:00:00 2001 From: Wang Qi Date: Thu, 10 Sep 2026 19:03:20 +0800 Subject: [PATCH 080/568] Docs: v0.27.2 release notes (#19504) --- docs/release_notes.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/docs/release_notes.md b/docs/release_notes.md index e782c82f440..36423e4c93b 100644 --- a/docs/release_notes.md +++ b/docs/release_notes.md @@ -9,6 +9,41 @@ sidebar_custom_props: { Key features, improvements and bug fixes in the latest releases. +## v0.27.2 + +Released on Sep 10, 2026. + +### New features +- Agentic RAG: Refactored the Agentic RAG retrieval framework, significantly improving reasoning speed and benchmark performance. ([#19046](https://github.com/infiniflow/ragflow/pull/19046), [#19112](https://github.com/infiniflow/ragflow/pull/19112), [#19172](https://github.com/infiniflow/ragflow/pull/19172), [#19209](https://github.com/infiniflow/ragflow/pull/19209), [#19424](https://github.com/infiniflow/ragflow/pull/19424), [#19459](https://github.com/infiniflow/ragflow/pull/19459)) +- Knowledge compilation runtime settings ([#19254](https://github.com/infiniflow/ragflow/pull/19254)) +- Enforce a rate limit on the knowledge compilation pipeline ([#19156](https://github.com/infiniflow/ragflow/pull/19156)) +- Knowledge graph shows total and current node counts ([#19142](https://github.com/infiniflow/ragflow/pull/19142),[#19095](https://github.com/infiniflow/ragflow/pull/19095), [#19114](https://github.com/infiniflow/ragflow/pull/19114)) +- Graph search highlights the node when pressing Enter on an entity name ([#19320](https://github.com/infiniflow/ragflow/pull/19320)) +- New Sitemap data source for sitemap.xml-based web ingestion ([#19344](https://github.com/infiniflow/ragflow/pull/19344)) +- WebDAV connector supports custom CA certificates ([#16901](https://github.com/infiniflow/ragflow/pull/16901)) +- MonkeyOCRv2 parsing support ([#18887](https://github.com/infiniflow/ragflow/pull/18887)) +- Self-hosted PaddleOCR-VL deployment support ([#19011](https://github.com/infiniflow/ragflow/pull/19011)) +- New Sofya search tool for agent ([#19323](https://github.com/infiniflow/ragflow/pull/19323)) +- EPUB document preview ([#19242](https://github.com/infiniflow/ragflow/pull/19242)) +- Excel citation sources located in document preview ([#18853](https://github.com/infiniflow/ragflow/pull/18853)) + +### Model Support +- New Hubris model provider ([#19341](https://github.com/infiniflow/ragflow/pull/19341)) +- New llmman model provider ([#19030](https://github.com/infiniflow/ragflow/pull/19030)) + +### Improvements +- New RERANK_TOKEN_LIMIT_MODE configuration ([#19404](https://github.com/infiniflow/ragflow/pull/19404)) +- Highlight in retrieval testing and search ([#18981](https://github.com/infiniflow/ragflow/pull/18981)) +- Similarity threshold displayed as a percentage ([#18974](https://github.com/infiniflow/ragflow/pull/18974)) + +### UI/UX +- Completed Turkish locale ([#19009](https://github.com/infiniflow/ragflow/pull/19009)) +- Search match highlighting in Team settings tables ([#15985](https://github.com/infiniflow/ragflow/pull/15985)) + +### Bug fixes +- Fixed images uploaded in chat being ignored by vision models ([#18884](https://github.com/infiniflow/ragflow/pull/18884)) +- Fixed non-UTF-8 encodings in CSV/TXT preview and document decoding ([#19222](https://github.com/infiniflow/ragflow/pull/19222), [#19253](https://github.com/infiniflow/ragflow/pull/19253)) + ## v0.27.1 Released on Aug 28, 2026. From ef800ba5c23d21213a55a711069206b7e9dea56c Mon Sep 17 00:00:00 2001 From: qinling0210 <88864212+qinling0210@users.noreply.github.com> Date: Thu, 10 Sep 2026 20:02:48 +0800 Subject: [PATCH 081/568] Port agentic RAG to GO (#19500) ### Summary Port agentic RAG to GO --- cmd/ragflow_server.go | 617 +++ cmd/ragflow_server_test.go | 382 ++ go.mod | 3 +- go.sum | 2 + internal/agent/audio/tts_dispatch.go | 2 +- internal/agent/chat/chat.go | 99 +- internal/agent/chat/message_fit.go | 178 + internal/agent/chat/message_fit_test.go | 211 + internal/agent/component/invoke.go | 2 +- internal/agent/component/io/docx_writer.go | 2 +- .../agent/component/io/html_writer_test.go | 2 +- internal/agent/component/list_operations.go | 2 +- .../agent/component/list_operations_test.go | 2 +- internal/agent/component/llm.go | 377 +- internal/agent/component/llm_test.go | 244 +- internal/agent/component/prompts/citation.go | 70 +- internal/agent/component/userfillup.go | 2 +- .../agent/component/variable_aggregator.go | 2 +- internal/agent/dsl/normalize.go | 2 +- internal/agent/dsl/normalize_test.go | 2 +- internal/agent/harness/agentic.go | 301 -- internal/agent/harness/agentic_rag.go | 120 - internal/agent/harness/agentic_test.go | 81 - internal/agent/harness/answer.go | 150 - internal/agent/harness/answer_test.go | 130 - internal/agent/harness/compilation.go | 210 - internal/agent/harness/compilation_test.go | 103 - internal/agent/harness/cross_check_test.go | 159 - internal/agent/harness/datasetnav.go | 225 - internal/agent/harness/datasetnav_test.go | 102 - internal/agent/harness/grounded_llm.go | 162 - internal/agent/harness/inspector.go | 265 -- internal/agent/harness/inspector_test.go | 108 - internal/agent/harness/kg_explore.go | 537 --- internal/agent/harness/kg_explore_test.go | 133 - internal/agent/harness/navigation.go | 281 -- internal/agent/harness/navigation_test.go | 64 - internal/agent/harness/orchestrator.go | 267 -- internal/agent/harness/orchestrator_test.go | 138 - internal/agent/harness/pipeline.go | 491 --- internal/agent/harness/planner.go | 164 - internal/agent/harness/production.go | 585 --- internal/agent/harness/production_test.go | 144 - .../agent/harness/production_wiki_test.go | 276 -- internal/agent/harness/research_agent.go | 461 -- internal/agent/harness/review_fixes_test.go | 106 - internal/agent/harness/route.go | 152 - internal/agent/harness/route_test.go | 210 - .../agent/harness/split_sentences_test.go | 72 - internal/agent/harness/sufficiency.go | 639 --- internal/agent/harness/sufficiency_ladder.go | 164 - .../agent/harness/sufficiency_ladder_test.go | 123 - internal/agent/harness/sufficiency_llm.go | 499 --- internal/agent/harness/types.go | 187 - .../agent/retrievalbridge/runtime_adapter.go | 112 + internal/agent/runtime/helpers.go | 2 +- internal/agent/runtime/registry_test.go | 2 +- internal/agent/runtime/retrieval.go | 13 +- internal/agent/tool/agentic_search.go | 13 +- internal/agent/tool/dataset_navigation.go | 5 +- .../agent/tool/dataset_navigation_test.go | 5 +- internal/agent/tool/retrieval_nlp.go | 21 +- internal/agent/tool/retrieval_nlp_test.go | 34 +- internal/agent/tool/retrieval_service.go | 18 +- internal/agent/workflowx/parallel_test.go | 2 +- internal/common/logger.go | 20 + internal/dao/tenant_model.go | 14 + internal/entity/models/aliyun.go | 268 +- internal/entity/models/aliyun_test.go | 167 + internal/entity/models/bedrock.go | 13 +- internal/entity/models/bedrock_test.go | 31 + internal/entity/models/chat_tools.go | 80 +- internal/entity/models/chat_tools_test.go | 172 + internal/entity/models/cohere.go | 7 +- internal/entity/models/cohere_test.go | 30 +- internal/entity/models/common_test.go | 22 + internal/entity/models/jina.go | 10 + internal/entity/models/jina_test.go | 34 + internal/entity/models/llm.go | 24 +- internal/entity/models/non_chat_usage_test.go | 18 +- internal/entity/models/nvidia.go | 8 +- internal/entity/models/nvidia_test.go | 29 + internal/entity/models/types.go | 27 + internal/entity/models/voyage.go | 12 +- internal/entity/models/voyage_test.go | 26 + internal/rag/advanced_rag/agentic_rag.go | 1972 +++++++++ .../rag/advanced_rag/agentic_rag_graph.go | 3697 +++++++++++++++++ .../advanced_rag/agentic_rag_graph_test.go | 2523 +++++++++++ internal/rag/advanced_rag/agentic_rag_test.go | 503 +++ internal/rag/advanced_rag/agentic_rag_util.go | 23 + .../advanced_rag/harness/action_session.go | 3570 ++++++++++++++++ .../harness/action_session_test.go | 1091 +++++ .../rag/advanced_rag/harness/arithmetic.go | 1600 +++++++ .../advanced_rag/harness/arithmetic_test.go | 565 +++ .../rag/advanced_rag/harness/chunk_utils.go | 180 + .../advanced_rag/harness/chunk_utils_test.go | 57 + internal/rag/advanced_rag/harness/config.go | 154 + .../rag/advanced_rag/harness/doc_fetch.go | 183 + .../advanced_rag/harness/grep_sed_narrow.go | 573 +++ internal/rag/advanced_rag/harness/kbinfos.go | 235 ++ .../rag/advanced_rag/harness/kbinfos_test.go | 51 + internal/rag/advanced_rag/harness/keywords.go | 294 ++ .../rag/advanced_rag/harness/keywords_test.go | 191 + internal/rag/advanced_rag/harness/memory.go | 498 +++ .../rag/advanced_rag/harness/memory_test.go | 114 + .../harness/orchestrator/direct.go | 50 + .../harness/orchestrator/query_rewriter.go | 126 + .../orchestrator/query_rewriter_test.go | 107 + .../orchestrator/sufficient_context.go | 599 +++ .../orchestrator/sufficient_context_test.go | 276 ++ .../rag/advanced_rag/harness/report_prompt.go | 54 + internal/rag/advanced_rag/harness/stats.go | 671 +++ .../rag/advanced_rag/harness/stats_test.go | 161 + .../rag/advanced_rag/harness/structure_qa.go | 212 + .../advanced_rag/harness/structure_qa_test.go | 175 + .../harness/tool_compiled_expansion.go | 558 +++ .../harness/tool_compiled_expansion_test.go | 431 ++ .../rag/advanced_rag/harness/tool_executor.go | 988 +++++ .../harness/tool_executor_test.go | 762 ++++ .../advanced_rag/harness/tool_exploration.go | 962 +++++ .../advanced_rag/harness/tool_navigation.go | 1575 +++++++ .../harness/tool_navigation_test.go | 944 +++++ .../rag/advanced_rag/harness/tool_search.go | 1482 +++++++ .../advanced_rag/harness/tool_search_test.go | 1122 +++++ .../harness/tool_text_processing.go | 667 +++ .../harness/tool_text_processing_test.go | 279 ++ internal/rag/advanced_rag/think_log.go | 150 + internal/rag/advanced_rag/think_log_test.go | 109 + .../rag/prompts/action_initialize_state.md | 23 + internal/rag/prompts/action_run.md | 38 + internal/rag/prompts/citation_prompt.md | 122 + internal/rag/prompts/generator.go | 226 + internal/rag/prompts/generator_test.go | 144 + internal/rag/prompts/sca_query_rewrite.md | 35 + internal/rag/prompts/sca_select.md | 106 + internal/rag/prompts/templates.go | 92 + internal/rag/prompts/templates_test.go | 163 + internal/service/chat_pipeline.go | 571 ++- internal/service/chat_pipeline_test.go | 103 + internal/service/chat_session.go | 13 + internal/service/citation.go | 5 + internal/service/citation_test.go | 20 + internal/service/dataset_artifact_nav_test.go | 5 +- internal/service/graph/retrieval.go | 4 +- internal/service/graph/search.go | 4 +- internal/service/memory.go | 4 +- internal/service/model_service.go | 82 + internal/service/nav/chunk_agg_router.go | 194 + internal/service/nav/chunk_agg_router_test.go | 127 + internal/service/nav/nav.go | 20 +- internal/service/nav/nav_service_router.go | 99 + .../service/nav/nav_service_router_test.go | 95 + internal/service/nav_embedder.go | 17 +- internal/service/nlp/datasetnav.go | 170 +- internal/service/nlp/datasetnav_test.go | 95 +- internal/service/nlp/retrieval.go | 7 +- internal/service/skill_search.go | 4 +- internal/service/web_search_provider_test.go | 17 + 158 files changed, 36103 insertions(+), 8287 deletions(-) create mode 100644 cmd/ragflow_server_test.go create mode 100644 internal/agent/chat/message_fit.go create mode 100644 internal/agent/chat/message_fit_test.go delete mode 100644 internal/agent/harness/agentic.go delete mode 100644 internal/agent/harness/agentic_rag.go delete mode 100644 internal/agent/harness/agentic_test.go delete mode 100644 internal/agent/harness/answer.go delete mode 100644 internal/agent/harness/answer_test.go delete mode 100644 internal/agent/harness/compilation.go delete mode 100644 internal/agent/harness/compilation_test.go delete mode 100644 internal/agent/harness/cross_check_test.go delete mode 100644 internal/agent/harness/datasetnav.go delete mode 100644 internal/agent/harness/datasetnav_test.go delete mode 100644 internal/agent/harness/grounded_llm.go delete mode 100644 internal/agent/harness/inspector.go delete mode 100644 internal/agent/harness/inspector_test.go delete mode 100644 internal/agent/harness/kg_explore.go delete mode 100644 internal/agent/harness/kg_explore_test.go delete mode 100644 internal/agent/harness/navigation.go delete mode 100644 internal/agent/harness/navigation_test.go delete mode 100644 internal/agent/harness/orchestrator.go delete mode 100644 internal/agent/harness/orchestrator_test.go delete mode 100644 internal/agent/harness/pipeline.go delete mode 100644 internal/agent/harness/planner.go delete mode 100644 internal/agent/harness/production.go delete mode 100644 internal/agent/harness/production_test.go delete mode 100644 internal/agent/harness/production_wiki_test.go delete mode 100644 internal/agent/harness/research_agent.go delete mode 100644 internal/agent/harness/review_fixes_test.go delete mode 100644 internal/agent/harness/route.go delete mode 100644 internal/agent/harness/route_test.go delete mode 100644 internal/agent/harness/split_sentences_test.go delete mode 100644 internal/agent/harness/sufficiency.go delete mode 100644 internal/agent/harness/sufficiency_ladder.go delete mode 100644 internal/agent/harness/sufficiency_ladder_test.go delete mode 100644 internal/agent/harness/sufficiency_llm.go delete mode 100644 internal/agent/harness/types.go create mode 100644 internal/agent/retrievalbridge/runtime_adapter.go create mode 100644 internal/entity/models/chat_tools_test.go create mode 100644 internal/rag/advanced_rag/agentic_rag.go create mode 100644 internal/rag/advanced_rag/agentic_rag_graph.go create mode 100644 internal/rag/advanced_rag/agentic_rag_graph_test.go create mode 100644 internal/rag/advanced_rag/agentic_rag_test.go create mode 100644 internal/rag/advanced_rag/agentic_rag_util.go create mode 100644 internal/rag/advanced_rag/harness/action_session.go create mode 100644 internal/rag/advanced_rag/harness/action_session_test.go create mode 100644 internal/rag/advanced_rag/harness/arithmetic.go create mode 100644 internal/rag/advanced_rag/harness/arithmetic_test.go create mode 100644 internal/rag/advanced_rag/harness/chunk_utils.go create mode 100644 internal/rag/advanced_rag/harness/chunk_utils_test.go create mode 100644 internal/rag/advanced_rag/harness/config.go create mode 100644 internal/rag/advanced_rag/harness/doc_fetch.go create mode 100644 internal/rag/advanced_rag/harness/grep_sed_narrow.go create mode 100644 internal/rag/advanced_rag/harness/kbinfos.go create mode 100644 internal/rag/advanced_rag/harness/kbinfos_test.go create mode 100644 internal/rag/advanced_rag/harness/keywords.go create mode 100644 internal/rag/advanced_rag/harness/keywords_test.go create mode 100644 internal/rag/advanced_rag/harness/memory.go create mode 100644 internal/rag/advanced_rag/harness/memory_test.go create mode 100644 internal/rag/advanced_rag/harness/orchestrator/direct.go create mode 100644 internal/rag/advanced_rag/harness/orchestrator/query_rewriter.go create mode 100644 internal/rag/advanced_rag/harness/orchestrator/query_rewriter_test.go create mode 100644 internal/rag/advanced_rag/harness/orchestrator/sufficient_context.go create mode 100644 internal/rag/advanced_rag/harness/orchestrator/sufficient_context_test.go create mode 100644 internal/rag/advanced_rag/harness/report_prompt.go create mode 100644 internal/rag/advanced_rag/harness/stats.go create mode 100644 internal/rag/advanced_rag/harness/stats_test.go create mode 100644 internal/rag/advanced_rag/harness/structure_qa.go create mode 100644 internal/rag/advanced_rag/harness/structure_qa_test.go create mode 100644 internal/rag/advanced_rag/harness/tool_compiled_expansion.go create mode 100644 internal/rag/advanced_rag/harness/tool_compiled_expansion_test.go create mode 100644 internal/rag/advanced_rag/harness/tool_executor.go create mode 100644 internal/rag/advanced_rag/harness/tool_executor_test.go create mode 100644 internal/rag/advanced_rag/harness/tool_exploration.go create mode 100644 internal/rag/advanced_rag/harness/tool_navigation.go create mode 100644 internal/rag/advanced_rag/harness/tool_navigation_test.go create mode 100644 internal/rag/advanced_rag/harness/tool_search.go create mode 100644 internal/rag/advanced_rag/harness/tool_search_test.go create mode 100644 internal/rag/advanced_rag/harness/tool_text_processing.go create mode 100644 internal/rag/advanced_rag/harness/tool_text_processing_test.go create mode 100644 internal/rag/advanced_rag/think_log.go create mode 100644 internal/rag/advanced_rag/think_log_test.go create mode 100644 internal/rag/prompts/action_initialize_state.md create mode 100644 internal/rag/prompts/action_run.md create mode 100644 internal/rag/prompts/citation_prompt.md create mode 100644 internal/rag/prompts/generator.go create mode 100644 internal/rag/prompts/generator_test.go create mode 100644 internal/rag/prompts/sca_query_rewrite.md create mode 100644 internal/rag/prompts/sca_select.md create mode 100644 internal/rag/prompts/templates.go create mode 100644 internal/rag/prompts/templates_test.go create mode 100644 internal/service/nav/chunk_agg_router.go create mode 100644 internal/service/nav/chunk_agg_router_test.go create mode 100644 internal/service/nav/nav_service_router.go create mode 100644 internal/service/nav/nav_service_router_test.go diff --git a/cmd/ragflow_server.go b/cmd/ragflow_server.go index 641ca7cbdfd..314a07da3d3 100644 --- a/cmd/ragflow_server.go +++ b/cmd/ragflow_server.go @@ -28,12 +28,16 @@ import ( "ragflow/internal/agent/audio" "ragflow/internal/agent/canvas" "ragflow/internal/agent/retrievalbridge" + "ragflow/internal/agent/runtime" agenttool "ragflow/internal/agent/tool" "ragflow/internal/channels" + modelModule "ragflow/internal/entity/models" "ragflow/internal/handler" "ragflow/internal/ingestion/knowledge_compile" ingestion "ragflow/internal/ingestion/service" "ragflow/internal/mcp" + "ragflow/internal/rag/advanced_rag" + "ragflow/internal/rag/advanced_rag/harness" "ragflow/internal/router" "ragflow/internal/server/local" "ragflow/internal/service" @@ -61,6 +65,8 @@ import ( "ragflow/internal/deepdoc/parser/pdf/inference/native_analyzer" "ragflow/internal/engine" "ragflow/internal/engine/redis" + et "ragflow/internal/engine/types" + "ragflow/internal/entity" _ "ragflow/internal/ingestion/wire" "ragflow/internal/server" "ragflow/internal/utility" @@ -80,6 +86,94 @@ type serverArgs struct { name *string // server name } +// engineDocEngine is the small slice of the engine surface the doc-chunk pager +// needs, kept as a local interface so it is trivially unit-testable without a +// live engine (the production value is engine.Get()). +type engineDocEngine interface { + Search(ctx context.Context, req *et.SearchRequest) (*et.SearchResult, error) +} + +// docChunkPager is the production harness.DocChunkLister. It pages one +// document's chunks in reading order straight off the chunk index, mirroring +// Python settings.retriever.chunk_list with sort_by_position=True +// (rag/nlp/search.py:824). This is what the document-level tools +// (summarize_document / fetch_full_document) consume. +// +// The index name is derived from the tenant id (ragflow_), exactly as +// retrieval does, so it needs no user-scope resolution: DocChunksRequest +// already carries the tenant and the bound datasets. +type docChunkPager struct { + docEngine engineDocEngine +} + +// DocChunks implements harness.DocChunkLister. +func (p *docChunkPager) DocChunks(ctx context.Context, req harness.DocChunksRequest) ([]map[string]any, error) { + if p == nil || p.docEngine == nil { + return nil, nil + } + if req.DocID == "" { + return nil, nil + } + orderBy := (&et.OrderByExpr{}). + Asc("chunk_order_int"). + Asc("page_num_int"). + Asc("top_int"). + Desc("create_timestamp_flt") + + resp, err := p.docEngine.Search(ctx, &et.SearchRequest{ + IndexNames: []string{tenantChunkIndexName(req.TenantID)}, + KbIDs: req.DatasetIDs, + Offset: req.Offset, + Limit: req.Limit, + OrderBy: orderBy, + SelectFields: []string{ + "id", "doc_id", "docnm", "content_with_weight", "content", "available_int", + }, + Filter: map[string]interface{}{ + "doc_id": req.DocID, + "available_int": 1, + "must_not": map[string]interface{}{"exists": "compile_kwd"}, + }, + }) + if err != nil { + return nil, err + } + if resp == nil { + return nil, nil + } + rows := make([]map[string]any, 0, len(resp.Chunks)) + for _, ck := range resp.Chunks { + row := make(map[string]any, 8) + // The harness chunk rows need the canonical keys its citation pipeline + // reads: chunk_id (dedup), docnm_kwd (doc title), doc_id and the text + // under content/content_with_weight (chunkText prefers content first). + if id, ok := ck["id"].(string); ok && id != "" { + row["chunk_id"] = id + } + if d, ok := ck["doc_id"]; ok { + row["doc_id"] = d + } + if d, ok := ck["docnm"]; ok { + row["docnm_kwd"] = d + } + if c, ok := ck["content"]; ok { + row["content"] = c + } + if c, ok := ck["content_with_weight"]; ok { + row["content_with_weight"] = c + } + // Keep whatever else the engine returned (e.g. position_int, img) so the + // merged Kbinfos rows stay rich, as retrieval does. + for k, v := range ck { + if _, seen := row[k]; !seen { + row[k] = v + } + } + rows = append(rows, row) + } + return rows, nil +} + func parseArgs() (*serverArgs, error) { args := &serverArgs{} @@ -776,6 +870,153 @@ func startServer(ctx context.Context) { agenttool.SetMemoryRetrievalService(retrievalbridge.NewMemoryAdapter(memoryService)) common.Info("agent: retrieval service adapter installed") + // Wire the agentic-RAG harness as the Go chat pipeline's evidence engine + // (internal/service/chat_pipeline.retrieveViaHarness): it searches through the + // runtime retrieval singleton below and runs each request on a model resolved + // from the caller's ModelID. Activating the agentic loop here enables the full + // planner/SCA path for reasoning chats. + runtime.SetRetrievalService(retrievalbridge.NewRuntimeAdapter()) + advanced_rag.SetAgenticLoop(advanced_rag.NewAgenticLoop()) + service.SetHarnessRetriever(func(ctx context.Context, req service.HarnessRequest) (service.HarnessResult, error) { + // Resolve the tenant's actual chat model, mirroring Python where RAGTools + // receives a fully-resolved LLMBundle: chat.LLMID may be a UUID/tenant_model + // id that the default invoker cannot split into a provider, so resolving here + // avoids falling through to a dummy driver. If resolution fails we leave model + // nil so the harness degrades to a direct search (no dummy fallback). + var model harness.SessionModel + // outerModel mirrors Python RAGTools.chat_mdl: the fully-resolved chat + // model that drives the outer rag_agent react loop (tools=[rag, + // summarize_document], terminal_tools={"rag"}). Wired into RAGTools.Outer + // so Rag() can run that loop instead of the direct graph. + var outerModel *modelModule.ChatModel + // resolvedModelName is the resolved chat model's own name (e.g. + // "gpt-4o"), i.e. Python chat_mdl.llm_name. It is the gen_json reply-cache + // key's model component; empty disables that cache. + resolvedModelName := "" + if req.ModelID != "" { + if driver, modelName, apiCfg, contentLen, mErr := modelProviderService.ResolveModelConfig(ctx, req.TenantID, entity.ModelTypeChat, req.ModelID); mErr == nil { + if inv := component.NewResolvedInvoker(driver, modelName, apiCfg); inv != nil { + // MaxLength mirrors Python LLMBundle.max_length (the model's + // context window in tokens); message-fitting nodes (calculate, + // structure_qa) use it as their chat.FitMessages budget. + model = &harness.InvokerSessionModel{Invoker: inv, DB: dao.DB, MaxLength: contentLen} + resolvedModelName = modelName + // Reuse the same resolved driver/name/api as the invoker so + // the outer loop and the inner tool calls share one model. + outerModel = modelModule.NewChatModel(driver, &modelName, apiCfg) + } + } else { + common.Warn("harness: failed to resolve chat model for reasoning; harness will degrade to direct search", zap.Error(mErr)) + } + } + + // OuterSupportsTools mirrors Python `if not chat_mdl.is_tools`: gate the + // outer react loop on the model's tool-calling capability, not mere + // existence of an outer model. A model that can't emit tool_calls must fall + // back to the direct graph (Python async_chat) rather than bind tools and + // return a retrieval-less direct answer. + outerSupportsTools := false + if req.ModelID != "" { + if ts, tsErr := modelProviderService.ResolveModelToolSupport(ctx, req.TenantID, entity.ModelTypeChat, req.ModelID); tsErr == nil { + outerSupportsTools = ts + } + } + + // Load the KB objects (mirroring Python RAGTools' self.kbs via + // KnowledgebaseService.get_by_ids(kb_ids)) so the agentic tool can + // derive rank features from parser_config.tag_kb_ids. Best-effort: a + // load failure leaves KBs empty and the adapter resolves them itself. + var kbs []*entity.Knowledgebase + if len(req.DatasetIDs) > 0 { + if loaded, lErr := dao.NewKnowledgebaseDAO().GetByIDs(ctx, dao.DB, req.DatasetIDs); lErr == nil { + kbs = loaded + } + } + // validate_dataset_embedding_models runs FIRST upstream + // (dialog_service.py:358-360) and mixing is a hard failure there, not a + // fallback to keyword-only retrieval. + if err := validateDatasetEmbeddingModels(ctx, kbs); err != nil { + return service.HarnessResult{}, err + } + // HasEmbedder mirrors Python `embd_mdl = ... if kbs and kbs[0].embd_id else + // None` (dialog_service.py:362): the gate is the FIRST dataset's embd_id. It + // is what hybrid_search applies to its vector leg (search.py:143), so + // getting it wrong silently degrades search_chunks to keyword-only. + hasEmbedder := hasEmbedderFor(kbs) + deps := advanced_rag.RAGTools{ + Model: model, + ModelName: resolvedModelName, + Outer: outerModel, + // OuterSupportsTools gates the outer react loop on tool capability + // (Python is_tools); false → fall back to direct RunAgenticRAG. + OuterSupportsTools: outerSupportsTools, + // DocScope mirrors Python RAGTools(doc_scope=...): the narrowed doc_ids + // (chat-level doc_ids + meta_data_filter) restrict every agentic + // retrieval to the user-selected documents instead of the whole kb. + DocScope: req.DocIDs, + DocIDVerifier: advanced_rag.NewDocIDLookup(), + // DocChunks pages one document's chunks in reading order off the + // chunk index (Python retriever.chunk_list), backing the + // document-level tools (summarize_document / fetch_full_document). + DocChunks: &docChunkPager{docEngine: docEngine}, + // Expand runs search_chunks' compiled-structure expansion + // (Python hybrid_search use_compiled=True → _expand_with_compiled). + // Backed by the same document engine the chunk reads use, with the + // dense seed leg wired to the bound dataset's own embedding model. + // The scope config lets each dataset be scanned under its own tenant + // and a doc scope be grouped by real owner, like graph_explore. + Expand: harness.NewCompiledExpander( + newDatasetCompiledStore(docEngine, modelProviderService, kbs), + harness.CompiledScopeConfig{ + DatasetIDs: req.DatasetIDs, + TenantID: req.TenantID, + KBs: kbs, + DocTenantResolver: advanced_rag.NewDocTenantResolver(), + }, + ), + // WebSearch backs the web_search tool (Python RAGTools.web_search). + // The pipeline supplies a callback only when the chat enables + // internet web search; a nil one also keeps the tool off the surface. + WebSearch: harnessWebSearcher(req.WebSearch), + KBs: kbs, + HasEmbedder: hasEmbedder, + // Tagger is the Go equivalent of Python's label_question + // (agentic_rag.py:668): classifies the query into question-type + // tags the retriever boosts on. metadataService implements it + // (service.MetadataService.LabelQuestion). + Tagger: metadataService, + } + if req.AnswerSink != nil { + deps.AnswerSink = &advanced_rag.AnswerSink{ + OnDelta: req.AnswerSink, + } + // Engine-stage progress (planner/orchestrator/research/SCA) is + // research-time think content — mirroring Python think_log, which + // forwarded the tagged lines into the block. Deliver each + // line as an isThink=true delta so the live reasoning block shows + // the research as it happens. + deps.Progress = func(line string) { + req.AnswerSink(line, true) + } + } + r := advanced_rag.Rag(ctx, deps, harness.RunRequest{ + Question: req.Question, + ThinkingMode: req.ThinkingMode, + DatasetIDs: req.DatasetIDs, + TenantID: req.TenantID, + SessionID: req.SessionID, + Images: req.Images, + TextAttachments: req.TextAttachments, + }) + res := service.HarnessResult{Chunks: r.Chunks, DocAggs: r.DocAggs, Answer: r.Answer} + if r.Kbinfos != nil { + res.Memory = r.Kbinfos.Memory + res.PreSummary = r.Kbinfos.PreSummary + } + return res, nil + }) + common.Info("agent: harness chat retriever wired (runtime retrieval + agentic loop)") + // Initialize handler layer authHandler := handler.NewAuthHandler() userHandler := handler.NewUserHandler(userService) @@ -1155,3 +1396,379 @@ func resolveDeepDocDropScore() float64 { func dirHasModels(dir string) bool { return common.HasModelFiles(dir) } + +// hasEmbedderFor mirrors Python `embd_mdl = LLMBundle(...) if kbs and +// kbs[0].embd_id else None` (dialog_service.py:362). The gate is the FIRST bound +// dataset's embd_id, not "any dataset has one": a dialog whose first dataset +// carries no embedding model yields embd_mdl=None upstream even if later ones do. +// +// Callers must run validateDatasetEmbeddingModels first — with validation +// passing, all datasets share one model and this equals "all have one". +func hasEmbedderFor(kbs []*entity.Knowledgebase) bool { + return len(kbs) > 0 && kbs[0] != nil && kbs[0].EmbdID != "" +} + +// validateDatasetEmbeddingModels mirrors Python validate_dataset_embedding_models +// (knowledgebase_service.py:62-94): every bound dataset must use the same embedding +// model, or none at all. Upstream this runs before embd_mdl is resolved +// (dialog_service.py:358-360) and a violation RAISES — it is not a "no embedding +// model" fallback: treating mixing as HasEmbedder=false would silently serve +// keyword-only results where Python errors. +func validateDatasetEmbeddingModels(ctx context.Context, kbs []*entity.Knowledgebase) error { + var withEmbd int + for _, kb := range kbs { + if kb != nil && kb.EmbdID != "" { + withEmbd++ + } + } + hasEmbd := withEmbd > 0 + if hasEmbd && withEmbd != len(kbs) { + return errors.New("cannot search across datasets where some have embedding models and others do not") + } + if !hasEmbd { + return nil + } + // Mirror Python's grouping key exactly: + // + // ref = tenant_embd_id or (embd_id when it is a raw tenant_model id) + // composite = resolved_names.get(ref) # "model@instance@provider" + // key = _base_model_name(composite) # == tenant_model.model_name + // + // The @instance@provider suffix is stripped by _base_model_name + // (knowledgebase_service.py:33), so only the MODEL NAME is compared — the + // instance and provider tables are not consulted at all. + refs := make([]string, 0, len(kbs)) + for _, kb := range kbs { + if kb == nil || kb.EmbdID == "" { + continue + } + ref := "" + if kb.TenantEmbdID != nil { + ref = strings.TrimSpace(*kb.TenantEmbdID) + } + if ref == "" && !strings.Contains(kb.EmbdID, "@") { + ref = strings.TrimSpace(kb.EmbdID) + } + if ref != "" { + refs = append(refs, ref) + } + } + + // Python resolves the refs with one batched lookup + // (tenant_model_service.py:562 get_by_ids) and silently skips ids that no + // longer resolve — a dangling id must not fail the request. + resolved := make(map[string]string, len(refs)) + // A nil/absent DB or any query error must not fail the request: Python skips + // unresolvable ids (tenant_model_service.py:557) and falls back to the raw + // id, so validation degrades to a stricter but safe comparison. + if len(refs) > 0 && dao.DB != nil { + if models, err := dao.NewTenantModelDAO().GetByIDs(ctx, dao.DB, refs); err == nil { + for _, m := range models { + if m != nil { + resolved[m.ID] = m.ModelName + } + } + } + } + + keys := make(map[string]struct{}, len(kbs)) + for _, kb := range kbs { + if kb == nil || kb.EmbdID == "" { + continue + } + embdID := strings.TrimSpace(kb.EmbdID) + ref := "" + if kb.TenantEmbdID != nil { + ref = strings.TrimSpace(*kb.TenantEmbdID) + } + if ref == "" && !strings.Contains(embdID, "@") { + ref = embdID + } + key := "" + if name, ok := resolved[ref]; ok && name != "" { + key = name + } else if embdID != "" && embdID != ref { + key = baseModelName(embdID) + } else { + key = ref + } + if key != "" { + keys[key] = struct{}{} + } + } + if len(keys) > 1 { + return fmt.Errorf("datasets use different embedding models") + } + return nil +} + +// baseModelName mirrors Python _base_model_name +// (knowledgebase_service.py:33): strip the @instance@provider suffix, keeping the +// model name. Python uses rsplit("@", 2)[0], which for the purposes of taking +// the leading segment is the same as splitting once on "@". +func baseModelName(embdID string) string { + name, _, _ := strings.Cut(embdID, "@") + return name +} + +// --------------------------------------------------------------------------- +// Harness seams (compiled expansion + open-web search) +// --------------------------------------------------------------------------- + +// engineCompiledStore implements harness.CompiledStore over the document +// engine, backing search_chunks' compiled-structure expansion (Python +// tools/compiled_expansion.py). The harness owns the expansion strategy; this +// adapter only maps its (scope, filters, free text) request onto one engine +// search, mirroring Python's settings.docStoreConn.search calls. +type engineCompiledStore struct { + engine engineDocEngine + // embed encodes the seed query for the dense leg. It must be the QUERY + // encoding of the dataset's own embedding model (Python + // _search_compiled_rows → _dense_expr → settings.retriever.get_vector → + // emb_mdl.encode_queries). Nil leaves the keyword leg only. + embed compiledQueryEncoder + // embedTenantID is the tenant owning the embedder's model (Python + // embd_owner_tenant_id = kbs[0].tenant_id). It is distinct from the searched + // scope's tenant, because Python builds ONE embedder from the leading bound + // dataset and reuses it for every scope. + embedTenantID string +} + +var _ harness.CompiledStore = (*engineCompiledStore)(nil) + +// compiledQueryEncoder is the query-side embedding seam used for the compiled +// dense seed leg. *service.NavEmbedder implements it via EncodeQueries. +type compiledQueryEncoder interface { + EncodeQueries(ctx context.Context, tenantID string, texts []string) ([][]float32, error) +} + +// Mirror Python compiled_expansion._VECTOR_NUM_CANDIDATES / _VECTOR_SIMILARITY. +// The HNSW ef_search floor (num_candidates) must be >= topN or the ANN search is +// bounded by the candidate list instead of by relevance. +const ( + compiledVectorNumCandidates = 256 + compiledVectorSimilarity = 0.1 +) + +// newEngineCompiledStore returns nil when no engine is available so +// harness.NewCompiledExpander disables expansion instead of searching nowhere. +// A nil embed (or empty embedTenantID) keeps the keyword-only leg. +func newEngineCompiledStore(e engineDocEngine, embed compiledQueryEncoder, embedTenantID string) harness.CompiledStore { + if e == nil { + return nil + } + return &engineCompiledStore{engine: e, embed: embed, embedTenantID: embedTenantID} +} + +// newDatasetCompiledStore builds the per-request compiled-row store, wiring the +// dense seed leg to the FIRST bound dataset's own embedding model. Python builds +// embd_mdl from kbs[0] (dialog_service.py:362-365) and reuses it for the whole +// expansion; using the tenant-default model instead would compare the query +// against rows embedded by a different model — different vector spaces, so the +// dense hits would be noise. +func newDatasetCompiledStore(e engineDocEngine, modelSvc *service.ModelProviderService, kbs []*entity.Knowledgebase) harness.CompiledStore { + if e == nil { + return nil + } + if hasEmbedderFor(kbs) { + return newEngineCompiledStore(e, service.NewNavEmbedder(modelSvc, kbs[0].EmbdID), kbs[0].TenantID) + } + return newEngineCompiledStore(e, nil, "") +} + +const tenantChunkIndexPrefix = "ragflow_" + +func tenantChunkIndexName(tenantID string) string { + return tenantChunkIndexPrefix + tenantID +} + +// compiledSynthesisKinds are the standalone synthesis-page compile_kwd values. +// Python scopes those rows by source_doc_ids, while entity/relation rows are +// scoped by doc_id (compiled_expansion.py _search_compiled_rows / +// _search_synthesis_pages). +var compiledSynthesisKinds = map[string]bool{ + "wiki_page": true, + "artifact_page": true, + "essence": true, +} + +// compiledRowSelectFields is the projection the expander reads off a compiled +// row: content_with_weight (seed name parsing), the entity/relation endpoints, +// exact name lookups, and provenance back to source chunks. +var compiledRowSelectFields = []string{ + "id", "kb_id", "doc_id", "docnm_kwd", + "content_with_weight", "summary_with_weight", "source_chunk_ids", + "name_kwd", "from_entity_kwd", "to_entity_kwd", "available_int", +} + +// compiledChunkSelectFields is the projection for source chunks promoted into +// evidence by compiled expansion. +var compiledChunkSelectFields = []string{ + "id", "kb_id", "doc_id", "docnm_kwd", + "content_with_weight", "source_chunk_ids", "similarity", +} + +// SearchCompiled implements harness.CompiledStore. +func (s *engineCompiledStore) SearchCompiled(ctx context.Context, kbID, tenantID string, docIDs []string, filters map[string][]string, matchText string, topN int) ([]map[string]any, error) { + if s == nil || s.engine == nil || kbID == "" || strings.TrimSpace(tenantID) == "" { + return nil, nil + } + if topN <= 0 { + topN = 1 + } + filter := compiledEngineFilter(filters) + if len(docIDs) > 0 { + filter[compiledDocScopeKey(filters)] = docIDs + } + req := &et.SearchRequest{ + IndexNames: []string{tenantChunkIndexName(tenantID)}, + KbIDs: []string{kbID}, + Limit: topN, + SelectFields: compiledRowSelectFields, + Filter: filter, + } + // Python prefers a dense seed leg and only falls back to a keyword match + // when no embedder is available or the vector build fails + // (compiled_expansion.py _search_compiled_rows:180-194 / + // _search_synthesis_pages:423-438). Exactly ONE expr is appended. + if text := strings.TrimSpace(matchText); text != "" { + if dense := s.denseExpr(ctx, text, topN); dense != nil { + req.MatchExprs = []interface{}{dense} + } else { + req.MatchExprs = []interface{}{&et.MatchTextExpr{ + Fields: []string{"content_ltks", "content_sm_ltks"}, + MatchingText: text, + TopN: topN, + }} + } + } + res, err := s.engine.Search(ctx, req) + if err != nil || res == nil { + return nil, err + } + return res.Chunks, nil +} + +// denseExpr builds the compiled-row dense match for the seed text, mirroring +// Python _dense_expr (compiled_expansion.py:31-47): the query is embedded with +// the dataset model's QUERY encoding, and the match carries the HNSW +// num_candidates floor and similarity threshold. Returns nil when no embedder is +// wired, the encode fails, or it panics — every caller then uses the keyword leg, +// exactly like Python's `except Exception` around get_vector. +func (s *engineCompiledStore) denseExpr(ctx context.Context, text string, topN int) *et.MatchDenseExpr { + if s == nil || s.embed == nil || strings.TrimSpace(s.embedTenantID) == "" { + return nil + } + var ( + vecs [][]float32 + err error + ) + func() { + defer func() { + if r := recover(); r != nil { + common.Warn("compiled expansion: seed encode panicked; falling back to keyword match") + } + }() + vecs, err = s.embed.EncodeQueries(ctx, s.embedTenantID, []string{text}) + }() + if err != nil || len(vecs) == 0 || len(vecs[0]) == 0 { + return nil + } + vec := make([]float64, len(vecs[0])) + for i, v := range vecs[0] { + vec[i] = float64(v) + } + return &et.MatchDenseExpr{ + VectorColumnName: fmt.Sprintf("q_%d_vec", len(vec)), + EmbeddingData: vec, + EmbeddingDataType: "float", + DistanceType: "cosine", + TopN: topN, + ExtraOptions: map[string]interface{}{ + "similarity": compiledVectorSimilarity, + "num_candidates": max(topN, compiledVectorNumCandidates), + }, + } +} + +// LoadChunks implements harness.CompiledStore: fetch the referenced source +// chunks by id (Python compiled_expansion.py:_load_chunks_for_doc searches the +// tenant index with an {"id": chunk_ids} condition). +func (s *engineCompiledStore) LoadChunks(ctx context.Context, kbID, tenantID string, chunkIDs []string) ([]map[string]any, error) { + if s == nil || s.engine == nil || kbID == "" || strings.TrimSpace(tenantID) == "" || len(chunkIDs) == 0 { + return nil, nil + } + res, err := s.engine.Search(ctx, &et.SearchRequest{ + IndexNames: []string{tenantChunkIndexName(tenantID)}, + KbIDs: []string{kbID}, + Limit: len(chunkIDs), + SelectFields: compiledChunkSelectFields, + Filter: map[string]interface{}{"id": chunkIDs}, + }) + if err != nil || res == nil { + return nil, err + } + return res.Chunks, nil +} + +// Vectorize implements harness.CompiledStore. The ported expander assigns +// compiled chunks the similarity stored on the row and blends by that field, so +// expansion itself never needs a query embedding. +func (s *engineCompiledStore) Vectorize(context.Context, string) ([]float64, error) { + return nil, fmt.Errorf("compiled store: vectorize is not wired") +} + +// compiledDocScopeKey mirrors Python's doc-scope column choice: synthesis pages +// are scoped by source_doc_ids, entity/relation rows by doc_id. +func compiledDocScopeKey(filters map[string][]string) string { + for _, ck := range filters["compile_kwd"] { + if compiledSynthesisKinds[strings.ToLower(strings.TrimSpace(ck))] { + return "source_doc_ids" + } + } + return "doc_id" +} + +// compiledEngineFilter maps the harness' OR-list filters onto the engine filter +// shape. available_int is a numeric column, so its string values are coerced to +// ints (Python passes the literal 1). +func compiledEngineFilter(filters map[string][]string) map[string]interface{} { + out := make(map[string]interface{}, len(filters)) + for k, vals := range filters { + if k == "available_int" { + ints := make([]int, 0, len(vals)) + for _, v := range vals { + if n, err := strconv.Atoi(strings.TrimSpace(v)); err == nil { + ints = append(ints, n) + } + } + if len(ints) > 0 { + out[k] = ints + } + continue + } + out[k] = vals + } + return out +} + +// harnessWebSearcherFunc adapts the chat pipeline's web-search callback to the +// harness.WebSearcher seam consumed by the web_search tool. The callback is a +// plain func so internal/service does not have to depend on the harness package. +type harnessWebSearcherFunc func(ctx context.Context, queries []string) ([]string, error) + +// Search implements harness.WebSearcher. +func (f harnessWebSearcherFunc) Search(ctx context.Context, queries []string) ([]string, error) { + return f(ctx, queries) +} + +var _ harness.WebSearcher = harnessWebSearcherFunc(nil) + +// harnessWebSearcher wraps a non-nil callback, returning a nil WebSearcher when +// the pipeline did not supply one — which is what hides the web_search tool. +func harnessWebSearcher(fn func(context.Context, []string) ([]string, error)) harness.WebSearcher { + if fn == nil { + return nil + } + return harnessWebSearcherFunc(fn) +} diff --git a/cmd/ragflow_server_test.go b/cmd/ragflow_server_test.go new file mode 100644 index 00000000000..e7093fd2720 --- /dev/null +++ b/cmd/ragflow_server_test.go @@ -0,0 +1,382 @@ +package main + +import ( + "context" + "errors" + "testing" + + "ragflow/internal/engine/types" + "ragflow/internal/entity" + "ragflow/internal/service" +) + +func kb(embdID string, tenantEmbdID string) *entity.Knowledgebase { + kb := &entity.Knowledgebase{EmbdID: embdID} + if tenantEmbdID != "" { + kb.TenantEmbdID = &tenantEmbdID + } + return kb +} + +// TestHasEmbedderForMirrorsPython pins dialog_service.py:362 — +// `embd_mdl = LLMBundle(...) if kbs and kbs[0].embd_id else None`. The gate is +// the FIRST dataset's embd_id, so a dialog whose leading dataset has no model +// yields no embedding model even when a later one does. +func TestHasEmbedderForMirrorsPython(t *testing.T) { + cases := []struct { + name string + kbs []*entity.Knowledgebase + want bool + }{ + {"no datasets", nil, false}, + {"single dataset with model", []*entity.Knowledgebase{kb("bge-m3", "")}, true}, + {"single dataset without model", []*entity.Knowledgebase{kb("", "")}, false}, + // Python reads kbs[0].embd_id only; it does not scan for any dataset + // carrying a model. + {"first without, later with", []*entity.Knowledgebase{kb("", ""), kb("bge-m3", "")}, false}, + {"all with the same model", []*entity.Knowledgebase{kb("bge-m3", ""), kb("bge-m3", "")}, true}, + } + for _, c := range cases { + if got := hasEmbedderFor(c.kbs); got != c.want { + t.Errorf("%s: hasEmbedderFor = %v, want %v", c.name, got, c.want) + } + } +} + +// TestValidateDatasetEmbeddingModels pins knowledgebase_service.py:62-94. +// Mixing is a hard error upstream (get_models raises at dialog_service.py:358) — +// NOT a silent fallback to keyword-only retrieval. +func TestValidateDatasetEmbeddingModels(t *testing.T) { + t.Run("all without a model is allowed", func(t *testing.T) { + if err := validateDatasetEmbeddingModels(context.Background(), []*entity.Knowledgebase{ + kb("", ""), kb("", ""), + }); err != nil { + t.Errorf("all-without must be allowed, got %v", err) + } + }) + + t.Run("all same model is allowed", func(t *testing.T) { + if err := validateDatasetEmbeddingModels(context.Background(), []*entity.Knowledgebase{ + kb("bge-m3", ""), kb("bge-m3", ""), + }); err != nil { + t.Errorf("same model must be allowed, got %v", err) + } + }) + + t.Run("some with some without is an error", func(t *testing.T) { + if err := validateDatasetEmbeddingModels(context.Background(), []*entity.Knowledgebase{ + kb("bge-m3", ""), kb("", ""), + }); err == nil { + t.Error("mixing present/absent embedding models must error (Python raises)") + } + }) + + t.Run("different models is an error", func(t *testing.T) { + if err := validateDatasetEmbeddingModels(context.Background(), []*entity.Knowledgebase{ + kb("bge-m3", ""), kb("text-embedding-3", ""), + }); err == nil { + t.Error("different embedding models must error (Python raises)") + } + }) + + t.Run("dangling tenant_model id falls back to embd_id base name", func(t *testing.T) { + // Python silently skips ids that no longer resolve + // (tenant_model_service.py:557) and falls back to + // _base_model_name(embd_id) — it must not fail the request. + if err := validateDatasetEmbeddingModels(context.Background(), []*entity.Knowledgebase{ + kb("bge-m3@inst@prov", "gone-1"), kb("bge-m3@inst2@prov2", "gone-2"), + }); err != nil { + t.Errorf("two dangling refs with the same base name must be allowed, got %v", err) + } + }) +} + +// TestBaseModelNameMirrorsPython pins knowledgebase_service.py:33: +// rsplit("@", 2)[0] — the model name, with @instance@provider stripped. +func TestBaseModelNameMirrorsPython(t *testing.T) { + cases := []struct{ in, want string }{ + {"bge-m3@inst@prov", "bge-m3"}, + {"bge-m3@inst", "bge-m3"}, + {"bge-m3", "bge-m3"}, + {"", ""}, + } + for _, c := range cases { + if got := baseModelName(c.in); got != c.want { + t.Errorf("baseModelName(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +// TestHarnessWebSearcherNilAndWrapped pins the adapter: a nil pipeline callback +// must yield a nil harness.WebSearcher (which hides the web_search tool), and a +// non-nil one must be callable through the seam. +func TestHarnessWebSearcherNilAndWrapped(t *testing.T) { + if got := harnessWebSearcher(nil); got != nil { + t.Error("nil callback must yield a nil WebSearcher") + } + called := false + searcher := harnessWebSearcher(func(_ context.Context, queries []string) ([]string, error) { + called = true + return queries, nil + }) + if searcher == nil { + t.Fatal("non-nil callback must yield a WebSearcher") + } + got, err := searcher.Search(context.Background(), []string{"q"}) + if err != nil { + t.Fatalf("Search: %v", err) + } + if !called { + t.Error("callback was not invoked") + } + if len(got) != 1 || got[0] != "q" { + t.Errorf("Search = %v, want [q]", got) + } +} + +// errStubEncode stands in for a provider-side embedding failure. +var errStubEncode = errors.New("stub encode failure") + +// recordingEngine captures the SearchRequest so the tests can pin the adapter's +// mapping without a live document engine. +type recordingEngine struct { + last *types.SearchRequest + res *types.SearchResult +} + +func (e *recordingEngine) Search(_ context.Context, req *types.SearchRequest) (*types.SearchResult, error) { + e.last = req + if e.res != nil { + return e.res, nil + } + return &types.SearchResult{}, nil +} + +// TestEngineCompiledStoreSearchCompiledMapsRequest pins the mapping from the +// harness' compiled-row request onto the engine search: tenant index, kb scope, +// numeric available_int, the synthesis-page doc-scope column (source_doc_ids), +// and the keyword match leg over content_ltks/content_sm_ltks. +func TestEngineCompiledStoreSearchCompiledMapsRequest(t *testing.T) { + eng := &recordingEngine{} + // No embedder wired → the keyword leg stands alone. + store := newEngineCompiledStore(eng, nil, "") + _, err := store.SearchCompiled(context.Background(), "kb1", "t1", []string{"d1"}, map[string][]string{ + "compile_kwd": {"wiki_page"}, + "available_int": {"1"}, + }, "culdcept", 7) + if err != nil { + t.Fatalf("SearchCompiled: %v", err) + } + req := eng.last + if req == nil { + t.Fatal("engine was not called") + } + if len(req.IndexNames) != 1 || req.IndexNames[0] != "ragflow_t1" { + t.Errorf("IndexNames = %v, want [ragflow_t1]", req.IndexNames) + } + if len(req.KbIDs) != 1 || req.KbIDs[0] != "kb1" { + t.Errorf("KbIDs = %v, want [kb1]", req.KbIDs) + } + if req.Limit != 7 { + t.Errorf("Limit = %d, want 7", req.Limit) + } + // available_int is a numeric column: "1" must reach the engine as an int. + if got, ok := req.Filter["available_int"].([]int); !ok || len(got) != 1 || got[0] != 1 { + t.Errorf("available_int = %#v, want []int{1}", req.Filter["available_int"]) + } + if got, ok := req.Filter["compile_kwd"].([]string); !ok || len(got) != 1 || got[0] != "wiki_page" { + t.Errorf("compile_kwd = %#v, want []string{wiki_page}", req.Filter["compile_kwd"]) + } + // Synthesis pages are scoped by source_doc_ids, not doc_id. + if _, ok := req.Filter["source_doc_ids"]; !ok { + t.Errorf("doc scope key = %v, want source_doc_ids present", req.Filter) + } + if _, ok := req.Filter["doc_id"]; ok { + t.Errorf("synthesis rows must not use doc_id scope: %v", req.Filter) + } + if len(req.MatchExprs) != 1 { + t.Fatalf("MatchExprs = %#v, want one keyword expr", req.MatchExprs) + } + mt, ok := req.MatchExprs[0].(*types.MatchTextExpr) + if !ok { + t.Fatalf("MatchExprs[0] = %T, want *types.MatchTextExpr", req.MatchExprs[0]) + } + if mt.MatchingText != "culdcept" || mt.TopN != 7 { + t.Errorf("keyword expr = %+v, want text=culdcept topN=7", mt) + } + if len(mt.Fields) != 2 || mt.Fields[0] != "content_ltks" || mt.Fields[1] != "content_sm_ltks" { + t.Errorf("keyword fields = %v, want [content_ltks content_sm_ltks]", mt.Fields) + } +} + +// TestCompiledDocScopeKey pins Python's column choice: entity/relation rows use +// doc_id; the three synthesis kinds use source_doc_ids. +func TestCompiledDocScopeKey(t *testing.T) { + cases := []struct { + name string + filters map[string][]string + want string + }{ + {"entity rows", map[string][]string{"knowledge_graph_kwd": {"entity"}}, "doc_id"}, + {"tree rows", map[string][]string{"knowledge_graph_kwd": {"entity"}, "compile_kwd": {"tree"}}, "doc_id"}, + {"wiki pages", map[string][]string{"compile_kwd": {"wiki_page"}}, "source_doc_ids"}, + {"artifact pages", map[string][]string{"compile_kwd": {"artifact_page"}}, "source_doc_ids"}, + {"essence", map[string][]string{"compile_kwd": {"essence"}}, "source_doc_ids"}, + } + for _, c := range cases { + if got := compiledDocScopeKey(c.filters); got != c.want { + t.Errorf("%s: compiledDocScopeKey = %q, want %q", c.name, got, c.want) + } + } +} + +// TestEngineCompiledStoreLoadChunks pins the id-scoped fetch used to promote +// source chunks into evidence. +func TestEngineCompiledStoreLoadChunks(t *testing.T) { + eng := &recordingEngine{res: &types.SearchResult{Chunks: []map[string]interface{}{{"id": "c1"}}}} + store := newEngineCompiledStore(eng, nil, "") + rows, err := store.LoadChunks(context.Background(), "kb1", "t1", []string{"c1", "c2"}) + if err != nil { + t.Fatalf("LoadChunks: %v", err) + } + if len(rows) != 1 { + t.Fatalf("rows = %d, want 1", len(rows)) + } + if eng.last.Limit != 2 { + t.Errorf("Limit = %d, want 2", eng.last.Limit) + } + ids, ok := eng.last.Filter["id"].([]string) + if !ok || len(ids) != 2 || ids[0] != "c1" || ids[1] != "c2" { + t.Errorf("id filter = %#v, want [c1 c2]", eng.last.Filter["id"]) + } +} + +// TestNewDatasetCompiledStore pins the store wiring: no engine yields no store; +// datasets without an embedding model yield a keyword-only store; a dataset +// embedding model wires the query encoder with THAT dataset's model and owner +// tenant (not a tenant default or the request tenant). +func TestNewDatasetCompiledStore(t *testing.T) { + eng := &recordingEngine{} + if got := newDatasetCompiledStore(nil, nil, nil); got != nil { + t.Error("nil engine must disable the compiled store") + } + if got := newDatasetCompiledStore(eng, nil, []*entity.Knowledgebase{{ID: "kb1", TenantID: "t1"}}); got == nil { + t.Error("engine without an embedder must still build a keyword-only store") + } + store := newDatasetCompiledStore(eng, service.NewModelProviderService(), + []*entity.Knowledgebase{{ID: "kb1", EmbdID: "bge-m3@inst@prov", TenantID: "owner-tenant"}}) + es, ok := store.(*engineCompiledStore) + if !ok { + t.Fatalf("store = %T, want *engineCompiledStore", store) + } + if es.embed == nil { + t.Fatal("the dataset's embedding model must wire the query encoder") + } + if es.embedTenantID != "owner-tenant" { + t.Errorf("embedTenantID = %q, want owner-tenant (the dataset owner, not the request tenant)", es.embedTenantID) + } +} + +// stubQueryEncoder records the query-encoding calls the dense leg makes. +type stubQueryEncoder struct { + vecs [][]float32 + err error + calls int + lastTenant string +} + +func (s *stubQueryEncoder) EncodeQueries(_ context.Context, tenantID string, _ []string) ([][]float32, error) { + s.calls++ + s.lastTenant = tenantID + return s.vecs, s.err +} + +// TestEngineCompiledStoreUsesDenseSeedLeg pins the parity fix: when an embedder +// is wired, the compiled-row search goes out as a DENSE expr on the query +// vector's q__vec column with Python's num_candidates floor and similarity +// threshold — and carries NO keyword expr alongside it (Python appends exactly +// one). The encoding runs under the embedder's OWN tenant (Python +// embd_owner_tenant_id = kbs[0].tenant_id), not the searched scope's tenant. +func TestEngineCompiledStoreUsesDenseSeedLeg(t *testing.T) { + eng := &recordingEngine{} + enc := &stubQueryEncoder{vecs: [][]float32{{1, 2, 3}}} + // Scope tenant differs from the embedder's owner tenant on purpose. + store := newEngineCompiledStore(eng, enc, "owner-tenant") + + if _, err := store.SearchCompiled(context.Background(), "kb1", "scope-tenant", nil, + map[string][]string{"knowledge_graph_kwd": {"entity"}}, "culdcept", 5); err != nil { + t.Fatalf("SearchCompiled: %v", err) + } + if enc.calls != 1 { + t.Fatalf("encode calls = %d, want 1", enc.calls) + } + if enc.lastTenant != "owner-tenant" { + t.Errorf("encode tenant = %q, want the embedder's owner tenant owner-tenant", enc.lastTenant) + } + if len(eng.last.MatchExprs) != 1 { + t.Fatalf("MatchExprs = %#v, want exactly one dense expr", eng.last.MatchExprs) + } + dense, ok := eng.last.MatchExprs[0].(*types.MatchDenseExpr) + if !ok { + t.Fatalf("MatchExprs[0] = %T, want *types.MatchDenseExpr", eng.last.MatchExprs[0]) + } + if dense.VectorColumnName != "q_3_vec" { + t.Errorf("VectorColumnName = %q, want q_3_vec", dense.VectorColumnName) + } + if dense.EmbeddingDataType != "float" || dense.DistanceType != "cosine" || dense.TopN != 5 { + t.Errorf("dense expr = %+v, want float/cosine/topN=5", dense) + } + if dense.ExtraOptions["similarity"] != 0.1 { + t.Errorf("similarity = %v, want 0.1", dense.ExtraOptions["similarity"]) + } + // max(topN, 256) — a small topN is floored to the HNSW candidate count. + if dense.ExtraOptions["num_candidates"] != 256 { + t.Errorf("num_candidates = %v, want 256 (max(5,256))", dense.ExtraOptions["num_candidates"]) + } + + // A topN above the floor is passed through unchanged. + if _, err := store.SearchCompiled(context.Background(), "kb1", "scope-tenant", nil, + map[string][]string{"knowledge_graph_kwd": {"entity"}}, "culdcept", 300); err != nil { + t.Fatalf("SearchCompiled(300): %v", err) + } + dense300 := eng.last.MatchExprs[0].(*types.MatchDenseExpr) + if dense300.ExtraOptions["num_candidates"] != 300 { + t.Errorf("num_candidates = %v, want 300", dense300.ExtraOptions["num_candidates"]) + } +} + +// TestEngineCompiledStoreDenseFallsBackToKeyword pins Python's `except Exception` +// around get_vector: an encode failure (or an empty vector) must degrade to the +// keyword leg rather than dropping the expansion. +func TestEngineCompiledStoreDenseFallsBackToKeyword(t *testing.T) { + for _, c := range []struct { + name string + enc *stubQueryEncoder + }{ + {"encode error", &stubQueryEncoder{err: errStubEncode}}, + {"empty vector", &stubQueryEncoder{vecs: [][]float32{{}}}}, + {"no vectors", &stubQueryEncoder{vecs: nil}}, + } { + t.Run(c.name, func(t *testing.T) { + eng := &recordingEngine{} + store := newEngineCompiledStore(eng, c.enc, "t1") + if _, err := store.SearchCompiled(context.Background(), "kb1", "t1", nil, + map[string][]string{"knowledge_graph_kwd": {"entity"}}, "culdcept", 5); err != nil { + t.Fatalf("SearchCompiled: %v", err) + } + if c.enc.calls != 1 { + t.Errorf("encode calls = %d, want 1", c.enc.calls) + } + if len(eng.last.MatchExprs) != 1 { + t.Fatalf("MatchExprs = %#v, want one keyword expr", eng.last.MatchExprs) + } + mt, ok := eng.last.MatchExprs[0].(*types.MatchTextExpr) + if !ok { + t.Fatalf("MatchExprs[0] = %T, want *types.MatchTextExpr keyword fallback", eng.last.MatchExprs[0]) + } + if mt.MatchingText != "culdcept" { + t.Errorf("keyword text = %q, want culdcept", mt.MatchingText) + } + }) + } +} diff --git a/go.mod b/go.mod index 6056062c6c5..96d38884c7d 100644 --- a/go.mod +++ b/go.mod @@ -11,6 +11,7 @@ require ( github.com/DATA-DOG/go-sqlmock v1.5.2 github.com/JohannesKaufmann/html-to-markdown v1.6.0 github.com/LuxorLabs/tenki-sdk-go/sandbox v0.7.0 + github.com/RealAlexandreAI/json-repair v0.0.17 github.com/alibabacloud-go/agentrun-20250910/v5 v5.8.4 github.com/alibabacloud-go/darabonba-openapi/v2 v2.2.1 github.com/alicebob/miniredis/v2 v2.38.0 @@ -144,7 +145,7 @@ require ( github.com/dlclark/regexp2 v1.10.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/ebitengine/purego v0.10.1 // indirect - github.com/eino-contrib/jsonschema v1.0.3 // indirect + github.com/eino-contrib/jsonschema v1.0.3 github.com/elastic/elastic-transport-go/v8 v8.8.0 // indirect github.com/envoyproxy/go-control-plane/envoy v1.37.0 // indirect github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect diff --git a/go.sum b/go.sum index 0826ca25f93..4c7d7a2cac2 100644 --- a/go.sum +++ b/go.sum @@ -62,6 +62,8 @@ github.com/LuxorLabs/tenki-sdk-go/sandbox v0.7.0/go.mod h1:rBypesed6hSrj+OgpJwyM github.com/PuerkitoBio/goquery v1.9.2 h1:4/wZksC3KgkQw7SQgkKotmKljk0M6V8TUvA8Wb4yPeE= github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk= github.com/RaveNoX/go-jsoncommentstrip v1.0.0/go.mod h1:78ihd09MekBnJnxpICcwzCMzGrKSKYe4AqU6PDYYpjk= +github.com/RealAlexandreAI/json-repair v0.0.17 h1:nXppoV05wAPo/+/HjpFkvvAgTb98s3bPcAALldG7j/g= +github.com/RealAlexandreAI/json-repair v0.0.17/go.mod h1:GKJi5borR78O8c7HCVbgqjhoiVibZ6hJldxbc6dGrAI= github.com/airbrake/gobrake v3.6.1+incompatible/go.mod h1:wM4gu3Cn0W0K7GUuVWnlXZU11AGBXMILnrdOU8Kn00o= github.com/alibabacloud-go/agentrun-20250910/v5 v5.8.4 h1:hiAsm9pz6aICOPLI1FC54vga10xwd/XxfNj06ow5jVM= github.com/alibabacloud-go/agentrun-20250910/v5 v5.8.4/go.mod h1:CYOwrIjr05fOHvdhid7MWtP/IT5ILLcE0eqiolzQT/Q= diff --git a/internal/agent/audio/tts_dispatch.go b/internal/agent/audio/tts_dispatch.go index ab4978807ff..6646795d7b1 100644 --- a/internal/agent/audio/tts_dispatch.go +++ b/internal/agent/audio/tts_dispatch.go @@ -77,7 +77,7 @@ type TTSDispatcher interface { // // - ModelProviderRequest.ModelName (from req.Engine) → modelName // The Engine field is repurposed as a model identifier hint -// in the audio package's contract. Built-in engine selectors +// in the audio package's Built-in engine selectors // ("gtts" / "edge-tts" / "custom") and an empty hint fall // through to the tenant's default TTS model; any other value // is passed as an explicit model name to the by-name lookup. diff --git a/internal/agent/chat/chat.go b/internal/agent/chat/chat.go index b8e3da96b4c..acc112f6640 100644 --- a/internal/agent/chat/chat.go +++ b/internal/agent/chat/chat.go @@ -17,9 +17,9 @@ // Package chat is a dependency-light home for the LLM chat-invoker interface // and its package-level singleton. It lives here (leaf, importing only eino // schema + gorm) so that both internal/agent/component (which owns the -// production eino-based invoker) and internal/agent/tool / internal/agent/harness -// (which need to call the LLM for routing/selection) can depend on it without -// forming an import cycle. The production invoker is registered at boot via +// production eino-based invoker) and internal/agent/tool / +// internal/rag/advanced_rag/harness (which need to call the LLM for +// routing/selection) can depend on it without forming an import cycle. The production invoker is registered at boot via // SetDefaultInvoker. package chat @@ -38,6 +38,52 @@ type Invoker interface { Invoke(ctx context.Context, db *gorm.DB, req Request) (*Response, error) } +// StreamingInvoker is implemented by invokers whose provider can emit the reply +// incrementally. Callers type-assert for it and fall back to Invoke when it is +// absent, so streaming stays an enhancement rather than a requirement. +// +// onDelta receives each piece as it arrives; isThink marks pieces of a hidden +// reasoning block, which must not be shown as part of the answer. +type StreamingInvoker interface { + Invoker + Stream(ctx context.Context, db *gorm.DB, req Request, onDelta func(delta string, isThink bool) error) (*Response, error) +} + +// Tool is one callable declared to the provider for native tool calling. It +// mirrors the OpenAI tool object (type + function) so the harness can forward +// its existing ToolSpec surface without reshaping it. +type Tool struct { + Type string `json:"type"` // "function" (only value providers accept today) + Function ToolFunction `json:"function"` +} + +// ToolFunction is the callable's name, description, and JSON-schema parameters. +type ToolFunction struct { + Name string `json:"name"` + Description string `json:"description"` + Parameters map[string]any `json:"parameters,omitempty"` +} + +// ToolCall is one invocation the provider requested via native tool calling. +// It carries the arguments as a parsed map so the harness can dispatch without +// re-parsing a fenced block. +type ToolCall struct { + ID string + Name string + Arguments map[string]any +} + +// ToolChoice controls whether/how the provider may call tools. "" (unset) lets +// the provider decide; "auto" mirrors OpenAI tool_choice="auto"; "none" forbids +// calls; "required" forces at least one call. +type ToolChoice string + +const ( + ToolChoiceAuto ToolChoice = "auto" + ToolChoiceNone ToolChoice = "none" + ToolChoiceRequired ToolChoice = "required" +) + // Request is the minimal surface needed to dispatch a chat call. type Request struct { Driver string @@ -51,6 +97,19 @@ type Request struct { FrequencyPenalty *float64 MaxTokens *int Thinking string // "enabled" | "disabled" | "" + // Tools, when non-nil, switches the call from prompt-based tool parsing to + // native provider tool calling. ToolChoice constrains the provider's use of + // them (see ToolChoice). Nil means no tools are declared. + Tools []Tool + ToolChoice ToolChoice +} + +// Usage is the token usage split for one chat call, mirroring the provider's +// prompt/completion/total breakdown (Python token_utils.usage_from_response). +type Usage struct { + PromptTokens int + CompletionTokens int + TotalTokens int } // Response is the result of a chat call. @@ -59,7 +118,18 @@ type Response struct { Thinking string Model string Stopped bool - Tokens int + // Tokens is the total token count (TotalTokens). Deprecated in favour of + // Usage, which carries the prompt/completion split; kept so existing callers + // that only total keep working unchanged. + Tokens int + // Usage carries the prompt/completion/total split when the provider reports + // it. Nil when the provider reported nothing. + Usage *Usage + // ToolCalls carries native provider tool invocations when the request + // declared Tools. Empty when the provider returned no calls (or the request + // used prompt-based tooling). The harness falls back to prompt parsing when + // this is empty and tools were requested. + ToolCalls []ToolCall } // ErrNotConfigured is returned by GetDefaultInvoker when no production invoker @@ -71,9 +141,8 @@ type configError struct{ msg string } func (e *configError) Error() string { return e.msg } var ( - mu sync.RWMutex - inst Invoker - defaultModel string + mu sync.RWMutex + inst Invoker ) // SetDefaultInvoker installs the (production or test) invoker. Pass nil to @@ -84,22 +153,6 @@ func SetDefaultInvoker(inv Invoker) { inst = inv } -// SetDefaultModelName records the tenant-default chat model name. The production -// invoker uses it when a Request omits ModelName, so harness/agentic-search LLM -// calls work without threading model config through every node. -func SetDefaultModelName(name string) { - mu.Lock() - defer mu.Unlock() - defaultModel = name -} - -// GetDefaultModelName returns the configured default model name ("" if unset). -func GetDefaultModelName() string { - mu.RLock() - defer mu.RUnlock() - return defaultModel -} - // GetDefaultInvoker returns the installed invoker. It returns nil when no // invoker has been installed (e.g. before server bootstrap or in tests that do // not need the LLM). diff --git a/internal/agent/chat/message_fit.go b/internal/agent/chat/message_fit.go new file mode 100644 index 00000000000..24c132340aa --- /dev/null +++ b/internal/agent/chat/message_fit.go @@ -0,0 +1,178 @@ +// +// 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. +// + +package chat + +import ( + "slices" + "strings" + + "github.com/cloudwego/eino/schema" + + "ragflow/internal/tokenizer" +) + +// Message fitting (Python message_fit_in). +// +// This lives in the chat package rather than internal/agent/component so that +// both component (which owns the production eino invoker) and +// internal/rag/advanced_rag/harness (which composes answers) can fit prompts +// without forming an import cycle — component cannot import harness, because +// harness's own tests import component. + +// EffectiveContextLength returns maxLength if positive, otherwise 8192. +// Mirrors Python's LLM.effective_context_length in PR #16413 — prevents +// zero/negative context windows from silently trimming all prompt content. +func EffectiveContextLength(maxLength int) int { + if maxLength > 0 { + return maxLength + } + return 8192 +} + +// ContextFitBudget returns 97% of the effective context length as the +// token budget for message_fit_in. Mirrors Python's LLM.context_fit_budget +// in PR #16413. +func ContextFitBudget(maxLength int) int { + return int(float64(EffectiveContextLength(maxLength)) * 0.97) +} + +// validateFittedMessages checks that the fitted message list is non-empty +// and the last message is a non-empty user turn (content or multi-modal +// parts). Returns an error string on failure, empty string on success. +// Python requires len >= 2 because the system prompt is always injected +// upstream; Go allows len >= 1 because the system message may be embedded +// inside msgs (from buildMessagesWithImages) or absent entirely. +func validateFittedMessages(msgFit []schema.Message) string { + if len(msgFit) == 0 { + return "**ERROR**: message_fit_in produced insufficient messages for LLM" + } + last := msgFit[len(msgFit)-1] + if last.Role != schema.User { + return "**ERROR**: LLM last message is not a user turn after prompt fitting; check model content_length context setting" + } + if strings.TrimSpace(last.Content) == "" && len(last.UserInputMultiContent) == 0 { + return "**ERROR**: LLM user message is empty after prompt fitting; check model content_length context setting" + } + return "" +} + +// FitMessages applies message_fit_in semantics to the given messages and +// validates that the result ends with a non-empty user turn. Returns the +// fitted messages and an error string (empty on success). +// Mirrors Python's LLM.fit_messages in PR #16413. +func FitMessages(systemPrompt string, msgs []schema.Message, maxLength int) ([]schema.Message, string) { + // Deep-copy msgs (mirrors Python's deepcopy) to avoid mutating caller's slice. + copied := make([]schema.Message, len(msgs)) + for i, m := range msgs { + cloned := slices.Clone(m.UserInputMultiContent) + for j, p := range cloned { + if p.Image != nil { + imgCopy := *p.Image + if p.Image.URL != nil { + u := *p.Image.URL + imgCopy.URL = &u + } + cloned[j].Image = &imgCopy + } + } + copied[i] = schema.Message{ + Role: m.Role, + Content: m.Content, + UserInputMultiContent: cloned, + } + } + + // Convert to messagefit.Message. Track where each entry's text lives + // (plain Content or a multi-modal text part) so the fitted text can be + // written back to the right field. Entries with no text at all + // (image-only turns) carry an empty Content in messagefit and survive + // fitting when kept. + type fitSource struct { + copiedIdx int // index into copied; -1 for the synthetic system prompt + multiIdx int // -1 means the text lives in Content + textInContent bool // the original message carried text in Content + } + all := make([]tokenizer.Message, 0, 1+len(copied)) + sources := make([]fitSource, 0, 1+len(copied)) + + if systemPrompt != "" { + all = append(all, tokenizer.Message{Role: "system", Content: systemPrompt}) + sources = append(sources, fitSource{copiedIdx: -1, multiIdx: 0}) + } + + for i := range copied { + text := copied[i].Content + multiIdx := -1 + hadText := text != "" + if !hadText { + // Fold every non-empty text part into the token budget: only the + // first text part is written back, so leaving later parts out + // would let text exceed the fitted budget after reconstruction. + var textParts []string + for j, p := range copied[i].UserInputMultiContent { + if p.Type == schema.ChatMessagePartTypeText && p.Text != "" { + textParts = append(textParts, p.Text) + if multiIdx < 0 { + multiIdx = j + } + } + } + if len(textParts) > 0 { + text = strings.Join(textParts, "\n\n") + } + } + all = append(all, tokenizer.Message{Role: string(copied[i].Role), Content: text}) + sources = append(sources, fitSource{copiedIdx: i, multiIdx: multiIdx, textInContent: copied[i].Content != ""}) + } + + // Use 97% of effective context as the token budget. + budget := ContextFitBudget(maxLength) + kept, keptIdx, _ := tokenizer.Fit(all, budget) + + // Convert back to []schema.Message. messagefit.Fit reports exactly which + // entries are kept (keptIdx); dropped entries are simply absent, so no + // empty-content sentinel is needed and image-only turns are preserved. + result := make([]schema.Message, 0, len(kept)) + for j, i := range keptIdx { + src := sources[i] + if src.copiedIdx < 0 { + result = append(result, schema.Message{Role: schema.System, Content: kept[j].Content}) + continue + } + m := copied[src.copiedIdx] + if src.multiIdx >= 0 && src.multiIdx < len(m.UserInputMultiContent) { + m.UserInputMultiContent[src.multiIdx].Text = kept[j].Content + // Drop any additional text parts: their content was folded into + // the first part before fitting, so keeping them would re-introduce + // text outside the token budget. + keptParts := m.UserInputMultiContent[:0] + for k, part := range m.UserInputMultiContent { + if part.Type == schema.ChatMessagePartTypeText && k != src.multiIdx { + continue + } + keptParts = append(keptParts, part) + } + m.UserInputMultiContent = keptParts + } else if src.textInContent { + // Always write the fitted text back (even when trimmed to empty): + // leaving the original would send untrimmed content past the budget. + m.Content = kept[j].Content + } + result = append(result, m) + } + return result, validateFittedMessages(result) +} diff --git a/internal/agent/chat/message_fit_test.go b/internal/agent/chat/message_fit_test.go new file mode 100644 index 00000000000..3820fedb146 --- /dev/null +++ b/internal/agent/chat/message_fit_test.go @@ -0,0 +1,211 @@ +// +// 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. +// + +package chat + +import ( + "strings" + "testing" + + "github.com/cloudwego/eino/schema" + + "ragflow/internal/tokenizer" +) + +func TestFitMessages_EverythingFits(t *testing.T) { + msgs := []schema.Message{ + {Role: schema.System, Content: "you are helpful"}, + {Role: schema.User, Content: "hello"}, + } + fitted, fitErr := FitMessages("", msgs, 100000) + if fitErr != "" { + t.Fatalf("unexpected fit error: %s", fitErr) + } + if len(fitted) != 2 { + t.Fatalf("got %d messages, want 2", len(fitted)) + } + if fitted[0].Content != "you are helpful" || fitted[1].Content != "hello" { + t.Fatalf("messages modified when they fit: %+v", fitted) + } +} + +func TestFitMessages_PreservesImageOnlyTurn(t *testing.T) { + imgURL := "data:image/png;base64,AAAA" + msgs := []schema.Message{ + {Role: schema.System, Content: "you are helpful"}, + {Role: schema.User, UserInputMultiContent: []schema.MessageInputPart{ + {Type: schema.ChatMessagePartTypeImageURL, Image: &schema.MessageInputImage{ + MessagePartCommon: schema.MessagePartCommon{URL: &imgURL}, + }}, + }}, + } + fitted, fitErr := FitMessages("", msgs, 100000) + if fitErr != "" { + t.Fatalf("unexpected fit error: %s", fitErr) + } + if len(fitted) != 2 { + t.Fatalf("got %d messages, want 2 (image-only turn must be preserved)", len(fitted)) + } + last := fitted[len(fitted)-1] + if len(last.UserInputMultiContent) != 1 || last.UserInputMultiContent[0].Type != schema.ChatMessagePartTypeImageURL { + t.Fatalf("image parts lost after fitting: %+v", last) + } +} + +func TestFitMessages_IncludesSyntheticSystemPrompt(t *testing.T) { + msgs := []schema.Message{{Role: schema.User, Content: "hello"}} + fitted, fitErr := FitMessages("be brief", msgs, 100000) + if fitErr != "" { + t.Fatalf("unexpected fit error: %s", fitErr) + } + if len(fitted) != 2 { + t.Fatalf("got %d messages, want 2 (synthetic system prompt + user)", len(fitted)) + } + if fitted[0].Role != schema.System || fitted[0].Content != "be brief" { + t.Fatalf("synthetic system prompt not preserved: %+v", fitted[0]) + } +} + +func TestFitMessages_DropsMiddleWhenOverBudget(t *testing.T) { + long := strings.Repeat("x ", 5000) + msgs := []schema.Message{ + {Role: schema.System, Content: long}, + {Role: schema.User, Content: "middle"}, + {Role: schema.User, Content: "last"}, + } + fitted, fitErr := FitMessages("", msgs, 1000) + if fitErr != "" { + t.Fatalf("unexpected fit error: %s", fitErr) + } + if len(fitted) != 2 { + t.Fatalf("got %d messages, want 2 (middle dropped, system + last user kept)", len(fitted)) + } + if fitted[0].Role != schema.System || fitted[1].Role != schema.User { + t.Fatalf("unexpected roles: %+v", fitted) + } + if !strings.Contains(fitted[1].Content, "last") { + t.Fatalf("last user message not preserved: %+v", fitted[1]) + } +} + +// TestFitMessages_SystemKeptButEmptied locks the write-back for a system +// message that the fitter keeps but trims to empty (the final user turn alone +// fills the budget): the fitted (empty) content must be written back instead +// of the original, so the conversation stays within the budget. +func TestFitMessages_SystemKeptButEmptied(t *testing.T) { + origSys := strings.Repeat("s ", 3000) // dominates (>80% of tokens) + msgs := []schema.Message{ + {Role: schema.System, Content: origSys}, + {Role: schema.User, Content: strings.Repeat("u ", 600)}, // alone exceeds the budget + } + fitted, fitErr := FitMessages("", msgs, 500) + if fitErr != "" { + t.Fatalf("unexpected fit error: %s", fitErr) + } + if len(fitted) != 2 { + t.Fatalf("got %d messages, want 2 (both kept)", len(fitted)) + } + if fitted[0].Role != schema.System || fitted[0].Content != "" { + t.Fatalf("system should be kept but trimmed to empty, got %+v", fitted[0]) + } + if fitted[1].Role != schema.User || fitted[1].Content == origSys { + t.Fatalf("user turn wrong after fitting: %+v", fitted[1]) + } + total := tokenizer.NumTokensFromString(fitted[0].Content) + tokenizer.NumTokensFromString(fitted[1].Content) + if total > 500 { + t.Fatalf("fitted total %d exceeds budget 500", total) + } +} + +// TestFitMessages_FoldsMultipleTextParts verifies that every non-empty text +// part of a multi-modal message participates in the token budget: the parts +// are folded into a single fitted text on the first text part and additional +// text parts are removed, so no text escapes the budget after reconstruction. +func TestFitMessages_FoldsMultipleTextParts(t *testing.T) { + long1 := strings.Repeat("a ", 3000) + long2 := strings.Repeat("b ", 3000) + imgURL := "data:image/png;base64,AAAA" + msgs := []schema.Message{ + {Role: schema.System, Content: "sys"}, + {Role: schema.User, UserInputMultiContent: []schema.MessageInputPart{ + {Type: schema.ChatMessagePartTypeText, Text: long1}, + {Type: schema.ChatMessagePartTypeImageURL, Image: &schema.MessageInputImage{ + MessagePartCommon: schema.MessagePartCommon{URL: &imgURL}, + }}, + {Type: schema.ChatMessagePartTypeText, Text: long2}, + }}, + } + fitted, fitErr := FitMessages("", msgs, 2000) + if fitErr != "" { + t.Fatalf("unexpected fit error: %s", fitErr) + } + if len(fitted) != 2 { + t.Fatalf("got %d messages, want 2", len(fitted)) + } + last := fitted[len(fitted)-1] + textParts := 0 + imageParts := 0 + for _, part := range last.UserInputMultiContent { + switch part.Type { + case schema.ChatMessagePartTypeText: + textParts++ + case schema.ChatMessagePartTypeImageURL: + imageParts++ + } + } + if textParts != 1 { + t.Fatalf("got %d text parts, want 1 (folded): %+v", textParts, last.UserInputMultiContent) + } + if imageParts != 1 { + t.Fatalf("image part lost after trimming: %+v", last.UserInputMultiContent) + } + if total := tokenizer.NumTokensFromString(last.UserInputMultiContent[0].Text); total > 2000 { + t.Fatalf("fitted text totals %d tokens, exceeds budget 2000", total) + } +} + +// TestFitMessages_ImageOnlyLastTurnOverBudget locks the over-budget path where +// an image-only turn is the last non-system message (ll2 = 0 tokens): the +// fitter keeps it, gives the whole budget to the system messages, and the +// image-only turn must survive reconstruction untouched. +func TestFitMessages_ImageOnlyLastTurnOverBudget(t *testing.T) { + imgURL := "data:image/png;base64,AAAA" + msgs := []schema.Message{ + {Role: schema.System, Content: strings.Repeat("s ", 3000)}, // dominates (>80% of tokens) + {Role: schema.User, UserInputMultiContent: []schema.MessageInputPart{ + {Type: schema.ChatMessagePartTypeImageURL, Image: &schema.MessageInputImage{ + MessagePartCommon: schema.MessagePartCommon{URL: &imgURL}, + }}, + }}, + } + fitted, fitErr := FitMessages("", msgs, 500) + if fitErr != "" { + t.Fatalf("unexpected fit error: %s", fitErr) + } + if len(fitted) != 2 { + t.Fatalf("got %d messages, want 2 (system + image-only turn)", len(fitted)) + } + if fitted[0].Role != schema.System || fitted[0].Content == msgs[0].Content { + t.Fatalf("system should be trimmed to the budget: %+v", fitted[0]) + } + if total := tokenizer.NumTokensFromString(fitted[0].Content); total > 500 { + t.Fatalf("system exceeds budget after fit: %d tokens", total) + } + last := fitted[len(fitted)-1] + if last.Role != schema.User || len(last.UserInputMultiContent) != 1 || last.UserInputMultiContent[0].Type != schema.ChatMessagePartTypeImageURL { + t.Fatalf("image-only turn lost or modified after over-budget fitting: %+v", last) + } +} diff --git a/internal/agent/component/invoke.go b/internal/agent/component/invoke.go index 4b14d190150..2ee8e75f725 100644 --- a/internal/agent/component/invoke.go +++ b/internal/agent/component/invoke.go @@ -85,7 +85,7 @@ func (i *InvokeComponent) Name() string { return i.name } // Invoke executes a single HTTP request and returns its response text as // `result`, matching the Python Invoke component. See Inputs() for the -// param contract. +// param // // SSRF flow (PR #15426): // 1. Validate the target URL via utility.AssertURLSafe (loopback / diff --git a/internal/agent/component/io/docx_writer.go b/internal/agent/component/io/docx_writer.go index cd57a0f8d0e..c70ce50adfa 100644 --- a/internal/agent/component/io/docx_writer.go +++ b/internal/agent/component/io/docx_writer.go @@ -29,7 +29,7 @@ // minimal: a single font, a single style, and a flat list of // paragraphs. Tables / images / lists are future polish items; the // test suite (see docx_writer_test.go) verifies the ZIP magic, the -// embedded document.xml content, and the XML-escape contract. +// embedded document.xml content, and the XML-escape package io import ( diff --git a/internal/agent/component/io/html_writer_test.go b/internal/agent/component/io/html_writer_test.go index f0f26a54241..467e6d0fc0f 100644 --- a/internal/agent/component/io/html_writer_test.go +++ b/internal/agent/component/io/html_writer_test.go @@ -136,7 +136,7 @@ func TestWriteHTML_HTMLStructure(t *testing.T) { // TestWriteHTML_ContentNotEscaped: the writer does NOT HTML-escape // the body — callers are expected to pass already-clean content. -// This test pins the no-escape contract. +// This test pins the no-escape func TestWriteHTML_ContentNotEscaped(t *testing.T) { out := string(WriteHTML("bold", HTMLOptions{})) if !strings.Contains(out, "bold") { diff --git a/internal/agent/component/list_operations.go b/internal/agent/component/list_operations.go index 9c2846366ea..94cf14dbe4c 100644 --- a/internal/agent/component/list_operations.go +++ b/internal/agent/component/list_operations.go @@ -556,7 +556,7 @@ func dedupKey(v any) string { // normValue is the Python _norm helper: "" for nil, else str(v). // Bools are rendered as "True" / "False" (Python's str() output) so -// filter `=` comparisons match the Python DSL contract. Mirrors +// filter `=` comparisons match the Python DSL Mirrors // agent/component/list_operations.py:151-153. func normValue(v any) string { if v == nil { diff --git a/internal/agent/component/list_operations_test.go b/internal/agent/component/list_operations_test.go index e92a76862ad..42da235d0c8 100644 --- a/internal/agent/component/list_operations_test.go +++ b/internal/agent/component/list_operations_test.go @@ -439,7 +439,7 @@ func TestListOperations_CoerceNBool(t *testing.T) { // TestListOperations_FilterEqBool pins Change #5: normValue must render // Go's bool as Python's str(bool) ("True"/"False") so filter `=` matches -// the Python DSL contract. +// the Python DSL func TestListOperations_FilterEqBool(t *testing.T) { c, err := NewListOperationsComponent(map[string]any{ "query": "cpn_0@xs", diff --git a/internal/agent/component/llm.go b/internal/agent/component/llm.go index f738b25b643..aeeb78bf758 100644 --- a/internal/agent/component/llm.go +++ b/internal/agent/component/llm.go @@ -14,6 +14,7 @@ import ( "context" "encoding/json" "fmt" + "io" "regexp" "slices" "sort" @@ -21,6 +22,7 @@ import ( "time" "github.com/cloudwego/eino/schema" + einojsonschema "github.com/eino-contrib/jsonschema" "gorm.io/gorm" "ragflow/internal/agent/chat" @@ -186,13 +188,7 @@ type einoChatInvoker struct{} // Invoke satisfies ChatInvoker. func (e *einoChatInvoker) Invoke(ctx context.Context, db *gorm.DB, req ChatInvokeRequest) (*ChatInvokeResponse, error) { if req.ModelName == "" { - // Harness/agentic-search nodes may omit the model; fall back to the - // bootstrap-registered tenant default so those calls work in production. - if def := chat.GetDefaultModelName(); def != "" { - req.ModelName = def - } else { - return nil, fmt.Errorf("component: LLM: model_id is required and no default model is configured") - } + return nil, fmt.Errorf("component: LLM: model_id is required") } driver := req.Driver modelName := req.ModelName @@ -231,19 +227,374 @@ func (e *einoChatInvoker) Invoke(ctx context.Context, db *gorm.DB, req ChatInvok chatCfg.Thinking = &f } wrapper := models.NewEinoChatModel(cm, chatCfg) + einoMsgs := toEinoMessages(req.Messages) + infos, choice := toolOptions(req.Tools, req.ToolChoice) + if len(infos) > 0 { + withTools, err := wrapper.WithTools(infos) + if err != nil { + return nil, err + } + wrapper = withTools.(*models.EinoChatModel).WithToolChoice(choice) + } + out, err := wrapper.Generate(ctx, einoMsgs) + if err != nil { + return nil, err + } + resp := &ChatInvokeResponse{ + Content: out.Content, + Thinking: out.ReasoningContent, + Model: modelName, + Stopped: true, + Usage: usageFromCM(cm), + } + if calls := nativeToolCalls(out.ToolCalls); len(calls) > 0 { + resp.ToolCalls = calls + } + return resp, nil +} + +// usageFromCM copies a ChatModel's LastUsage split into the chat.Response Usage, +// and mirrors its total into Tokens for the callers that still read the legacy +// single counter. +func usageFromCM(cm *models.ChatModel) *chat.Usage { + if cm == nil || cm.LastUsage == nil { + return nil + } + return &chat.Usage{ + PromptTokens: cm.LastUsage.PromptTokens, + CompletionTokens: cm.LastUsage.CompletionTokens, + TotalTokens: cm.LastUsage.TotalTokens, + } +} + +// toolOptions converts the seam-level chat.Tool declarations into eino tool +// infos and a tool_choice string the provider understands. It returns +// (nil, "") when no tools were requested, so the invoke falls back to plain +// completion and the harness can still parse tool calls from a fenced block. +func toolOptions(tools []chat.Tool, choice chat.ToolChoice) ([]*schema.ToolInfo, string) { + if len(tools) == 0 { + return nil, "" + } + infos := make([]*schema.ToolInfo, 0, len(tools)) + for _, t := range tools { + name, desc := t.Function.Name, t.Function.Description + if name == "" { + continue + } + infos = append(infos, &schema.ToolInfo{ + Name: name, + Desc: desc, + ParamsOneOf: paramsFromMap(t.Function.Parameters), + }) + } + if len(infos) == 0 { + return nil, "" + } + resolved := "auto" + switch choice { + case chat.ToolChoiceNone: + resolved = "none" + case chat.ToolChoiceRequired: + resolved = "required" + case chat.ToolChoiceAuto: + resolved = "auto" + case "": + resolved = "auto" + } + return infos, resolved +} + +// paramsFromMap builds an eino ParamsOneOf from a raw JSON-schema dict. The +// harness ToolSpec carries the schema as map[string]any, so we round-trip it +// through JSON into a jsonschema.Schema. A malformed schema yields a permissive +// (empty) ParamsOneOf rather than failing the whole call. +func paramsFromMap(raw map[string]any) *schema.ParamsOneOf { + if len(raw) == 0 { + return &schema.ParamsOneOf{} + } + b, err := json.Marshal(raw) + if err != nil { + return &schema.ParamsOneOf{} + } + var js einojsonschema.Schema + if err := json.Unmarshal(b, &js); err != nil { + return &schema.ParamsOneOf{} + } + return schema.NewParamsOneOfByJSONSchema(&js) +} + +// nativeToolCalls converts eino tool calls into the seam's chat.ToolCall values, +// parsing each call's JSON arguments into a map for direct dispatch. A malformed +// argument string is left as an empty map rather than dropping the call, so the +// harness can surface the parse failure through its normal error path. +func nativeToolCalls(calls []schema.ToolCall) []chat.ToolCall { + if len(calls) == 0 { + return nil + } + out := make([]chat.ToolCall, 0, len(calls)) + for _, c := range calls { + args := map[string]any{} + if c.Function.Arguments != "" { + _ = json.Unmarshal([]byte(c.Function.Arguments), &args) + } + out = append(out, chat.ToolCall{ + ID: c.ID, + Name: c.Function.Name, + Arguments: args, + }) + } + return out +} + +// Stream satisfies chat.StreamingInvoker: it emits the reply as it arrives +// while still returning the assembled result, so a caller can push deltas to the +// user without waiting for the full answer. +func (e *einoChatInvoker) Stream(ctx context.Context, _ *gorm.DB, req ChatInvokeRequest, onDelta func(delta string, isThink bool) error) (*ChatInvokeResponse, error) { + modelName := req.ModelName + if modelName == "" { + return nil, fmt.Errorf("component: LLM: model_id is required") + } + driver, bareModel := req.Driver, modelName + if driver == "" && bareModel != "" { + if name, provider, ok := splitCompositeLLMID(bareModel); ok { + driver, bareModel = provider, name + } + } + if driver == "" { + driver = "dummy" + } + d, err := newChatModelDriver(driver, req.BaseURL) + if err != nil { + return nil, fmt.Errorf("component: LLM: resolve driver %q: %w", driver, err) + } + apiKey := req.APIKey + cm := models.NewChatModel(d, &bareModel, &models.APIConfig{ApiKey: &apiKey}) + chatCfg := &models.ChatConfig{Temperature: req.Temperature, TopP: req.TopP, MaxTokens: req.MaxTokens} + switch req.Thinking { + case "enabled": + t := true + chatCfg.Thinking = &t + case "disabled": + f := false + chatCfg.Thinking = &f + } + + wrapper := models.NewEinoChatModel(cm, chatCfg) + if infos, choice := toolOptions(req.Tools, req.ToolChoice); len(infos) > 0 { + withTools, err := wrapper.WithTools(infos) + if err != nil { + return nil, err + } + wrapper = withTools.(*models.EinoChatModel).WithToolChoice(choice) + } + return streamEinoChat(ctx, wrapper, toEinoMessages(req.Messages), cm, bareModel, onDelta) +} + +// streamEinoChat drains a streaming eino chat call and assembles the reply the +// one-shot path would have returned, forwarding every piece to onDelta as it +// arrives (reasoning pieces are flagged isThink so the caller never renders them +// as answer text). Both chat invokers share it, so streaming and one-shot calls +// cannot drift apart. +// +// Streaming native tool calls arrive as incremental deltas, each carrying an +// Index (parallel calls) and a slice of Function.Arguments. Merge them by +// index the same way Python's async_chat_streamly aggregates tool_calls +// (chat_model.py:711-719): first delta seeds the entry, later deltas append to +// the arguments string. The full list is committed once the stream ends. +func streamEinoChat(ctx context.Context, wrapper *models.EinoChatModel, msgs []*schema.Message, cm *models.ChatModel, modelName string, onDelta func(delta string, isThink bool) error) (*ChatInvokeResponse, error) { + sr, err := wrapper.Stream(ctx, msgs) + if err != nil { + return nil, err + } + defer sr.Close() + + var content, reasoning strings.Builder + pendingCalls := map[int]*schema.ToolCall{} + for { + chunk, recvErr := sr.Recv() + if recvErr == io.EOF { + break + } + if recvErr != nil { + return nil, recvErr + } + if chunk == nil { + continue + } + // Streaming tool-call deltas are merged before any content handling so a + // chunk that carries both is processed exactly once. + for _, tc := range chunk.ToolCalls { + idx := -1 + if tc.Index != nil { + idx = *tc.Index + } + existing, ok := pendingCalls[idx] + if !ok { + cp := tc + if cp.Function.Arguments == "" { + cp.Function.Arguments = "" + } + pendingCalls[idx] = &cp + continue + } + existing.Function.Arguments += tc.Function.Arguments + if existing.ID == "" && tc.ID != "" { + existing.ID = tc.ID + } + if existing.Function.Name == "" && tc.Function.Name != "" { + existing.Function.Name = tc.Function.Name + } + } + // Reasoning is streamed first and flagged, so the caller can render it + // separately instead of showing it as part of the answer. + if chunk.ReasoningContent != "" { + reasoning.WriteString(chunk.ReasoningContent) + if onDelta != nil { + if err := onDelta(chunk.ReasoningContent, true); err != nil { + return nil, err + } + } + } + if chunk.Content != "" { + content.WriteString(chunk.Content) + if onDelta != nil { + if err := onDelta(chunk.Content, false); err != nil { + return nil, err + } + } + } + } + resp := &ChatInvokeResponse{ + Content: content.String(), + Thinking: reasoning.String(), + Model: modelName, + Stopped: true, + Usage: usageFromCM(cm), + } + if len(pendingCalls) > 0 { + // Preserve provider-given index order (Python's final_tool_calls.values() + // is insertion-ordered by index) rather than relying on map iteration. + idxs := make([]int, 0, len(pendingCalls)) + for k := range pendingCalls { + idxs = append(idxs, k) + } + sort.Ints(idxs) + merged := make([]schema.ToolCall, 0, len(pendingCalls)) + for _, k := range idxs { + merged = append(merged, *pendingCalls[k]) + } + if calls := nativeToolCalls(merged); len(calls) > 0 { + resp.ToolCalls = calls + } + } + return resp, nil +} + +// resolvedModelInvoker is a ChatInvoker pinned to an already-resolved model +// (driver/modelName/apiConfig). Unlike einoChatInvoker it never consults the +// process-global default model name nor splits a composite llm id — the caller +// (e.g. the Go chat pipeline's harness bridge) resolves the tenant model up +// front via the model provider service. This mirrors Python, where RAGTools +// receives a fully-resolved LLMBundle, and lets the agentic-RAG harness call a +// tenant's actual chat model (which may be a UUID/tenant_model id) instead of +// falling through to a dummy driver. +type resolvedModelInvoker struct { + driver models.ModelDriver + modelName string + apiConfig *models.APIConfig +} + +// NewResolvedInvoker builds a ChatInvoker bound to the given resolved model +// config. modelName may be a bare model name; apiConfig carries the api key and +// base url already resolved for the tenant. +func NewResolvedInvoker(driver models.ModelDriver, modelName string, apiConfig *models.APIConfig) ChatInvoker { + return &resolvedModelInvoker{driver: driver, modelName: modelName, apiConfig: apiConfig} +} + +// resolvedChatWrapper builds the eino wrapper for the pinned model, applying the +// request's sampling config, thinking switch and tool binding. Invoke and Stream +// share it so both send an identical request; only the transport differs. +func (c *resolvedModelInvoker) resolvedChatWrapper(modelName string, req ChatInvokeRequest) (*models.EinoChatModel, *models.ChatModel, error) { + cm := models.NewChatModel(c.driver, &modelName, c.apiConfig) + chatCfg := &models.ChatConfig{ + Temperature: req.Temperature, + TopP: req.TopP, + MaxTokens: req.MaxTokens, + } + switch req.Thinking { + case "enabled": + t := true + chatCfg.Thinking = &t + case "disabled": + f := false + chatCfg.Thinking = &f + } + wrapper := models.NewEinoChatModel(cm, chatCfg) + infos, choice := toolOptions(req.Tools, req.ToolChoice) + if len(infos) > 0 { + withTools, err := wrapper.WithTools(infos) + if err != nil { + return nil, nil, err + } + wrapper = withTools.(*models.EinoChatModel).WithToolChoice(choice) + } + return wrapper, cm, nil +} + +// modelFor returns the model to call: the request's override when set, else the +// model this invoker was pinned to. +func (c *resolvedModelInvoker) modelFor(req ChatInvokeRequest) string { + if req.ModelName != "" { + return req.ModelName + } + return c.modelName +} + +// Invoke satisfies ChatInvoker. +func (c *resolvedModelInvoker) Invoke(ctx context.Context, db *gorm.DB, req ChatInvokeRequest) (*ChatInvokeResponse, error) { + modelName := c.modelFor(req) + wrapper, cm, err := c.resolvedChatWrapper(modelName, req) + if err != nil { + return nil, err + } out, err := wrapper.Generate(ctx, toEinoMessages(req.Messages)) if err != nil { return nil, err } - return &ChatInvokeResponse{ + resp := &ChatInvokeResponse{ Content: out.Content, Thinking: out.ReasoningContent, Model: modelName, Stopped: true, - Tokens: 0, - }, nil + Usage: usageFromCM(cm), + } + if calls := nativeToolCalls(out.ToolCalls); len(calls) > 0 { + resp.ToolCalls = calls + } + return resp, nil +} + +// Stream satisfies chat.StreamingInvoker, the seam +// harness.InvokerSessionModel.StreamComplete asserts when it composes the final +// answer (harness/action_session.go:1504). Without it every agentic answer fell +// back to the one-shot call above and reached the client in a single piece, +// logging "chat invoker … does not support streaming" per request. Mirrors +// Python, where LLMBundle.async_chat_streamly feeds tools.answer_sink while the +// model is still writing. +func (c *resolvedModelInvoker) Stream(ctx context.Context, _ *gorm.DB, req ChatInvokeRequest, onDelta func(delta string, isThink bool) error) (*ChatInvokeResponse, error) { + modelName := c.modelFor(req) + wrapper, cm, err := c.resolvedChatWrapper(modelName, req) + if err != nil { + return nil, err + } + return streamEinoChat(ctx, wrapper, toEinoMessages(req.Messages), cm, modelName, onDelta) } +// The harness asserts chat.StreamingInvoker on the invoker it is handed +// (action_session.go:1504), so a missing Stream silently downgrades the final +// answer to a non-streaming call. Fail at build time instead. +var _ chat.StreamingInvoker = (*resolvedModelInvoker)(nil) + // toEinoMessages converts the LLM component's Message slice to eino's. // // Copies Role, Content, AND UserInputMultiContent (multi-modal parts), @@ -277,6 +628,8 @@ func toEinoMessages(msgs []schema.Message) []*schema.Message { Role: role, Content: m.Content, UserInputMultiContent: cloned, + ToolCalls: m.ToolCalls, + ToolCallID: m.ToolCallID, }) } return out @@ -451,7 +804,7 @@ func (c *LLMComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[strin // The system prompt is already embedded as the first message // in msgs by buildMessagesWithImages; pass "" so fitMessages // does not duplicate it. - fitted, fitErr := fitMessages("", msgs, contentLength) + fitted, fitErr := chat.FitMessages("", msgs, contentLength) if fitErr != "" { return map[string]any{"content": fitErr}, nil } @@ -486,7 +839,7 @@ func (c *LLMComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[strin // Operators who do NOT set MaxRetries (both fields zero) get // the boot retry chain unchanged. The unit tests in // llm_retry_test.go pin both the unwrap behaviour and the - // stacking-prevention contract. + // stacking-prevention hasOverride := p.MaxRetries > 0 || p.DelayAfterError > 0 if hasOverride { maxRetries := p.MaxRetries diff --git a/internal/agent/component/llm_test.go b/internal/agent/component/llm_test.go index c84a5887c1e..cf0401c5433 100644 --- a/internal/agent/component/llm_test.go +++ b/internal/agent/component/llm_test.go @@ -19,7 +19,10 @@ import ( "strings" "testing" + "ragflow/internal/agent/chat" + "ragflow/internal/common" "ragflow/internal/entity" + "ragflow/internal/entity/models" "ragflow/internal/tokenizer" "github.com/cloudwego/eino/schema" @@ -507,191 +510,6 @@ func TestLLM_ResolvesTenantModelID(t *testing.T) { } } -func TestFitMessages_EverythingFits(t *testing.T) { - msgs := []schema.Message{ - {Role: schema.System, Content: "you are helpful"}, - {Role: schema.User, Content: "hello"}, - } - fitted, fitErr := fitMessages("", msgs, 100000) - if fitErr != "" { - t.Fatalf("unexpected fit error: %s", fitErr) - } - if len(fitted) != 2 { - t.Fatalf("got %d messages, want 2", len(fitted)) - } - if fitted[0].Content != "you are helpful" || fitted[1].Content != "hello" { - t.Fatalf("messages modified when they fit: %+v", fitted) - } -} - -func TestFitMessages_PreservesImageOnlyTurn(t *testing.T) { - imgURL := "data:image/png;base64,AAAA" - msgs := []schema.Message{ - {Role: schema.System, Content: "you are helpful"}, - {Role: schema.User, UserInputMultiContent: []schema.MessageInputPart{ - {Type: schema.ChatMessagePartTypeImageURL, Image: &schema.MessageInputImage{ - MessagePartCommon: schema.MessagePartCommon{URL: &imgURL}, - }}, - }}, - } - fitted, fitErr := fitMessages("", msgs, 100000) - if fitErr != "" { - t.Fatalf("unexpected fit error: %s", fitErr) - } - if len(fitted) != 2 { - t.Fatalf("got %d messages, want 2 (image-only turn must be preserved)", len(fitted)) - } - last := fitted[len(fitted)-1] - if len(last.UserInputMultiContent) != 1 || last.UserInputMultiContent[0].Type != schema.ChatMessagePartTypeImageURL { - t.Fatalf("image parts lost after fitting: %+v", last) - } -} - -func TestFitMessages_IncludesSyntheticSystemPrompt(t *testing.T) { - msgs := []schema.Message{{Role: schema.User, Content: "hello"}} - fitted, fitErr := fitMessages("be brief", msgs, 100000) - if fitErr != "" { - t.Fatalf("unexpected fit error: %s", fitErr) - } - if len(fitted) != 2 { - t.Fatalf("got %d messages, want 2 (synthetic system prompt + user)", len(fitted)) - } - if fitted[0].Role != schema.System || fitted[0].Content != "be brief" { - t.Fatalf("synthetic system prompt not preserved: %+v", fitted[0]) - } -} - -func TestFitMessages_DropsMiddleWhenOverBudget(t *testing.T) { - long := strings.Repeat("x ", 5000) - msgs := []schema.Message{ - {Role: schema.System, Content: long}, - {Role: schema.User, Content: "middle"}, - {Role: schema.User, Content: "last"}, - } - fitted, fitErr := fitMessages("", msgs, 1000) - if fitErr != "" { - t.Fatalf("unexpected fit error: %s", fitErr) - } - if len(fitted) != 2 { - t.Fatalf("got %d messages, want 2 (middle dropped, system + last user kept)", len(fitted)) - } - if fitted[0].Role != schema.System || fitted[1].Role != schema.User { - t.Fatalf("unexpected roles: %+v", fitted) - } - if !strings.Contains(fitted[1].Content, "last") { - t.Fatalf("last user message not preserved: %+v", fitted[1]) - } -} - -// TestFitMessages_SystemKeptButEmptied locks the write-back for a system -// message that the fitter keeps but trims to empty (the final user turn alone -// fills the budget): the fitted (empty) content must be written back instead -// of the original, so the conversation stays within the budget. -func TestFitMessages_SystemKeptButEmptied(t *testing.T) { - origSys := strings.Repeat("s ", 3000) // dominates (>80% of tokens) - msgs := []schema.Message{ - {Role: schema.System, Content: origSys}, - {Role: schema.User, Content: strings.Repeat("u ", 600)}, // alone exceeds the budget - } - fitted, fitErr := fitMessages("", msgs, 500) - if fitErr != "" { - t.Fatalf("unexpected fit error: %s", fitErr) - } - if len(fitted) != 2 { - t.Fatalf("got %d messages, want 2 (both kept)", len(fitted)) - } - if fitted[0].Role != schema.System || fitted[0].Content != "" { - t.Fatalf("system should be kept but trimmed to empty, got %+v", fitted[0]) - } - if fitted[1].Role != schema.User || fitted[1].Content == origSys { - t.Fatalf("user turn wrong after fitting: %+v", fitted[1]) - } - total := tokenizer.NumTokensFromString(fitted[0].Content) + tokenizer.NumTokensFromString(fitted[1].Content) - if total > 500 { - t.Fatalf("fitted total %d exceeds budget 500", total) - } -} - -// TestFitMessages_FoldsMultipleTextParts verifies that every non-empty text -// part of a multi-modal message participates in the token budget: the parts -// are folded into a single fitted text on the first text part and additional -// text parts are removed, so no text escapes the budget after reconstruction. -func TestFitMessages_FoldsMultipleTextParts(t *testing.T) { - long1 := strings.Repeat("a ", 3000) - long2 := strings.Repeat("b ", 3000) - imgURL := "data:image/png;base64,AAAA" - msgs := []schema.Message{ - {Role: schema.System, Content: "sys"}, - {Role: schema.User, UserInputMultiContent: []schema.MessageInputPart{ - {Type: schema.ChatMessagePartTypeText, Text: long1}, - {Type: schema.ChatMessagePartTypeImageURL, Image: &schema.MessageInputImage{ - MessagePartCommon: schema.MessagePartCommon{URL: &imgURL}, - }}, - {Type: schema.ChatMessagePartTypeText, Text: long2}, - }}, - } - fitted, fitErr := fitMessages("", msgs, 2000) - if fitErr != "" { - t.Fatalf("unexpected fit error: %s", fitErr) - } - if len(fitted) != 2 { - t.Fatalf("got %d messages, want 2", len(fitted)) - } - last := fitted[len(fitted)-1] - textParts := 0 - imageParts := 0 - for _, part := range last.UserInputMultiContent { - switch part.Type { - case schema.ChatMessagePartTypeText: - textParts++ - case schema.ChatMessagePartTypeImageURL: - imageParts++ - } - } - if textParts != 1 { - t.Fatalf("got %d text parts, want 1 (folded): %+v", textParts, last.UserInputMultiContent) - } - if imageParts != 1 { - t.Fatalf("image part lost after trimming: %+v", last.UserInputMultiContent) - } - if total := tokenizer.NumTokensFromString(last.UserInputMultiContent[0].Text); total > 2000 { - t.Fatalf("fitted text totals %d tokens, exceeds budget 2000", total) - } -} - -// TestFitMessages_ImageOnlyLastTurnOverBudget locks the over-budget path where -// an image-only turn is the last non-system message (ll2 = 0 tokens): the -// fitter keeps it, gives the whole budget to the system messages, and the -// image-only turn must survive reconstruction untouched. -func TestFitMessages_ImageOnlyLastTurnOverBudget(t *testing.T) { - imgURL := "data:image/png;base64,AAAA" - msgs := []schema.Message{ - {Role: schema.System, Content: strings.Repeat("s ", 3000)}, // dominates (>80% of tokens) - {Role: schema.User, UserInputMultiContent: []schema.MessageInputPart{ - {Type: schema.ChatMessagePartTypeImageURL, Image: &schema.MessageInputImage{ - MessagePartCommon: schema.MessagePartCommon{URL: &imgURL}, - }}, - }}, - } - fitted, fitErr := fitMessages("", msgs, 500) - if fitErr != "" { - t.Fatalf("unexpected fit error: %s", fitErr) - } - if len(fitted) != 2 { - t.Fatalf("got %d messages, want 2 (system + image-only turn)", len(fitted)) - } - if fitted[0].Role != schema.System || fitted[0].Content == msgs[0].Content { - t.Fatalf("system should be trimmed to the budget: %+v", fitted[0]) - } - if total := tokenizer.NumTokensFromString(fitted[0].Content); total > 500 { - t.Fatalf("system exceeds budget after fit: %d tokens", total) - } - last := fitted[len(fitted)-1] - if last.Role != schema.User || len(last.UserInputMultiContent) != 1 || last.UserInputMultiContent[0].Type != schema.ChatMessagePartTypeImageURL { - t.Fatalf("image-only turn lost or modified after over-budget fitting: %+v", last) - } -} - // TestLLM_Invoke_MaxTokensStillOutputCapAndNotBudget pins the core semantics // of the content_length change: the canvas max_tokens must still reach the // invoker as the generation cap, but must NOT be the message-fitting budget. @@ -822,3 +640,59 @@ func TestCleanFormattedAnswer(t *testing.T) { }) } } + +// streamingStubDriver is a ModelDriver whose only real behaviour is the stream +// the resolved invoker must forward. Everything else is inherited from +// models.DummyModel ("not implemented"), which the test never calls. +type streamingStubDriver struct { + models.DummyModel +} + +func (d *streamingStubDriver) ChatStreamlyWithSender(_ context.Context, _ string, _ []models.Message, _ *models.APIConfig, _ *models.ChatConfig, _ *common.ModelUsage, sender func(*string, *string) error) error { + think, answer := "thinking…", "the answer" + if err := sender(nil, &think); err != nil { + return err + } + return sender(&answer, nil) +} + +// TestResolvedModelInvokerStreams pins the seam the harness asserts: +// harness.InvokerSessionModel.StreamComplete type-asserts chat.StreamingInvoker +// (harness/action_session.go:1504), so a resolved invoker without Stream +// silently downgraded every agentic answer to the one-shot call — the log line +// "chat invoker *component.resolvedModelInvoker does not support streaming" — +// and the client received the whole answer in one piece. +func TestResolvedModelInvokerStreams(t *testing.T) { + invoker := NewResolvedInvoker(&streamingStubDriver{}, "stub-model", &models.APIConfig{}) + streamer, ok := invoker.(chat.StreamingInvoker) + if !ok { + t.Fatalf("resolved invoker %T must implement chat.StreamingInvoker", invoker) + } + + var answer, think strings.Builder + resp, err := streamer.Stream(t.Context(), nil, chat.Request{ + Messages: []schema.Message{{Role: schema.User, Content: "q"}}, + }, func(delta string, isThink bool) error { + if isThink { + think.WriteString(delta) + return nil + } + answer.WriteString(delta) + return nil + }) + if err != nil { + t.Fatalf("Stream: %v", err) + } + // Reasoning rides the think channel, content the answer channel — the caller + // frames each separately, so a mixed-up flag would put reasoning in the answer. + if think.String() != "thinking…" { + t.Errorf("think deltas = %q, want the reasoning piece", think.String()) + } + if answer.String() != "the answer" { + t.Errorf("answer deltas = %q, want the content piece", answer.String()) + } + // The assembled reply matches what Invoke would have returned. + if resp.Content != "the answer" || resp.Thinking != "thinking…" { + t.Errorf("assembled reply = (%q, %q), want (the answer, thinking…)", resp.Content, resp.Thinking) + } +} diff --git a/internal/agent/component/prompts/citation.go b/internal/agent/component/prompts/citation.go index 229ab366035..b65e57c9dc0 100644 --- a/internal/agent/component/prompts/citation.go +++ b/internal/agent/component/prompts/citation.go @@ -22,76 +22,22 @@ package prompts import ( "fmt" "strings" + + ragprompts "ragflow/internal/rag/prompts" ) -// citationPromptText is the citation-instruction template, mirrored -// from rag/prompts/citation_prompt.md. +// CitationPrompt returns the citation-instruction text. The LLM +// component appends it to the system prompt when LLMParam.Cite is true. // -// The full Markdown (123 lines) is preserved so the LLM receives the -// same instruction set as the Python engine. Trim or extend here only -// after a corresponding change in citation_prompt.md. +// The text lives once, in internal/rag/prompts/citation_prompt.md (a copy of +// rag/prompts/citation_prompt.md), and is delegated to here so the two Go +// columns cannot drift apart again. // // Format: [ID:N] inline citation; max 4 per sentence; placed at // sentence end before punctuation; forbidden format "[ID:0, ID:5, ...]" // — must be space-separated as "[ID:0][ID:5]". -const citationPromptText = `Based on the provided document or chat history, add citations to the input text using the format specified later. - -# Citation Requirements: - -## Technical Rules: -- Use format: [ID:i] or [ID:i] [ID:j] for multiple sources -- Place citations at the end of sentences, before punctuation -- Maximum 4 citations per sentence -- DO NOT cite content not from -- DO NOT modify whitespace or original text -- STRICTLY prohibit non-standard formatting (~~, etc.) -- For RTL languages (Arabic, Hebrew, Persian): Place citations at the logical end of sentences (same position as LTR). The frontend handles bidirectional rendering automatically. - -## What MUST Be Cited: -1. **Quantitative data**: Numbers, percentages, statistics, measurements -2. **Temporal claims**: Dates, timeframes, sequences of events -3. **Causal relationships**: Claims about cause and effect -4. **Comparative statements**: Rankings, comparisons, superlatives -5. **Technical definitions**: Specialized terms, concepts, methodologies -6. **Direct attributions**: What someone said, did, or believes -7. **Predictions/forecasts**: Future projections, trend analyses -8. **Controversial claims**: Disputed facts, minority opinions - -## What Should NOT Be Cited: -- Common knowledge (e.g., "The sun rises in the east") -- Transitional phrases -- General introductions -- Your own analysis or synthesis (unless directly from source) - -## Example: - -ID: 45 -└── Content: The global smartphone market grew by 7.8% in Q3 2024. - -ID: 46 -└── Content: 5G adoption reached 1.5 billion users worldwide by October 2024. - - -USER: How is the smartphone market performing? - -ASSISTANT: -The smartphone industry is showing strong recovery. The global smartphone market grew by 7.8% in Q3 2024 [ID:45]. 5G adoption reached 1.5 billion users worldwide by October 2024 [ID:46]. - -REMEMBER: -- Cite FACTS, not opinions or transitions -- Each citation supports the ENTIRE sentence -- Place citations at sentence end, before punctuation -- Format like "[ID:0, ID:5, ...]" is FORBIDDEN. Must be "[ID:0][ID:5]..." -` - -// CitationPrompt returns the citation-instruction text. The LLM -// component appends it to the system prompt when LLMParam.Cite is true. -// -// Future: a post-stream grounding enhancement can additionally -// render a ... block of retrieval chunks into -// the system message before this prompt. func CitationPrompt() string { - return citationPromptText + return ragprompts.CitationPrompt("") } // citationPlusTemplate is the post-stream citation-grounding template, diff --git a/internal/agent/component/userfillup.go b/internal/agent/component/userfillup.go index 7ef3d5bafeb..f206248c759 100644 --- a/internal/agent/component/userfillup.go +++ b/internal/agent/component/userfillup.go @@ -86,7 +86,7 @@ func (p *userFillUpParam) Update(conf map[string]any) error { // Check performs parameter validation. UserFillUp has no required // fields — any config is accepted and degrades gracefully on missing -// template data. The method is kept to satisfy the ParamBase contract. +// template data. The method is kept to satisfy the ParamBase func (p *userFillUpParam) Check() error { return nil } // AsDict returns the param as a plain map for serialization / debug. diff --git a/internal/agent/component/variable_aggregator.go b/internal/agent/component/variable_aggregator.go index 263529eda5b..40b824593f3 100644 --- a/internal/agent/component/variable_aggregator.go +++ b/internal/agent/component/variable_aggregator.go @@ -47,7 +47,7 @@ type variableAggregatorParam struct { } // Update copies a fresh param map into the receiver. Mirrors the Python -// ComponentParamBase contract. +// ComponentParamBase // // `groups` may arrive as either []any (engine-decoded from JSON) or // []map[string]any (test/direct construction); both shapes are accepted diff --git a/internal/agent/dsl/normalize.go b/internal/agent/dsl/normalize.go index 0579d36a134..9f6e1847904 100644 --- a/internal/agent/dsl/normalize.go +++ b/internal/agent/dsl/normalize.go @@ -442,7 +442,7 @@ func toStringSlice(v any) []string { // Without the deep copy, a caller that reuses the original // decoded DSL map (e.g. for re-validation or diffing) would // observe side effects that contradict the documented -// "never mutates its input" contract. +// "never mutates its input" // // Primitives and non-mutable values (string, number, bool) are // shared by reference; only the maps and slices that the diff --git a/internal/agent/dsl/normalize_test.go b/internal/agent/dsl/normalize_test.go index 315b93e7c17..424cb595c89 100644 --- a/internal/agent/dsl/normalize_test.go +++ b/internal/agent/dsl/normalize_test.go @@ -530,7 +530,7 @@ func TestNormalizeForCanvas_RepairsLeakedParallelShape(t *testing.T) { } // TestNormalize_DoesNotMutateInput pins the documented -// "never mutates its input" contract. The original DSL map's +// "never mutates its input" The original DSL map's // graph.edges[*].sourceHandle / targetHandle, components // entries, and components[*].obj.component_name must all be // unchanged after NormalizeForCanvas returns. diff --git a/internal/agent/harness/agentic.go b/internal/agent/harness/agentic.go deleted file mode 100644 index 01ea4b009b3..00000000000 --- a/internal/agent/harness/agentic.go +++ /dev/null @@ -1,301 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "fmt" - "strings" - "sync" - - "gorm.io/gorm" -) - -// AgenticResearch is the high/ultra two-level loop (mirrors Python -// orchestrator/agentic.py agentic_research): the orchestrator assigns claims, -// the research agent researches each in parallel batches, and the decision -// ladder decides sufficiency each round. -// -// It drives the SAME pipeline (shared Kbinfos, compilation gating, doc routing) -// as the linear Run flow, so high/ultra is a strict superset of medium, not a -// parallel implementation. -func AgenticResearch(ctx context.Context, db *gorm.DB, pipeline *Pipeline, question string, claims []*ClaimTarget, mode ExecutionStrategy) OrchestratorResult { - kbinfos := pipeline.kbinfos - - // Stagnation guard: stop early when the score stops improving. - const stagnationCycles = 2 - const stagnationGain = 0.05 - prevScore := -1.0 - - var pendingFollowups []string - - for cycle := 0; cycle < mode.MaxOrchestratorCycles; cycle++ { - unverified := unverifiedClaims(claims) - - if len(unverified) > 0 { - // Consume follow-ups ONCE per round, shared by every claim in the batch. - followups := pendingFollowups - pendingFollowups = nil - - // Research in batches of MaxParallelAgents. - batchSize := mode.MaxParallelAgents - if batchSize < 1 { - batchSize = 1 - } - for i := 0; i < len(unverified); i += batchSize { - end := i + batchSize - if end > len(unverified) { - end = len(unverified) - } - batch := unverified[i:end] - results := researchBatch(ctx, db, pipeline, batch, mode, followups) - for j, c := range batch { - r := results[j] - c.IsVerified = r.IsVerified - c.Confidence = r.Confidence - c.AgentResult = &r - - // Ultra: dynamic claim expansion from discovered_claims. - if mode.AllowsDynamicClaims { - for _, dc := range r.DiscoveredClaims { - if dc == "" || claimDescExists(claims, dc) { - continue - } - claims = append(claims, &ClaimTarget{ - ClaimID: fmt.Sprintf("c_dyn_%d", len(claims)), - Description: dc, - }) - } - } - } - } - } - - // ── Step A.5: note the discovered entity so graph_explore is eligible ── - // (mirrors agentic.py ctx.note_entity(_discovered_entity(tools))). Gates - // graph_explore via HasDiscoveredEntity on the pipeline. - if ent := discoveredEntity(kbinfos.Chunks); ent != "" { - pipeline.noteEntity(ent) - } - - // ── Step B: sufficiency check ── - allChunks := map[int]map[string]interface{}{} - for i, c := range kbinfos.Chunks { - allChunks[i] = c - } - var agentResults []AgentResult - for _, c := range claims { - if c.AgentResult != nil { - agentResults = append(agentResults, *c.AgentResult) - } - } - var crossResults []ClaimCrossCheckResult - for _, r := range agentResults { - crossResults = append(crossResults, CrossCheckClaim(&r, allChunks)) - } - - claimValues := make([]ClaimTarget, 0, len(claims)) - for _, c := range claims { - if c != nil { - claimValues = append(claimValues, *c) - } - } - verdict := ComputeFusionScore(agentResults, crossResults, mode, question, claimValues, allChunks) - - // LLM Sufficient Context AutoRater (primary judge), invoked every round. - var citedIDs []int - for _, r := range agentResults { - citedIDs = append(citedIDs, r.EvidenceIDs...) - } - boost := LLMSufficiencyBoost(ctx, db, question, &verdict, kbinfos, citedIDs) - if boost != nil && len(boost.Followups) > 0 { - pendingFollowups = boost.Followups - } - - // LLM groundedness review (draft review): ungrounded claims merge into - // hard_violations. - var reports []ClaimReport - for _, r := range agentResults { - if r.Report != "" { - reports = append(reports, ClaimReport{ClaimID: r.ClaimID, Report: r.Report}) - } - } - grounded := LLMGroundedVerify(ctx, db, question, reports, kbinfos, citedIDs) - validIDs := map[string]bool{} - for _, r := range agentResults { - validIDs[r.ClaimID] = true - } - hvSet := map[string]bool{} - for _, id := range verdict.HardViolations { - hvSet[id] = true - } - for cid, g := range grounded { - if validIDs[cid] && (!g.Grounded || len(g.Ungrounded) > 0) { - hvSet[cid] = true - } - } - verdict.HardViolations = sortedKeys(hvSet) - - action, shouldContinue, _ := RouteSufficiencyVerdict(verdict, mode.Label, cycle, mode.MaxOrchestratorCycles, boost) - - // Stagnation guard: override CONTINUE with a partial answer when the - // score has not meaningfully improved. - if shouldContinue && (verdict.Status == "INSUFFICIENT" || verdict.Status == "USEFUL_BUT_INCOMPLETE") { - if prevScore >= 0 && cycle >= stagnationCycles && verdict.Score-prevScore < stagnationGain { - action = "ANSWER_PARTIAL" - shouldContinue = false - } else { - prevScore = verdict.Score - } - } - - switch action { - case "ANSWER": - finalizeAgentResults(kbinfos, claims) - return OrchestratorResult{Verdict: &verdict, Kbinfos: kbinfos} - case "ANSWER_PARTIAL": - finalizeAgentResults(kbinfos, claims) - return OrchestratorResult{Verdict: &verdict, PartialAnswer: true, Kbinfos: kbinfos} - case "ABSTAIN": - kbinfos.Chunks = nil - return OrchestratorResult{Verdict: &verdict, Abstain: true, Kbinfos: kbinfos} - case "FALLBACK_LLM": - finalizeAgentResults(kbinfos, claims) - return OrchestratorResult{Verdict: &verdict, PartialAnswer: true, ForceLLM: true, Kbinfos: kbinfos} - } - } - - // Max cycles reached. - finalizeAgentResults(kbinfos, claims) - return OrchestratorResult{Verdict: nil, PartialAnswer: true, Kbinfos: kbinfos} -} - -// discoveredEntity picks a salient discovered name from the gathered evidence -// (mirrors Python _discovered_entity): prefer an explicit entity/keyword tag on a -// chunk, fall back to a source document name. Used only to gate graph_explore. -func discoveredEntity(chunks []map[string]interface{}) string { - for _, c := range chunks { - for _, key := range []string{"entities_kwd", "important_kwd"} { - switch val := c[key].(type) { - case []string: - if len(val) > 0 { - if first := strings.TrimSpace(val[0]); first != "" { - return first - } - } - case []interface{}: - if len(val) > 0 { - if s, ok := val[0].(string); ok { - if first := strings.TrimSpace(s); first != "" { - return first - } - } - } - case string: - if s := strings.TrimSpace(val); s != "" { - if fields := strings.Fields(s); len(fields) > 0 { - return fields[0] - } - } - } - } - } - for _, c := range chunks { - if name := strings.TrimSpace(chunkDoc(c)); name != "" { - return name - } - } - return "" -} - -// researchBatch runs ResearchAgentLoop for each claim in parallel. -func researchBatch(ctx context.Context, db *gorm.DB, pipeline *Pipeline, batch []*ClaimTarget, mode ExecutionStrategy, followups []string) []AgentResult { - results := make([]AgentResult, len(batch)) - var wg sync.WaitGroup - for i, c := range batch { - wg.Add(1) - go func(idx int, claim *ClaimTarget) { - defer wg.Done() - results[idx] = ResearchAgentLoop(ctx, db, pipeline, *claim, mode, followups) - }(i, c) - } - wg.Wait() - return results -} - -func unverifiedClaims(claims []*ClaimTarget) []*ClaimTarget { - var out []*ClaimTarget - for _, c := range claims { - if c != nil && !c.IsVerified { - out = append(out, c) - } - } - return out -} - -func claimDescExists(claims []*ClaimTarget, desc string) bool { - for _, c := range claims { - if c != nil && c.Description == desc { - return true - } - } - return false -} - -// finalizeAgentResults mirrors Python _finalize + _merge_agent_results: build the -// pre_summary and trim evidence to only cited chunks. -func finalizeAgentResults(kbinfos *Kbinfos, claims []*ClaimTarget) { - var combined []string - seenEvidence := map[int]bool{} - for _, c := range claims { - if c == nil || c.AgentResult == nil { - continue - } - if c.AgentResult.Report != "" { - status := "❌" - if c.IsVerified { - status = "✅" - } - report := c.AgentResult.Report - if len(report) > 500 { - report = report[:500] - } - combined = append(combined, fmt.Sprintf("【%s】%s %s", c.ClaimID, status, report)) - } - for _, eid := range c.AgentResult.EvidenceIDs { - seenEvidence[eid] = true - } - } - if len(combined) > 0 { - kbinfos.PreSummary = strings.Join(combined, "\n\n") - } - - // Trim evidence to cited chunks only (preserve order, never empty). - if len(seenEvidence) > 0 && len(seenEvidence) < len(kbinfos.Chunks) { - keep := make([]int, 0, len(seenEvidence)) - for i := range kbinfos.Chunks { - if seenEvidence[i] { - keep = append(keep, i) - } - } - newChunks := make([]map[string]interface{}, 0, len(keep)) - for _, i := range keep { - newChunks = append(newChunks, kbinfos.Chunks[i]) - } - kbinfos.Chunks = newChunks - } -} diff --git a/internal/agent/harness/agentic_rag.go b/internal/agent/harness/agentic_rag.go deleted file mode 100644 index b449cdefcd4..00000000000 --- a/internal/agent/harness/agentic_rag.go +++ /dev/null @@ -1,120 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "log" - "strings" - - "gorm.io/gorm" -) - -// AgenticState carries the shared state across the agentic-RAG graph nodes. -type AgenticState struct { - Question string - Keywords string - SystemPrompt string - Route RouteDecision - SeedChunks []string - Plan WorkflowPlan - Kbinfos *Kbinfos - PartialAnswer bool - Abstain bool - EmptyResult bool - FinalAnswer string - FormalizeError string -} - -// RunAgenticRAG drives the agentic-search graph: route → pre_search → planner → -// orchestrator → formalize_answer. Mirrors build_agentic_graph's linear flow. -// -// - low (direct_search): one hybrid search → answer. -// - medium+ (decompose_and_search / agentic_research / deep_research): -// pre_search grounds the planner, then decompose-and-search runs until a -// sufficiency verdict stops it. -// -// RunAgenticRAG drives the agentic-search graph. It computes the route itself -// and delegates to RunAgenticRAGWithRoute so production runners that need a -// route-aware search strategy (e.g. prefer wiki_query on a wiki suggestion) can -// reuse the same flow with a pre-computed route. -func RunAgenticRAG(ctx context.Context, db *gorm.DB, question, keywords, modeLabel string, search SearchFn, systemPrompt string) AnswerResult { - return RunAgenticRAGWithRoute(ctx, db, question, keywords, modeLabel, RouteNode(ctx, db, question, modeLabel), search, systemPrompt) -} - -// RunAgenticRAGWithRoute is the route-aware core of RunAgenticRAG. It performs -// pre_search → planner → orchestrator → formalize_answer with the given route. -func RunAgenticRAGWithRoute(ctx context.Context, db *gorm.DB, question, keywords, modeLabel string, route RouteDecision, search SearchFn, systemPrompt string) AnswerResult { - state := &AgenticState{ - Question: strings.TrimSpace(question), - Keywords: keywords, - SystemPrompt: strings.TrimSpace(systemPrompt), - Kbinfos: &Kbinfos{}, - } - if state.Question == "" { - return AnswerResult{FinalAnswer: emptyResultMessage, Empty: true} - } - - // ── route (pre-computed by the caller) ── - state.Route = route - - // ── pre_search (decomposition modes only) ── - if state.Route.RequiresDecomposition { - chunks, aggs := search(ctx, state.Question, state.Keywords) - state.SeedChunks = extractChunkTexts(chunks) - state.Kbinfos.Merge(chunks, aggs) - } - - // ── planner ── - state.Plan = PlannerNode(ctx, db, state.Route, state.SeedChunks) - - // ── orchestrator ── - var orch OrchestratorResult - if state.Route.RequiresDecomposition { - claims := make([]*ClaimTarget, len(state.Plan.Claims)) - for i := range state.Plan.Claims { - claims[i] = &state.Plan.Claims[i] - } - orch = DecomposeAndSearch(ctx, search, state.Question, state.Keywords, claims, modeLabel, state.Kbinfos) - } else { - orch = DirectSearch(ctx, search, state.Question, state.Keywords, state.Kbinfos) - } - state.PartialAnswer = orch.PartialAnswer - state.Abstain = orch.Abstain - state.EmptyResult = orch.EmptyResult - if orch.Kbinfos != nil { - state.Kbinfos = orch.Kbinfos - } - - // ── formalize_answer ── - res := FormalizeAnswer(ctx, db, state.Question, state.Kbinfos, state.PartialAnswer, state.Abstain, state.EmptyResult, orch.Caveat, orch.ForceLLM, state.SystemPrompt) - // Log only the question length, never its content, to avoid persisting user - // input in logs. - log.Printf("agentic_rag: finished (qlen=%d, strategy=%s, chunks=%d, partial=%v, abstain=%v)", - len(state.Question), state.Route.ExecutionStrategy, len(state.Kbinfos.Chunks), state.PartialAnswer, state.Abstain) - return res -} - -func extractChunkTexts(chunks []map[string]interface{}) []string { - out := make([]string, 0, len(chunks)) - for _, c := range chunks { - if t := chunkText(c); t != "" { - out = append(out, t) - } - } - return out -} diff --git a/internal/agent/harness/agentic_test.go b/internal/agent/harness/agentic_test.go deleted file mode 100644 index 8db254804cd..00000000000 --- a/internal/agent/harness/agentic_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// -// 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. -// - -package harness - -import "testing" - -// TestDiscoveredEntity_EntityTag asserts the entity/keyword tag takes priority. -func TestDiscoveredEntity_EntityTag(t *testing.T) { - chunks := []map[string]interface{}{ - {"entities_kwd": []string{"Paris", "France"}, "docnm_kwd": "Document A"}, - } - if got := discoveredEntity(chunks); got != "Paris" { - t.Errorf("discoveredEntity = %q, want Paris", got) - } -} - -// TestDiscoveredEntity_ImportantKwdString asserts a string important_kwd returns -// its first word. -func TestDiscoveredEntity_ImportantKwdString(t *testing.T) { - chunks := []map[string]interface{}{ - {"important_kwd": "Quantum Computing"}, - } - if got := discoveredEntity(chunks); got != "Quantum" { - t.Errorf("discoveredEntity = %q, want Quantum", got) - } -} - -// TestDiscoveredEntity_DocNameFallback asserts the doc name fallback when no -// entity/keyword tag is present. -func TestDiscoveredEntity_DocNameFallback(t *testing.T) { - chunks := []map[string]interface{}{ - {"content_with_weight": "some text", "docnm_kwd": "Annual Report 2023"}, - } - if got := discoveredEntity(chunks); got != "Annual Report 2023" { - t.Errorf("discoveredEntity = %q, want 'Annual Report 2023'", got) - } -} - -// TestDiscoveredEntity_Empty asserts empty evidence yields empty. -func TestDiscoveredEntity_Empty(t *testing.T) { - if got := discoveredEntity(nil); got != "" { - t.Errorf("discoveredEntity(nil) = %q, want empty", got) - } - if got := discoveredEntity([]map[string]interface{}{{"content_with_weight": "x"}}); got != "" { - t.Errorf("discoveredEntity(no name) = %q, want empty", got) - } -} - -// TestNoteEntity asserts empty names never clear a prior discovery. -func TestNoteEntity(t *testing.T) { - p := &Pipeline{} - if p.HasDiscoveredEntity() { - t.Fatal("fresh pipeline must have no discovered entity") - } - p.noteEntity("Paris") - if !p.HasDiscoveredEntity() { - t.Fatal("noteEntity(Paris) must set discovered entity") - } - p.noteEntity("") // fruitless round must not clear - if !p.HasDiscoveredEntity() { - t.Error("empty noteEntity must not clear prior discovery") - } - p.noteEntity("France") - if p.lastEntity != "France" { - t.Errorf("lastEntity = %q, want France", p.lastEntity) - } -} diff --git a/internal/agent/harness/answer.go b/internal/agent/harness/answer.go deleted file mode 100644 index 8663de7bb00..00000000000 --- a/internal/agent/harness/answer.go +++ /dev/null @@ -1,150 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "fmt" - "strings" - - "github.com/cloudwego/eino/schema" - - "gorm.io/gorm" - "ragflow/internal/agent/chat" -) - -// FINAL_ANSWER_SYSTEM mirrors Python report_prompt.FINAL_ANSWER_SYSTEM. -const finalAnswerSystem = `You are a smart agent. Answer the user's question using ONLY the evidence provided below. Do not invent facts: if the evidence cannot support a claim, say so plainly instead of guessing. - -# Citation rules -{cite_rules} - -# Language -Answer in the SAME language as the question. Translate retrieved evidence into that language as part of composing the answer; only verbatim quoted snippets may stay in their source language. - -# Fallback -If the evidence does not answer the question, reply with a clear statement that you don't have enough information based on the available sources (in the user's language). -` - -const partialAnswerPreamble = "Note: the following answer is based on partial information and may be incomplete." - -const defaultCiteRules = "Cite passages with their source documents where available." - -const ( - abstainMessage = "I cannot answer this question based on the available information." - emptyResultMessage = "I don't have enough information based on the available sources." -) - -// AnswerResult mirrors the formalize_answer node output. -type AnswerResult struct { - FinalAnswer string - Abstained bool - Empty bool -} - -// FormalizeAnswer generates the final answer from the gathered kbinfos. Mirrors -// Python's formalize_answer node: abstain/empty short-circuits, otherwise builds -// system+user and calls the chat invoker. -// -// forceLLM forces the direct-LLM path even when there is no evidence: used by the -// FALLBACK_LLM verdict (FallbackToDirectLLM), where the mode is unanswerable but -// we still want the model to attempt an answer or plainly state it cannot — not -// a canned "no evidence" string. Mirrors Python, which only short-circuits on -// empty evidence when an explicit empty_response is configured. -// systemPrompt, when non-empty, is prepended to the final-answer system prompt -// so the agentic graph honors a configured dialog system prompt (mirrors Python -// RAGTools.system_prompt + formalize_answer). -func FormalizeAnswer(ctx context.Context, db *gorm.DB, question string, kb *Kbinfos, partial, abstain, empty bool, caveat string, forceLLM bool, systemPrompt string) AnswerResult { - if abstain { - return AnswerResult{FinalAnswer: abstainMessage, Abstained: true} - } - if !forceLLM && (empty || kb == nil || len(kb.Chunks) == 0) { - return AnswerResult{FinalAnswer: emptyResultMessage, Empty: true} - } - - var b strings.Builder - b.WriteString("Question:\n" + question + "\n") - // Research summary (merged claim reports from the high/ultra loop) precedes - // the raw evidence, mirroring Python formalize_answer. - if kb.PreSummary != "" { - b.WriteString("\nResearch Summary:\n" + kb.PreSummary + "\n") - } - if partial { - preamble := partialAnswerPreamble - if caveat != "" { - preamble = partialAnswerPreamble + " " + caveat - } - b.WriteString(preamble + "\n") - } - b.WriteString("\nEvidence:\n") - for i, c := range kb.Chunks { - text := chunkText(c) - doc := chunkDoc(c) - if text == "" { - continue - } - b.WriteString(fmt.Sprintf("[%d] %s", i+1, text)) - if doc != "" { - b.WriteString(fmt.Sprintf(" (source: %s)", doc)) - } - b.WriteString("\n") - } - - system := strings.ReplaceAll(finalAnswerSystem, "{cite_rules}", defaultCiteRules) - if strings.TrimSpace(systemPrompt) != "" { - system = strings.TrimSpace(systemPrompt) + "\n\n" + system - } - inv := chat.GetDefaultInvoker() - if inv == nil { - return AnswerResult{FinalAnswer: "I'm sorry, the chat invoker is not configured."} - } - resp, err := inv.Invoke(ctx, db, chat.Request{ - Messages: []schema.Message{ - {Role: schema.System, Content: system}, - {Role: schema.User, Content: b.String()}, - }, - }) - if err != nil { - return AnswerResult{FinalAnswer: "I'm sorry, I encountered an error while composing the answer."} - } - return AnswerResult{FinalAnswer: resp.Content} -} - -func chunkText(c map[string]interface{}) string { - if t, ok := c["content_with_weight"].(string); ok && t != "" { - return t - } - if t, ok := c["content"].(string); ok { - return t - } - // "text" is the fallback used by the AutoRater evidence renderer (Python - // _evidence_md: content_with_weight or text). - if t, ok := c["text"].(string); ok { - return t - } - return "" -} - -func chunkDoc(c map[string]interface{}) string { - if d, ok := c["docnm_kwd"].(string); ok { - return d - } - if d, ok := c["doc_id"].(string); ok { - return d - } - return "" -} diff --git a/internal/agent/harness/answer_test.go b/internal/agent/harness/answer_test.go deleted file mode 100644 index 1b5773296ef..00000000000 --- a/internal/agent/harness/answer_test.go +++ /dev/null @@ -1,130 +0,0 @@ -package harness - -import ( - "context" - "strings" - "testing" - - "github.com/cloudwego/eino/schema" - "gorm.io/gorm" - - "ragflow/internal/agent/component" -) - -// TestFormalizeAnswer_Abstain asserts abstain short-circuits to the abstain -// message without calling the model. -func TestFormalizeAnswer_Abstain(t *testing.T) { - res := FormalizeAnswer(t.Context(), nil, "Q", &Kbinfos{}, false, true, false, "", false, "") - if !res.Abstained || res.FinalAnswer != abstainMessage { - t.Errorf("abstain result = %+v, want abstain message", res) - } -} - -// TestFormalizeAnswer_Empty asserts empty chunks short-circuit to the empty -// message. -func TestFormalizeAnswer_Empty(t *testing.T) { - res := FormalizeAnswer(t.Context(), nil, "Q", &Kbinfos{}, false, false, false, "", false, "") - if !res.Empty || res.FinalAnswer != emptyResultMessage { - t.Errorf("empty result = %+v, want empty message", res) - } -} - -// TestFormalizeAnswer_Generates asserts a chat invoker is used to compose the -// final answer from the evidence. -func TestFormalizeAnswer_Generates(t *testing.T) { - installChat(t, "here is the final answer") - kb := &Kbinfos{Chunks: []map[string]interface{}{{"content_with_weight": "evidence alpha"}}} - res := FormalizeAnswer(t.Context(), nil, "What is X?", kb, false, false, false, "", false, "") - if res.FinalAnswer != "here is the final answer" { - t.Errorf("final answer = %q, want chat output", res.FinalAnswer) - } -} - -// TestFormalizeAnswer_PartialPreamble asserts the partial preamble is included -// when partial=true. -func TestFormalizeAnswer_PartialPreamble(t *testing.T) { - installChat(t, "partial ans") - kb := &Kbinfos{Chunks: []map[string]interface{}{{"content_with_weight": "evidence"}}} - res := FormalizeAnswer(t.Context(), nil, "Q", kb, true, false, false, "", false, "") - if !strings.Contains(res.FinalAnswer, "partial ans") { - t.Errorf("final answer = %q", res.FinalAnswer) - } -} - -// TestFormalizeAnswer_ForceLLM asserts forceLLM skips the empty short-circuit and -// still calls the model, so the FALLBACK_LLM verdict reaches the direct LLM. -func TestFormalizeAnswer_ForceLLM(t *testing.T) { - installChat(t, "direct llm fallback answer") - res := FormalizeAnswer(t.Context(), nil, "Q", &Kbinfos{}, false, false, true, "", true, "") - if res.Empty { - t.Error("forceLLM must not return the empty short-circuit") - } - if res.FinalAnswer != "direct llm fallback answer" { - t.Errorf("final answer = %q, want chat output (direct LLM invoked)", res.FinalAnswer) - } -} - -// TestRunAgenticRAG_LowMode asserts low mode does a single direct search and -// produces an answer. -func TestRunAgenticRAG_LowMode(t *testing.T) { - installChat(t, "final composed answer") - res := RunAgenticRAG(t.Context(), nil, "What is a rocket?", "", "low", - func(_ context.Context, _, _ string) ([]map[string]interface{}, []map[string]interface{}) { - return []map[string]interface{}{{"chunk_id": "a", "content_with_weight": "rocket evidence"}}, nil - }, "") - if res.FinalAnswer != "final composed answer" { - t.Errorf("final answer = %q", res.FinalAnswer) - } -} - -// TestRunAgenticRAG_EmptySearch asserts an empty search yields the empty message. -func TestRunAgenticRAG_EmptySearch(t *testing.T) { - res := RunAgenticRAG(t.Context(), nil, "Q", "", "low", - func(_ context.Context, _, _ string) ([]map[string]interface{}, []map[string]interface{}) { - return nil, nil - }, "") - if !res.Empty || res.FinalAnswer != emptyResultMessage { - t.Errorf("empty result = %+v", res) - } -} - -// recordingChatInvoker records the system prompt it receives and returns a fixed -// answer, so tests can assert the final-answer system message is composed -// correctly. -type recordingChatInvoker struct { - content string - system string -} - -func (r *recordingChatInvoker) Invoke(_ context.Context, _ *gorm.DB, req component.ChatInvokeRequest) (*component.ChatInvokeResponse, error) { - for _, m := range req.Messages { - if m.Role == schema.System { - r.system = m.Content - break - } - } - return &component.ChatInvokeResponse{Content: r.content}, nil -} - -// TestFormalizeAnswer_SystemPromptPrepended asserts that a non-empty dialog -// system prompt is prepended to the final-answer system prompt. -func TestFormalizeAnswer_SystemPromptPrepended(t *testing.T) { - inv := &recordingChatInvoker{content: "final composed answer"} - component.SetDefaultChatInvoker(inv) - t.Cleanup(func() { component.SetDefaultChatInvoker(nil) }) - - kb := &Kbinfos{Chunks: []map[string]interface{}{{"content_with_weight": "evidence"}}} - res := FormalizeAnswer(t.Context(), nil, "Q", kb, false, false, false, "", false, "Be concise and factual.") - if res.FinalAnswer != "final composed answer" { - t.Errorf("final answer = %q, want chat output", res.FinalAnswer) - } - if inv.system == "" { - t.Fatal("system prompt was not sent to the chat invoker") - } - if !strings.Contains(inv.system, "Be concise and factual.") { - t.Errorf("system prompt does not contain the dialog prompt: %q", inv.system) - } - if !strings.Contains(inv.system, "You are a smart agent") { - t.Errorf("system prompt does not contain the default final-answer prompt: %q", inv.system) - } -} diff --git a/internal/agent/harness/compilation.go b/internal/agent/harness/compilation.go deleted file mode 100644 index 883fc303d77..00000000000 --- a/internal/agent/harness/compilation.go +++ /dev/null @@ -1,210 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "strings" - - "gorm.io/gorm" - - "ragflow/internal/dao" - "ragflow/internal/entity" - "ragflow/internal/service/nav" -) - -// buildCompilationMap reports which compiled artifacts each bound KB carries, -// mirroring Python _get_compilation_map + _add_template_group_compilations + -// _has_dataset_nav_rows. The Pipeline uses this map to gate compilation-requiring -// tools (ontology_navigate / mindmap_navigate / graph_explore / wiki_query) and to -// decide which tree/timeline/mindmap/wiki artifact a route may target. -// -// The map is keyed by KB id; each value is the set of compilation kinds that KB -// carries, using the SAME canonical tokens the tools filter on: -// - "toc" / "tree" → ontology_navigate catalog kinds -// - "mindmap" → mindmap_navigate -// - "graph" / "knowledge_graph" → graph_explore -// - "wiki" → wiki_query -// - "page_index" / "timeline" → ontology_navigate catalog kinds -func buildCompilationMap(ctx context.Context, db *gorm.DB, tenantID string, datasetIDs []string) map[string]map[string]bool { - out := map[string]map[string]bool{} - if db == nil || len(datasetIDs) == 0 { - return out - } - kbDAO := dao.KnowledgebaseDAO{} - kbs, err := kbDAO.GetByIDs(ctx, db, datasetIDs) - if err != nil { - return out - } - tplDAO := dao.CompilationTemplateDAO{} - navSvc := nav.GetNavService() - - for _, kb := range kbs { - if kb == nil { - continue - } - comps := map[string]bool{} - pc := kb.ParserConfig - - // 1. Top-level parser_config toggles (mirrors _get_compilation_map). - if boolVal(pc, "toc") { - comps["toc"] = true - } - if boolVal(pc, "knowledge_graph") { - comps["knowledge_graph"] = true - } - if boolVal(pc, "wiki") { - comps["wiki"] = true - } - if boolVal(pc, "mindmap") { - comps["mindmap"] = true - } - if boolVal(pc, "page_index") { - comps["page_index"] = true - } - - // 2. Template-group-derived compilations (mirrors _add_template_group_compilations). - for _, groupID := range parserConfigTemplateGroupIDs(pc) { - templates, err := tplDAO.ListByGroup(ctx, db, groupID) - if err != nil { - continue - } - for _, t := range templates { - if t == nil { - continue - } - addCompilationKind(comps, t.Kind) - } - } - - // 3. Dataset-navigation rows → "tree" (mirrors _has_dataset_nav_rows). - if hasDatasetNavRows(ctx, navSvc, tenantID, kb.ID) { - comps["tree"] = true - } - - if len(comps) > 0 { - out[kb.ID] = comps - } - } - return out -} - -// addCompilationKind maps a template kind onto the canonical compilation tokens, -// mirroring _compilation_kind_for_agentic_map + the comps accumulation in -// _add_template_group_compilations. -func addCompilationKind(comps map[string]bool, rawKind string) { - // normalizeCompilationKind has already collapsed page_index/pageindex to - // "timeline", so those tokens never reach the switch (mirrors Python, where - // the same collapse makes its page_index/pageindex elif branch unreachable). - norm := normalizeCompilationKind(rawKind) - switch norm { - case "knowledge_graph": - comps["knowledge_graph"] = true - case "tree": - comps["tree"] = true - case "timeline": - comps["page_index"] = true - case "mindmap", "mind_map": - comps["mindmap"] = true - case "wiki": - comps["wiki"] = true - } -} - -// normalizeCompilationKind mirrors Python _compilation_kind_for_agentic_map: -// pageindex/page_index collapse to "timeline"; otherwise lower + '-'→'_'. -func normalizeCompilationKind(kind string) string { - norm := strings.ToLower(strings.TrimSpace(kind)) - norm = strings.ReplaceAll(norm, "-", "_") - switch norm { - case "pageindex", "page_index": - return "timeline" - default: - return norm - } -} - -// parserConfigTemplateGroupIDs mirrors Python _parser_config_compilation_template_group_ids: -// read "compilation_template_group_id" (top-level or under "ext"), accept a -// single string or a list, dedup, drop empties. -func parserConfigTemplateGroupIDs(pc entity.JSONMap) []string { - if pc == nil { - return nil - } - var raw interface{} - if v, ok := pc["compilation_template_group_id"]; ok { - raw = v - } else if ext, ok := pc["ext"].(map[string]interface{}); ok { - raw = ext["compilation_template_group_id"] - } - if raw == nil { - return nil - } - var list []string - switch v := raw.(type) { - case string: - list = []string{v} - case []interface{}: - for _, item := range v { - if s, ok := item.(string); ok { - list = append(list, s) - } - } - case []string: - list = v - } - seen := map[string]bool{} - var out []string - for _, id := range list { - id = strings.TrimSpace(id) - if id == "" || seen[id] { - continue - } - seen[id] = true - out = append(out, id) - } - return out -} - -// hasDatasetNavRows reports whether the KB has dataset-navigation rows (mirrors -// Python _has_dataset_nav_rows). It asks the nav service for top-level clusters; -// a non-empty list means the tree artifact is present. -func hasDatasetNavRows(ctx context.Context, ns nav.NavService, tenantID, kbID string) bool { - if ns == nil || tenantID == "" || kbID == "" { - return false - } - clusters, _, err := ns.ListClusters(ctx, tenantID, kbID, 0, 1) - if err != nil { - return false - } - return len(clusters) > 0 -} - -func boolVal(m entity.JSONMap, key string) bool { - if m == nil { - return false - } - switch v := m[key].(type) { - case bool: - return v - case string: - return strings.EqualFold(v, "true") || v == "1" - case float64: - return v != 0 - } - return false -} diff --git a/internal/agent/harness/compilation_test.go b/internal/agent/harness/compilation_test.go deleted file mode 100644 index c504c0f5721..00000000000 --- a/internal/agent/harness/compilation_test.go +++ /dev/null @@ -1,103 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "testing" - - "ragflow/internal/entity" -) - -// TestNormalizeCompilationKind asserts pageindex/page_index collapse to timeline -// and '-'→'_' normalization. -func TestNormalizeCompilationKind(t *testing.T) { - cases := map[string]string{ - "pageindex": "timeline", - "page_index": "timeline", - "PAGE_INDEX": "timeline", - "mind_map": "mind_map", - "Mind-Map": "mind_map", - "knowledge_graph": "knowledge_graph", - "tree": "tree", - } - for in, want := range cases { - if got := normalizeCompilationKind(in); got != want { - t.Errorf("normalizeCompilationKind(%q) = %q, want %q", in, got, want) - } - } -} - -// TestAddCompilationKind asserts each template kind maps onto the canonical token. -func TestAddCompilationKind(t *testing.T) { - comps := map[string]bool{} - addCompilationKind(comps, "knowledge_graph") - addCompilationKind(comps, "mind_map") - addCompilationKind(comps, "timeline") - addCompilationKind(comps, "wiki") - addCompilationKind(comps, "tree") - for _, want := range []string{"knowledge_graph", "mindmap", "page_index", "wiki", "tree"} { - if !comps[want] { - t.Errorf("missing %q in comps %v", want, comps) - } - } - if comps["mind_map"] { - t.Error("mind_map must be normalized to mindmap, not kept verbatim") - } -} - -// TestParserConfigTemplateGroupIDs asserts single-string, list, and ext-nested -// forms all resolve, with dedup and empty-drop. -func TestParserConfigTemplateGroupIDs(t *testing.T) { - // top-level single string - pc := entity.JSONMap{"compilation_template_group_id": "g1"} - if got := parserConfigTemplateGroupIDs(pc); len(got) != 1 || got[0] != "g1" { - t.Errorf("single string: got %v", got) - } - // top-level list with dup + empty - pc = entity.JSONMap{"compilation_template_group_id": []interface{}{"g1", "g1", "", "g2"}} - if got := parserConfigTemplateGroupIDs(pc); len(got) != 2 { - t.Errorf("list dedup: got %v", got) - } - // ext-nested - pc = entity.JSONMap{"ext": map[string]interface{}{"compilation_template_group_id": []interface{}{"g3"}}} - if got := parserConfigTemplateGroupIDs(pc); len(got) != 1 || got[0] != "g3" { - t.Errorf("ext-nested: got %v", got) - } - // absent → nil - if got := parserConfigTemplateGroupIDs(entity.JSONMap{}); got != nil { - t.Errorf("absent: got %v, want nil", got) - } -} - -// TestBoolVal asserts bool/string/float forms. -func TestBoolVal(t *testing.T) { - if !boolVal(entity.JSONMap{"x": true}, "x") { - t.Error("bool true must be true") - } - if !boolVal(entity.JSONMap{"x": "true"}, "x") { - t.Error(`string "true" must be true`) - } - if boolVal(entity.JSONMap{"x": "false"}, "x") { - t.Error(`string "false" must be false`) - } - if boolVal(entity.JSONMap{"x": 1.0}, "x") != true { - t.Error("float 1.0 must be true") - } - if boolVal(entity.JSONMap{}, "x") { - t.Error("absent key must be false") - } -} diff --git a/internal/agent/harness/cross_check_test.go b/internal/agent/harness/cross_check_test.go deleted file mode 100644 index 99613867f72..00000000000 --- a/internal/agent/harness/cross_check_test.go +++ /dev/null @@ -1,159 +0,0 @@ -// -// 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. -// - -package harness - -import "testing" - -// TestFilterRelevantNumbers asserts 0, ...]}` - -type navSelectVerdict struct { - Relevant []int `json:"relevant"` -} - -// NavigateDatasetByTree walks the dataset nav tree with two LLM passes -// (cluster-select → document-select) and returns the routed doc_ids (capped at -// navMaxDocs). This is the LLM two-round selection (P1b) implemented in the -// harness package, which can import the chat invoker (agent/tool cannot without -// an import cycle). It routes only — it does not retrieve. -func NavigateDatasetByTree(ctx context.Context, db *gorm.DB, ns nav.NavService, tenantID, kbID, query string) []string { - query = strings.TrimSpace(query) - if query == "" { - return nil - } - - // 1. List top-level clusters. - clusters, _, err := ns.ListClusters(ctx, tenantID, kbID, 0, navMaxClusters) - if err != nil { - log.Printf("datasetnav: list clusters failed: %v", err) - return nil - } - if len(clusters) == 0 { - return nil - } - clusterItems := make([]navSelectItem, len(clusters)) - for i, c := range clusters { - clusterItems[i] = navSelectItem{Name: c.Name, Description: c.Description, DocCount: c.DocCount} - } - - // 2. LLM selects relevant clusters. - selected := askNavSelect(ctx, db, query, "clusters", clusterItems, navMaxClusters) - if len(selected) == 0 { - return nil - } - - // 3. BFS-descend selected clusters to document leaves. - leaves := collectNavLeaves(ctx, ns, tenantID, kbID, selected) - - // 4. LLM selects relevant documents. - docs := askNavSelect(ctx, db, query, "documents", leaves, navTreeMaxLeaves) - - // Dedup + cap. - seen := map[string]bool{} - var routed []string - for _, d := range docs { - if d.DocID == "" || seen[d.DocID] { - continue - } - seen[d.DocID] = true - routed = append(routed, d.DocID) - if len(routed) >= navMaxDocs { - break - } - } - return routed -} - -// navSelectItem is a renderable cluster/document with a name + description. -type navSelectItem struct { - Name string - Description string - DocCount int - DocID string -} - -// askNavSelect renders items as a numbered list and asks the model which indices -// are relevant. Returns the selected items (a subset). Mirrors _ask_nav_select. -func askNavSelect(ctx context.Context, db *gorm.DB, query, noun string, items []navSelectItem, maxItems int) []navSelectItem { - if len(items) == 0 { - return nil - } - capped := items - if len(capped) > maxItems { - capped = capped[:maxItems] - } - var b strings.Builder - for i, it := range capped { - name := strings.TrimSpace(it.Name) - if name == "" { - name = fmt.Sprintf("item-%d", i) - } - desc := strings.Join(strings.Fields(it.Description), " ") - if len(desc) > 300 { - desc = desc[:300] - } - b.WriteString(fmt.Sprintf("[%d] %s", i, name)) - if it.DocCount > 0 { - b.WriteString(fmt.Sprintf(" [%d docs]", it.DocCount)) - } - b.WriteString(": " + desc + "\n") - } - - system := strings.ReplaceAll(navSelectSystem, "{noun}", noun) - user := fmt.Sprintf("Question:\n%s\n\n%s (numbered):\n%s\n\nOutput JSON:", query, strings.Title(noun), b.String()) - - inv := chat.GetDefaultInvoker() - if inv == nil { - log.Printf("datasetnav: LLM %s selection skipped (chat invoker not configured)", noun) - return nil - } - resp, err := inv.Invoke(ctx, db, chat.Request{ - Messages: []schema.Message{ - {Role: schema.System, Content: system}, - {Role: schema.User, Content: user}, - }, - }) - if err != nil { - log.Printf("datasetnav: LLM %s selection failed: %v", noun, err) - return nil - } - var v navSelectVerdict - if err := unmarshalModelJSON(resp.Content, &v); err != nil { - return nil - } - seen := map[int]bool{} - var out []navSelectItem - for _, idx := range v.Relevant { - if idx < 0 || idx >= len(capped) || seen[idx] { - continue - } - seen[idx] = true - out = append(out, capped[idx]) - } - return out -} - -// collectNavLeaves BFS-descents selected clusters to document leaves. Mirrors -// Python _collect_nav_leaves. -func collectNavLeaves(ctx context.Context, ns nav.NavService, tenantID, kbID string, selected []navSelectItem) []navSelectItem { - type node struct { - name string - depth int - } - frontier := make([]node, 0, len(selected)) - for _, c := range selected { - if c.Name != "" { - frontier = append(frontier, node{c.Name, 0}) - } - } - var leaves []navSelectItem - seenDocs := map[string]bool{} - seenNodes := map[string]bool{} - for len(frontier) > 0 && len(leaves) < navTreeMaxLeaves { - cur := frontier[0] - frontier = frontier[1:] - if seenNodes[cur.name] { - continue - } - seenNodes[cur.name] = true - children, _, err := ns.ListChildren(ctx, tenantID, kbID, cur.name, 0, navChildrenPageSize) - if err != nil { - continue - } - for _, ch := range children { - if ch.Type == "doc" { - did := strings.TrimSpace(ch.DocID) - if did != "" && !seenDocs[did] { - seenDocs[did] = true - leaves = append(leaves, navSelectItem{Name: ch.Name, Description: ch.Description, DocID: did}) - if len(leaves) >= navTreeMaxLeaves { - break - } - } - } else if ch.Type == "cluster" && ch.Name != "" && cur.depth+1 < navTreeMaxDepth { - frontier = append(frontier, node{ch.Name, cur.depth + 1}) - } - } - } - return leaves -} diff --git a/internal/agent/harness/datasetnav_test.go b/internal/agent/harness/datasetnav_test.go deleted file mode 100644 index 4d82a010240..00000000000 --- a/internal/agent/harness/datasetnav_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package harness - -import ( - "context" - "testing" - - "ragflow/internal/service/nav" -) - -// TestAskNavSelect_IndexBased asserts the model's index-based selection maps -// back to the item subset. -func TestAskNavSelect_IndexBased(t *testing.T) { - installChat(t, `{"relevant":[0,2]}`) - items := []navSelectItem{ - {Name: "Alpha", Description: "aaa"}, - {Name: "Beta", Description: "bbb"}, - {Name: "Gamma", Description: "ggg"}, - } - out := askNavSelect(t.Context(), nil, "query", "clusters", items, 10) - if len(out) != 2 { - t.Fatalf("selected = %d, want 2", len(out)) - } - if out[0].Name != "Alpha" || out[1].Name != "Gamma" { - t.Errorf("selected names = %q, %q; want Alpha, Gamma", out[0].Name, out[1].Name) - } -} - -// TestAskNavSelect_Empty asserts an empty "relevant" list yields nothing. -func TestAskNavSelect_Empty(t *testing.T) { - installChat(t, `{"relevant":[]}`) - if out := askNavSelect(t.Context(), nil, "q", "clusters", []navSelectItem{{Name: "A"}}, 10); len(out) != 0 { - t.Errorf("expected no selection, got %d", len(out)) - } -} - -// TestAskNavSelect_OutOfRange asserts invalid indices are skipped. -func TestAskNavSelect_OutOfRange(t *testing.T) { - installChat(t, `{"relevant":[0,99,-1]}`) - out := askNavSelect(t.Context(), nil, "q", "clusters", []navSelectItem{{Name: "A"}, {Name: "B"}}, 10) - if len(out) != 1 || out[0].Name != "A" { - t.Errorf("out-of-range selection = %+v, want [A]", out) - } -} - -// TestNavigateDatasetByTree_NoQuery asserts empty query returns nil without -// calling anything. -func TestNavigateDatasetByTree_NoQuery(t *testing.T) { - if out := NavigateDatasetByTree(t.Context(), nil, nil, "t1", "kb1", " "); out != nil { - t.Errorf("expected nil for empty query, got %v", out) - } -} - -// fakeNavSvcHarness is an in-memory nav.NavService for the BFS test. -type fakeNavSvcHarness struct { - clusters []nav.NavNode - children map[string][]nav.NavNode -} - -func (f *fakeNavSvcHarness) UpsertDoc(context.Context, nav.UpsertDocInput) error { return nil } -func (f *fakeNavSvcHarness) RemoveDoc(context.Context, string, string, string) error { - return nil -} -func (f *fakeNavSvcHarness) Search(context.Context, string, string, string, []float32, int) ([]nav.NavHit, error) { - return nil, nil -} -func (f *fakeNavSvcHarness) ListClusters(context.Context, string, string, int, int) ([]nav.NavNode, int64, error) { - return f.clusters, int64(len(f.clusters)), nil -} -func (f *fakeNavSvcHarness) ListChildren(_ context.Context, _, _, name string, _, _ int) ([]nav.NavNode, int64, error) { - return f.children[name], int64(len(f.children[name])), nil -} - -// TestCollectNavLeaves_BFS asserts document leaves are collected, sub-clusters -// descended, and leaves deduped by doc_id. -func TestCollectNavLeaves_BFS(t *testing.T) { - ns := &fakeNavSvcHarness{ - clusters: []nav.NavNode{{Name: "C1", Description: "cluster 1"}}, - children: map[string][]nav.NavNode{ - "C1": { - {Name: "Sub", Type: "cluster"}, - {Name: "DocA", Type: "doc", DocID: "d1"}, - {Name: "DocB", Type: "doc", DocID: "d2"}, - }, - "Sub": {{Name: "DocC", Type: "doc", DocID: "d3"}}, - }, - } - selected := []navSelectItem{{Name: "C1", Description: "cluster 1"}} - leaves := collectNavLeaves(t.Context(), ns, "t1", "kb1", selected) - if len(leaves) != 3 { - t.Fatalf("leaves = %d, want 3 (d1,d2 from C1 + d3 from Sub)", len(leaves)) - } - seen := map[string]bool{} - for _, l := range leaves { - if l.DocID == "" { - t.Errorf("leaf %q has empty doc_id", l.Name) - } - seen[l.DocID] = true - } - if !seen["d1"] || !seen["d2"] || !seen["d3"] { - t.Errorf("collected doc_ids = %v, want d1,d2,d3", seen) - } -} diff --git a/internal/agent/harness/grounded_llm.go b/internal/agent/harness/grounded_llm.go deleted file mode 100644 index 941ffb9d233..00000000000 --- a/internal/agent/harness/grounded_llm.go +++ /dev/null @@ -1,162 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "fmt" - "strings" - - "github.com/cloudwego/eino/schema" - - "gorm.io/gorm" - "ragflow/internal/agent/chat" -) - -// LLM groundedness review (draft review). It reviews each claim's draft report -// against the cited evidence semantically, catching over-claims/relation errors -// that the lexical code-level cross-check cannot see. - -// groundedSelectPrompt is the groundedness reviewer system prompt (self-contained). -const groundedSelectPrompt = `You are an answer-groundedness reviewer. For each claim's report (the draft answer), determine whether every assertion is supported by the provided evidence. - -A claim's report is GROUNDED only if each of its assertions can be inferred from the evidence. The assertion does NOT need to use the same words as the evidence (semantic paraphrase is fine), but it must NOT: -- assert a fact that is absent from the evidence (likely model prior-injection / hallucination); -- assert a relation or value that contradicts the evidence; -- over-claim beyond what the evidence supports (e.g. the evidence only says a medication was prescribed, but the report claims "the patient is well"). - -Question: %s - -Claim reports to verify: -%s - -Evidence (each chunk labeled with an integer ID): -%s - -For each claim, classify its assertions: -- SUPPORTED: the evidence explicitly supports it, including a semantic paraphrase. -- UNGROUNDED: the evidence lacks the content, or the claimed relation/value contradicts the evidence, or the assertion over-claims beyond the evidence. - -Output format (JSON): -{ - "claims": [ - { - "claim_id": "c1", - "grounded": true, - "ungrounded_assertions": [] - }, - { - "claim_id": "c2", - "grounded": false, - "ungrounded_assertions": [ - {"assertion": "the patient had no adverse reactions", "reason": "the evidence only mentions the medication was prescribed, not the patient's reaction"} - ] - } - ] -} - -Requirements: -1. Include EVERY claim in the output (do not skip any claim_id). -2. ` + "`grounded`" + ` is true only if ALL of the claim's assertions are supported. -3. ` + "`ungrounded_assertions`" + ` is empty when ` + "`grounded`" + ` is true; otherwise list each ungrounded assertion with a one-line ` + "`reason`" + `. -4. Prefer identifying genuine over-claims or contradictions over surface-level wording differences — a semantic paraphrase IS supported.` - -// GroundedVerdict is a single claim's draft-review result. -type GroundedVerdict struct { - Grounded bool - Ungrounded []string -} - -// ClaimReport is one claim's draft report submitted for grounded review. -type ClaimReport struct { - ClaimID string - Report string -} - -type groundedClaimResult struct { - ClaimID string `json:"claim_id"` - Grounded bool `json:"grounded"` - UngroundedAssertions []struct { - Assertion string `json:"assertion"` - Reason string `json:"reason"` - } `json:"ungrounded_assertions"` -} - -type groundedReviewResult struct { - Claims []groundedClaimResult `json:"claims"` -} - -// LLMGroundedVerify mirrors Python llm_grounded_verify: for each claim report, -// decide whether it is semantically grounded in the cited evidence. Returns an -// empty map when the LLM review is unavailable (no model, no evidence, or a -// failure) — callers treat that as "no new signal". -func LLMGroundedVerify(ctx context.Context, db *gorm.DB, question string, reports []ClaimReport, kb *Kbinfos, evidenceIDs []int) map[string]GroundedVerdict { - if len(reports) == 0 { - return nil - } - inv := chat.GetDefaultInvoker() - if inv == nil { - return nil - } - evidenceMD := renderEvidenceMD(kb, evidenceIDs, narrowKeywords(question)) - if evidenceMD == "" { - return nil - } - - var reportsMD strings.Builder - for _, r := range reports { - if r.Report != "" { - reportsMD.WriteString(fmt.Sprintf("Claim %s: %s\n", r.ClaimID, r.Report)) - } - } - if reportsMD.Len() == 0 { - reportsMD.WriteString("(no claims)") - } - - prompt := fmt.Sprintf(groundedSelectPrompt, question, reportsMD.String(), evidenceMD) - resp, err := inv.Invoke(ctx, db, chat.Request{ - Messages: []schema.Message{ - {Role: schema.System, Content: prompt}, - }, - }) - if err != nil { - return nil - } - var res groundedReviewResult - if err := unmarshalModelJSON(resp.Content, &res); err != nil { - return nil - } - out := map[string]GroundedVerdict{} - for _, item := range res.Claims { - cid := strings.TrimSpace(item.ClaimID) - if cid == "" { - continue - } - var ungrounded []string - for _, u := range item.UngroundedAssertions { - s := strings.TrimSpace(u.Assertion) - if s == "" { - s = strings.TrimSpace(u.Reason) - } - if s != "" { - ungrounded = append(ungrounded, s) - } - } - out[cid] = GroundedVerdict{Grounded: item.Grounded, Ungrounded: ungrounded} - } - return out -} diff --git a/internal/agent/harness/inspector.go b/internal/agent/harness/inspector.go deleted file mode 100644 index 647a4c826ac..00000000000 --- a/internal/agent/harness/inspector.go +++ /dev/null @@ -1,265 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "crypto/md5" - "fmt" - "regexp" - "sort" - "strings" -) - -// Inspector tools (mirrors Python harness/tools/inspector.py): operate on the -// chunks already accumulated in the shared Kbinfos, rather than issuing new -// retrieval. They are stateless reads of the in-memory evidence pool. - -// InspectorOpenContext expands context around a chunk (mirrors open_context): -// the chunk plus its 2 neighbours on each side. -func InspectorOpenContext(chunks []map[string]interface{}, chunkID string) []map[string]interface{} { - idx := findChunkIndex(chunks, chunkID) - if idx < 0 { - return nil - } - start := idx - 2 - if start < 0 { - start = 0 - } - end := idx + 2 - if end > len(chunks) { - end = len(chunks) - } - return append([]map[string]interface{}(nil), chunks[start:end]...) -} - -// InspectorCompareSources returns the chunks matching the given ids (mirrors -// compare_sources). -func InspectorCompareSources(chunks []map[string]interface{}, chunkIDs []string) []map[string]interface{} { - if len(chunkIDs) == 0 { - return nil - } - want := map[string]bool{} - for _, id := range chunkIDs { - want[id] = true - } - var out []map[string]interface{} - for _, c := range chunks { - if want[chunkIDOf(c)] { - out = append(out, c) - } - } - return out -} - -// InspectorGrepWithin narrows chunks of one document to their keyword-bearing -// sentences (mirrors grep_within + _narrow_by_keywords). It returns copies so the -// shared kbinfos citation pool is never mutated. -func InspectorGrepWithin(chunks []map[string]interface{}, docID, pattern string) []map[string]interface{} { - kwds := keywordList(pattern) - var scoped []map[string]interface{} - for _, c := range chunks { - if docIDOf(c) == docID { - scoped = append(scoped, c) - } - } - if len(kwds) == 0 || len(scoped) == 0 { - return scoped - } - - var out []map[string]interface{} - dedup := map[string]bool{} - for _, c := range scoped { - cp := cloneChunk(c) - content := chunkText(cp) - narrowed := narrowContent(content, kwds) - if narrowed == "" { - continue - } - key := md5.Sum([]byte(narrowed)) - if dedup[fmt.Sprintf("%x", key)] { - continue - } - dedup[fmt.Sprintf("%x", key)] = true - cp["content_with_weight"] = narrowed - if _, ok := cp["content"]; ok { - cp["content"] = narrowed - } - delete(cp, "highlight") - out = append(out, cp) - } - return out -} - -// InspectorRequestAdjacent returns count neighbours before or after a chunk -// (mirrors request_adjacent). -func InspectorRequestAdjacent(chunks []map[string]interface{}, chunkID, direction string, count int) []map[string]interface{} { - idx := findChunkIndex(chunks, chunkID) - if idx < 0 { - return nil - } - if count <= 0 { - count = 3 - } - var start, end int - if direction == "prev" { - start = idx - count - if start < 0 { - start = 0 - } - end = idx - } else { - start = idx + 1 - end = start + count - if end > len(chunks) { - end = len(chunks) - } - } - if start >= len(chunks) || start >= end { - return nil - } - return append([]map[string]interface{}(nil), chunks[start:end]...) -} - -// findChunkIndex mirrors Python _find_chunk_index. -func findChunkIndex(chunks []map[string]interface{}, chunkID string) int { - for i, c := range chunks { - if chunkIDOf(c) == chunkID { - return i - } - } - return -1 -} - -// chunkIDOf mirrors Python _chunk_id: chunk_id or id. -func chunkIDOf(c map[string]interface{}) string { - if v, ok := c["chunk_id"].(string); ok && v != "" { - return v - } - if v, ok := c["id"].(string); ok && v != "" { - return v - } - return "" -} - -// docIDOf returns the chunk's doc_id. -func docIDOf(c map[string]interface{}) string { - if v, ok := c["doc_id"].(string); ok { - return v - } - return "" -} - -// keywordList mirrors _narrow_by_keywords' keyword parsing: comma-separated; when -// fewer than 3 comma terms, split on spaces into bigrams. -func keywordList(keywords string) []string { - comma := splitTrim(keywords, ",") - if len(comma) < 3 { - words := splitTrim(keywords, " ") - var bigrams []string - for i := 0; i+1 < len(words); i++ { - bigrams = append(bigrams, words[i]+" "+words[i+1]) - } - return bigrams - } - return comma -} - -func splitTrim(s, sep string) []string { - var out []string - for _, part := range strings.Split(s, sep) { - part = strings.ToLower(strings.TrimSpace(part)) - if part != "" { - out = append(out, part) - } - } - return out -} - -// narrowContent mirrors Python _narrow_content: keep keyword-bearing sentences -// (+/- 1 neighbour), highlight matches, wrap in "...". Returns "" when no -// keyword occurs anywhere in the content. -func narrowContent(content string, kwds []string) string { - sents := splitSentences(content) - if len(sents) == 0 { - return "" - } - keep := map[int]bool{} - matched := false - for i, s := range sents { - low := strings.ToLower(s) - for _, kw := range kwds { - if strings.Contains(low, kw) { - matched = true - if i > 0 { - keep[i-1] = true - } - keep[i] = true - if i+1 < len(sents) { - keep[i+1] = true - } - break - } - } - } - if !matched { - return "" - } - idx := make([]int, 0, len(keep)) - for i := range keep { - idx = append(idx, i) - } - sort.Ints(idx) - var b strings.Builder - for _, i := range idx { - b.WriteString(sents[i]) - } - narrowed := strings.TrimSpace(b.String()) - return "..." + highlightKeywords(narrowed, kwds) + "..." -} - -// highlightKeywords mirrors Python _highlight_keywords: wrap the longest keyword -// matches in *asterisks*, case-insensitive. -func highlightKeywords(text string, kwds []string) string { - terms := make([]string, 0, len(kwds)) - seen := map[string]bool{} - for _, k := range kwds { - if k != "" && !seen[k] { - seen[k] = true - terms = append(terms, k) - } - } - if len(terms) == 0 { - return text - } - sort.Slice(terms, func(i, j int) bool { return len(terms[i]) > len(terms[j]) }) - parts := make([]string, len(terms)) - for i, t := range terms { - parts[i] = regexp.QuoteMeta(t) - } - re := regexp.MustCompile("(?i)" + strings.Join(parts, "|")) - return re.ReplaceAllString(text, "*$0*") -} - -// cloneChunk returns a shallow copy of a chunk map so inspector narrowing never -// mutates the shared kbinfos citation pool. -func cloneChunk(c map[string]interface{}) map[string]interface{} { - cp := make(map[string]interface{}, len(c)) - for k, v := range c { - cp[k] = v - } - return cp -} diff --git a/internal/agent/harness/inspector_test.go b/internal/agent/harness/inspector_test.go deleted file mode 100644 index 4c1fdf05a69..00000000000 --- a/internal/agent/harness/inspector_test.go +++ /dev/null @@ -1,108 +0,0 @@ -// -// 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. -// - -package harness - -import "testing" - -func sampleChunks() []map[string]interface{} { - return []map[string]interface{}{ - {"chunk_id": "c0", "content_with_weight": "alpha", "doc_id": "d1"}, - {"chunk_id": "c1", "content_with_weight": "beta", "doc_id": "d1"}, - {"chunk_id": "c2", "content_with_weight": "gamma", "doc_id": "d1"}, - {"chunk_id": "c3", "content_with_weight": "delta", "doc_id": "d2"}, - {"chunk_id": "c4", "content_with_weight": "epsilon", "doc_id": "d2"}, - } -} - -// TestInspectorOpenContext asserts the chunk plus 2 neighbours on each side -// (Python slice chunks[idx-2:idx+2] is right-open, so 4 chunks: idx-2..idx+1). -func TestInspectorOpenContext(t *testing.T) { - out := InspectorOpenContext(sampleChunks(), "c2") - if len(out) != 4 { // c0..c3 (idx-2..idx+1) - t.Fatalf("open_context around c2 = %d chunks, want 4", len(out)) - } - if chunkIDOf(out[2]) != "c2" { - t.Errorf("middle chunk = %s, want c2", chunkIDOf(out[2])) - } - // Near the boundary, clamp. - if out := InspectorOpenContext(sampleChunks(), "c0"); len(out) != 2 { - t.Errorf("open_context around c0 = %d, want 2 (clamped)", len(out)) - } -} - -// TestInspectorCompareSources asserts only requested ids are returned. -func TestInspectorCompareSources(t *testing.T) { - out := InspectorCompareSources(sampleChunks(), []string{"c1", "c3"}) - if len(out) != 2 || chunkIDOf(out[0]) != "c1" || chunkIDOf(out[1]) != "c3" { - t.Errorf("compare_sources = %v", out) - } -} - -// TestInspectorGrepWithin asserts chunks are narrowed to keyword sentences and -// copies never mutate the original. Keywords are comma-separated (≥3 to avoid -// the space-bigram fallback). -func TestInspectorGrepWithin(t *testing.T) { - chunks := []map[string]interface{}{ - {"chunk_id": "c0", "content_with_weight": "Paris has 2 million people. It is in France. The Eiffel Tower is famous.", "doc_id": "d1"}, - {"chunk_id": "c1", "content_with_weight": "Tokyo has 14 million people. It is in Japan.", "doc_id": "d1"}, - } - orig := chunks[0]["content_with_weight"].(string) - out := InspectorGrepWithin(chunks, "d1", "france, eiffel, tower") - if len(out) != 1 { - t.Fatalf("grep_within = %d chunks, want 1 (only c0 has France/Eiffel)", len(out)) - } - if got := chunkText(out[0]); !contains(got, "*France*") { - t.Errorf("narrowed content must highlight France, got %q", got) - } - // Original must be untouched. - if chunks[0]["content_with_weight"].(string) != orig { - t.Error("grep_within must not mutate the shared chunk pool") - } -} - -// TestInspectorRequestAdjacent asserts next/prev direction and count clamp. -func TestInspectorRequestAdjacent(t *testing.T) { - next := InspectorRequestAdjacent(sampleChunks(), "c1", "next", 2) - if len(next) != 2 || chunkIDOf(next[0]) != "c2" || chunkIDOf(next[1]) != "c3" { - t.Errorf("request_adjacent next = %v", next) - } - prev := InspectorRequestAdjacent(sampleChunks(), "c4", "prev", 10) - if len(prev) != 4 { // c0..c3, clamped - t.Errorf("request_adjacent prev = %d, want 4 (clamped)", len(prev)) - } -} - -// TestKeywordList asserts comma vs space-bigram parsing. -func TestKeywordList(t *testing.T) { - // >=3 comma terms → kept as-is. - if got := keywordList("a, b, c"); len(got) != 3 { - t.Errorf("comma list = %v", got) - } - // <3 comma terms → space bigrams. - if got := keywordList("alpha beta"); len(got) != 1 || got[0] != "alpha beta" { - t.Errorf("space bigram = %v", got) - } -} - -func contains(s, sub string) bool { - for i := 0; i+len(sub) <= len(s); i++ { - if s[i:i+len(sub)] == sub { - return true - } - } - return false -} diff --git a/internal/agent/harness/kg_explore.go b/internal/agent/harness/kg_explore.go deleted file mode 100644 index 7b41f2bf4db..00000000000 --- a/internal/agent/harness/kg_explore.go +++ /dev/null @@ -1,537 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "encoding/json" - "fmt" - "sort" - "strings" - - "github.com/cloudwego/eino/schema" - - "ragflow/internal/agent/chat" - "ragflow/internal/engine" - "ragflow/internal/engine/types" - "ragflow/internal/service" -) - -// graph_explore (mirrors Python harness/tools/navigation.py graph_explore): walk -// the compiled knowledge graph. Unlike ontology_navigate/mindmap_navigate (which -// read the single merged "graph" JSON), the KG store keeps one searchable row per -// entity/relation, so we *search* our way to a small subgraph: dense-seed -// entities by the question, hop _KG_HOPS out over relations, then ask the chat -// model whether that subgraph answers the question. -// -// Seeds use the tenant embedding model via service.NavEmbedder (dense KNN, -// similarity>=kgSeedSim, re-ranked by mention_count_int desc); when the embedding -// model is unavailable it degrades to keyword match (mirrors Python _kg_search's -// `embed_mdl is None` path). - -const ( - kgScopeDataset = "dataset" - kgScopeDoc = "doc" - - kgSeeds = 2 // top-N entities matched directly to the question - kgSeedPool = 64 // KNN candidate pool before the mention_count_int re-sort - kgSeedSim = 0.8 // dense seed similarity floor (Python _KG_SEED_SIM) - kgHops = 2 // relation hops out from the seeds - kgNeighbors = 128 // cap on neighbour entity rows resolved per hop - kgRelLimit = 32 // relations fetched per endpoint filter -) - -type kgEntity struct { - Name string `json:"name"` - Type string `json:"type"` - Description string `json:"description"` - Aliases []string `json:"aliases"` - SourceChunkIDs []string `json:"source_chunk_ids"` - DocID string `json:"doc_id"` -} - -type kgRelation struct { - From string `json:"from"` - To string `json:"to"` - Type string `json:"type"` - SourceChunkIDs []string `json:"source_chunk_ids"` - DocID string `json:"doc_id"` -} - -// ExploreResult is the graph_explore output: exactly one of Answer / Chunks is -// populated. -type ExploreResult struct { - Answer string - Chunks []map[string]interface{} -} - -// ExploreGraph implements graph_explore. -func ExploreGraph(ctx context.Context, tenantID string, datasetIDs []string, query, keywords string, docScope []string) (ExploreResult, error) { - empty := ExploreResult{} - text := strings.TrimSpace(query + " " + keywords) - if text == "" || len(datasetIDs) == 0 { - return empty, nil - } - de := engine.Get() - if de == nil { - return empty, fmt.Errorf("graph_explore: engine not configured") - } - - scopeKwd := kgScopeDataset - if len(docScope) > 0 { - scopeKwd = kgScopeDoc - } - - var entities []kgEntity - var relations []kgRelation - seenNames := map[string]bool{} - - addEntities := func(new []kgEntity, scopeKey string) []string { - var added []string - for _, e := range new { - key := scopeKey + ":" + strings.ToLower(e.Name) - if seenNames[key] { - continue - } - seenNames[key] = true - entities = append(entities, e) - added = append(added, e.Name) - } - return added - } - - // Encode the seed text ONCE (not per dataset): a single embedding request - // serves every KB. A nil vector means the embedding model is unavailable and - // the seed search falls back to keyword match. - seedVec := encodeSeedVector(ctx, tenantID, text) - - for _, kbID := range datasetIDs { - // (1) Seeds: dense KNN (similarity>=_KG_SEED_SIM) over the scoped entity - // rows, re-ranked by mention_count_int desc; falls back to keyword match - // when the embedding model is unavailable. - seedRows := kgSeedSearch(ctx, de, tenantID, kbID, docScope, text, scopeKwd, seedVec) - var seeds []kgEntity - for _, r := range seedRows { - if e, ok := kgParseEntity(r); ok { - seeds = append(seeds, e) - } - } - frontier := addEntities(seeds, kbID) - - // (2) Expand kgHops out, collecting relations and neighbour entities. - for hop := 0; hop < kgHops; hop++ { - if len(frontier) == 0 { - break - } - terms := endpointTerms(frontier) - relRows := kgSearch(ctx, de, tenantID, kbID, docScope, "relation", "", kgRelLimit, scopeKwd, - map[string]interface{}{"from_entity_kwd": terms}, "", 0) - relRows = append(relRows, kgSearch(ctx, de, tenantID, kbID, docScope, "relation", "", kgRelLimit, scopeKwd, - map[string]interface{}{"to_entity_kwd": terms}, "", 0)...) - seenRel := map[string]bool{} - var hopRelations []kgRelation - for _, r := range relRows { - rel, ok := kgParseRelation(r) - if !ok { - continue - } - k := rel.From + "|" + rel.To + "|" + rel.Type - if seenRel[k] { - continue - } - seenRel[k] = true - hopRelations = append(hopRelations, rel) - } - relations = append(relations, hopRelations...) - - // Neighbour entity names not yet visited. - seenLower := map[string]bool{} - for k := range seenNames { - if strings.HasPrefix(k, kbID+":") { - seenLower[strings.TrimPrefix(k, kbID+":")] = true - } - } - neighSet := map[string]string{} - for _, r := range hopRelations { - for _, n := range []string{r.From, r.To} { - n = strings.TrimSpace(n) - if n == "" || seenLower[strings.ToLower(n)] { - continue - } - neighSet[strings.ToLower(n)] = n - } - } - if len(neighSet) == 0 { - break - } - neighFiltered := make([]string, 0, len(neighSet)) - for _, n := range neighSet { - neighFiltered = append(neighFiltered, n) - } - limit := kgNeighbors - if len(neighFiltered) < limit { - limit = len(neighFiltered) - } - neighRows := kgSearch(ctx, de, tenantID, kbID, docScope, "entity", "", limit, scopeKwd, - map[string]interface{}{"name_kwd": endpointTerms(neighFiltered)}, "", 0) - var neighbours []kgEntity - for _, r := range neighRows { - if e, ok := kgParseEntity(r); ok { - neighbours = append(neighbours, e) - } - } - frontier = addEntities(neighbours, kbID) - } - } - - if len(entities) == 0 && len(relations) == 0 { - return empty, nil - } - - // (3) Does the subgraph answer the question? - answer, relevant := askStructureAnswer(ctx, query, entities, relations) - // (4a) Sufficient — return the answer, no chunks. - if answer != "" { - return ExploreResult{Answer: answer}, nil - } - - // (4b) Insufficient — return source passages behind the relevant nodes. - evidence := collectEvidenceIDs(entities, relations, relevant) - var chunks []map[string]interface{} - for docID, ids := range evidence { - if docID != "" && len(ids) > 0 { - chunks = append(chunks, loadChunksByIDs(ctx, tenantID, ids)...) - } - } - return ExploreResult{Chunks: chunks}, nil -} - -// encodeSeedVector encodes the seed text once for the whole ExploreGraph call. -// Returns nil when the tenant embedding model is unavailable (or encoding fails). -func encodeSeedVector(ctx context.Context, tenantID, text string) []float64 { - embedder := service.NewNavEmbedder(service.NewModelProviderService(), "") - vecs, err := embedder.Encode(ctx, tenantID, []string{text}) - if err != nil || len(vecs) == 0 || len(vecs[0]) == 0 { - return nil - } - vec := make([]float64, len(vecs[0])) - for i, v := range vecs[0] { - vec[i] = float64(v) - } - return vec -} - -// kgSeedSearch searches the compiled KG entity rows for seeds (mirrors Python -// _kg_search dense branch): dense KNN over name_kwd with similarity>=0.8, -// re-ranked by mention_count_int desc, top kgSeeds. Falls back to keyword match -// when seedVec is nil (embedding model unavailable). -func kgSeedSearch(ctx context.Context, de engine.DocEngine, tenantID, kbID string, docIDs []string, text, scopeKwd string, seedVec []float64) []map[string]interface{} { - if seedVec != nil { - dense := &types.MatchDenseExpr{ - VectorColumnName: fmt.Sprintf("q_%d_vec", len(seedVec)), - EmbeddingData: seedVec, - EmbeddingDataType: "float", - DistanceType: "cosine", - TopN: kgSeedPool, - ExtraOptions: map[string]interface{}{"similarity": kgSeedSim}, - } - rows := kgSearchRaw(ctx, de, tenantID, kbID, docIDs, "entity", scopeKwd, nil, []interface{}{dense}, "mention_count_int", kgSeedPool) - return topMentionCount(rows, kgSeeds) - } - // Text fallback (mirrors Python _kg_search `embed_mdl is None` path). - return kgSearch(ctx, de, tenantID, kbID, docIDs, "entity", text, kgSeeds, scopeKwd, nil, "mention_count_int", kgSeedPool) -} - -// topMentionCount re-ranks rows by mention_count_int desc and returns topN. -func topMentionCount(rows []map[string]interface{}, topN int) []map[string]interface{} { - sort.SliceStable(rows, func(i, j int) bool { - return mentionCount(rows[i]) > mentionCount(rows[j]) - }) - if len(rows) > topN { - rows = rows[:topN] - } - return rows -} - -func mentionCount(row map[string]interface{}) int { - switch v := row["mention_count_int"].(type) { - case int: - return v - case int64: - return int(v) - case float64: - return int(v) - case float32: - return int(v) - } - return 0 -} - -// kgSearchRaw is the low-level KG row search with explicit match exprs and any -// extra filter keys (e.g. from_entity_kwd/to_entity_kwd/name_kwd). -func kgSearchRaw(ctx context.Context, de engine.DocEngine, tenantID, kbID string, docIDs []string, kind, scopeKwd string, extra map[string]interface{}, matchExprs []interface{}, orderDesc string, limit int) []map[string]interface{} { - idx := fmt.Sprintf("ragflow_%s", tenantID) - condition := map[string]interface{}{"knowledge_graph_kwd": kind} - if scopeKwd != "" { - condition["scope_kwd"] = scopeKwd - } - if len(docIDs) > 0 { - condition["doc_id"] = docIDs - } - for k, v := range extra { - condition[k] = v - } - fields := []string{"content_with_weight", "source_chunk_ids", "doc_id", "docnm_kwd", "name_kwd", "mention_count_int", "from_entity_kwd", "to_entity_kwd"} - req := &types.SearchRequest{ - IndexNames: []string{idx}, - KbIDs: []string{kbID}, - SelectFields: fields, - Filter: condition, - Limit: limit, - MatchExprs: matchExprs, - } - if orderDesc != "" { - req.OrderBy = &types.OrderByExpr{} - req.OrderBy.Desc(orderDesc) - } - res, err := de.Search(ctx, req) - if err != nil { - return nil - } - return res.Chunks -} - -// kgSearch searches the compiled KG rows of one KB (mirrors Python _kg_search), -// using keyword match. It only builds the MatchTextExpr (with the pool-based -// TopN) and delegates the request construction to kgSearchRaw. -func kgSearch(ctx context.Context, de engine.DocEngine, tenantID, kbID string, docIDs []string, kind, text string, topN int, scopeKwd string, extra map[string]interface{}, orderDesc string, pool int) []map[string]interface{} { - var matchExprs []interface{} - if text != "" { - knnTopN := topN - if pool > knnTopN { - knnTopN = pool - } - matchExprs = []interface{}{&types.MatchTextExpr{ - Fields: []string{"content_ltks", "content_sm_ltks"}, - MatchingText: text, - TopN: knnTopN, - }} - } - return kgSearchRaw(ctx, de, tenantID, kbID, docIDs, kind, scopeKwd, extra, matchExprs, orderDesc, topN) -} - -func kgParseEntity(row map[string]interface{}) (kgEntity, bool) { - name := "" - payload := map[string]interface{}{} - if s, ok := row["content_with_weight"].(string); ok { - _ = json.Unmarshal([]byte(s), &payload) - } - if v, ok := payload["name"].(string); ok && v != "" { - name = v - } else if v, ok := payload["term"].(string); ok && v != "" { - name = v - } else if v, ok := payload["title"].(string); ok && v != "" { - name = v - } - name = strings.TrimSpace(name) - if name == "" { - return kgEntity{}, false - } - e := kgEntity{ - Name: name, - Type: strOr(payload["type"], "other"), - Description: strOr(payload["description"], ""), - SourceChunkIDs: strSliceField(row["source_chunk_ids"]), - DocID: strOr(row["doc_id"], ""), - } - if aliases, ok := payload["aliases"].([]interface{}); ok { - for _, a := range aliases { - if s, ok := a.(string); ok && strings.TrimSpace(s) != "" { - e.Aliases = append(e.Aliases, strings.TrimSpace(s)) - } - } - } - return e, true -} - -func kgParseRelation(row map[string]interface{}) (kgRelation, bool) { - src := strings.TrimSpace(strOr(row["from_entity_kwd"], "")) - tgt := strings.TrimSpace(strOr(row["to_entity_kwd"], "")) - if src == "" || tgt == "" { - return kgRelation{}, false - } - typ := "related" - if payload, ok := row["content_with_weight"].(string); ok { - var p map[string]interface{} - if json.Unmarshal([]byte(payload), &p) == nil { - if t, ok := p["type"].(string); ok && t != "" { - typ = t - } else if t, ok := p["relation"].(string); ok && t != "" { - typ = t - } - } - } - return kgRelation{ - From: src, To: tgt, Type: typ, - SourceChunkIDs: strSliceField(row["source_chunk_ids"]), - DocID: strOr(row["doc_id"], ""), - }, true -} - -// endpointTerms mirrors Python _endpoint_terms: original + lowercased forms, so -// hop queries match both merged (lowercased) and per-doc (original-case) -// endpoint fields. -func endpointTerms(names []string) []string { - set := map[string]bool{} - for _, n := range names { - n = strings.TrimSpace(n) - if n == "" { - continue - } - set[n] = true - set[strings.ToLower(n)] = true - } - out := make([]string, 0, len(set)) - for n := range set { - out = append(out, n) - } - sort.Strings(out) - return out -} - -// collectEvidenceIDs mirrors Python _collect_evidence_ids: group source chunk ids -// of relevant entities AND relations by doc. -func collectEvidenceIDs(entities []kgEntity, relations []kgRelation, relevantNames []string) map[string][]string { - wanted := map[string]bool{} - for _, n := range relevantNames { - if s := strings.TrimSpace(n); s != "" { - wanted[strings.ToLower(s)] = true - } - } - byDoc := map[string][]string{} - seen := map[string]bool{} - add := func(docID string, ids []string) { - for _, cid := range ids { - if cid == "" { - continue - } - key := docID + "|" + cid - if seen[key] { - continue - } - seen[key] = true - byDoc[docID] = append(byDoc[docID], cid) - } - } - for _, e := range entities { - names := map[string]bool{strings.ToLower(e.Name): true} - for _, a := range e.Aliases { - names[strings.ToLower(a)] = true - } - if intersects(names, wanted) { - add(e.DocID, e.SourceChunkIDs) - } - } - for _, r := range relations { - if wanted[strings.ToLower(r.From)] || wanted[strings.ToLower(r.To)] { - add(r.DocID, r.SourceChunkIDs) - } - } - return byDoc -} - -func intersects(a, b map[string]bool) bool { - for k := range a { - if b[k] { - return true - } - } - return false -} - -// askStructureAnswer asks the chat model whether the subgraph answers the query -// (mirrors Python _ask_structure), returning (answer, relevant_names). -func askStructureAnswer(ctx context.Context, query string, entities []kgEntity, relations []kgRelation) (string, []string) { - inv := chat.GetDefaultInvoker() - if inv == nil { - return "", nil - } - rendered := renderKGSubgraph(entities, relations) - resp, err := inv.Invoke(ctx, nil, chat.Request{ - Messages: []schema.Message{ - {Role: schema.System, Content: strings.ReplaceAll(navSystemPrompt, "{noun}", "knowledge graph")}, - {Role: schema.User, Content: fmt.Sprintf("Question:\n%s\n\nKnowledge graph:\n%s\n\nOutput JSON:", query, rendered)}, - }, - }) - if err != nil { - return "", nil - } - var v structureNavVerdict - if err := unmarshalModelJSON(resp.Content, &v); err != nil { - return "", nil - } - answer := "" - if v.IsSufficient { - answer = strings.TrimSpace(v.Answer) - } - return answer, v.RelevantEntities -} - -func renderKGSubgraph(entities []kgEntity, relations []kgRelation) string { - var b strings.Builder - b.WriteString("Entities:") - for i, e := range entities { - if i >= maxStructureEntities { - break - } - b.WriteString("\n- " + e.Name + " (" + orStr(e.Type, "other") + ")") - if d := strings.Join(strings.Fields(e.Description), " "); d != "" { - b.WriteString(": " + d) - } - } - b.WriteString("\n\nRelations:") - for i, r := range relations { - if i >= maxStructureRelations { - break - } - b.WriteString("\n- " + r.From + " -[" + r.Type + "]-> " + r.To) - } - return b.String() -} - -func strOr(v interface{}, def string) string { - if s, ok := v.(string); ok && s != "" { - return s - } - return def -} - -func strSliceField(v interface{}) []string { - switch x := v.(type) { - case []string: - return x - case []interface{}: - var out []string - for _, item := range x { - if s, ok := item.(string); ok { - out = append(out, s) - } - } - return out - } - return nil -} diff --git a/internal/agent/harness/kg_explore_test.go b/internal/agent/harness/kg_explore_test.go deleted file mode 100644 index a544cb883e2..00000000000 --- a/internal/agent/harness/kg_explore_test.go +++ /dev/null @@ -1,133 +0,0 @@ -// -// 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. -// - -package harness - -import "testing" - -// TestKGParseEntity asserts the name/alias/source extraction from a KG row. -func TestKGParseEntity(t *testing.T) { - row := map[string]interface{}{ - "content_with_weight": `{"name":"Paris","type":"LOCATION","aliases":["City of Light"]}`, - "source_chunk_ids": []interface{}{"ck-1", "ck-2"}, - "doc_id": "doc-1", - } - e, ok := kgParseEntity(row) - if !ok { - t.Fatal("entity must parse") - } - if e.Name != "Paris" || e.Type != "LOCATION" { - t.Errorf("name/type = %q/%q", e.Name, e.Type) - } - if len(e.Aliases) != 1 || e.Aliases[0] != "City of Light" { - t.Errorf("aliases = %v", e.Aliases) - } - if len(e.SourceChunkIDs) != 2 || e.DocID != "doc-1" { - t.Errorf("source_chunk_ids/doc_id = %v/%q", e.SourceChunkIDs, e.DocID) - } -} - -// TestKGParseRelation asserts endpoint + type extraction, and rejection of -// dangling endpoints. -func TestKGParseRelation(t *testing.T) { - row := map[string]interface{}{ - "content_with_weight": `{"type":"capital_of"}`, - "from_entity_kwd": "Paris", - "to_entity_kwd": "France", - } - r, ok := kgParseRelation(row) - if !ok { - t.Fatal("relation must parse") - } - if r.From != "Paris" || r.To != "France" || r.Type != "capital_of" { - t.Errorf("from/to/type = %q/%q/%q", r.From, r.To, r.Type) - } - if _, ok := kgParseRelation(map[string]interface{}{"from_entity_kwd": "", "to_entity_kwd": "X"}); ok { - t.Error("dangling endpoint must be rejected") - } -} - -// TestEndpointTerms asserts original + lowercased variants are produced. -func TestEndpointTerms(t *testing.T) { - terms := endpointTerms([]string{"Paris", "France"}) - got := map[string]bool{} - for _, t := range terms { - got[t] = true - } - for _, want := range []string{"Paris", "paris", "France", "france"} { - if !got[want] { - t.Errorf("endpoint terms missing %q, got %v", want, terms) - } - } -} - -// TestCollectEvidenceIDs asserts relevant entities AND relations contribute -// source chunk ids grouped by doc. -func TestCollectEvidenceIDs(t *testing.T) { - entities := []kgEntity{ - {Name: "Paris", SourceChunkIDs: []string{"ck-1"}, DocID: "doc-1"}, - {Name: "Berlin", SourceChunkIDs: []string{"ck-2"}, DocID: "doc-1"}, - } - relations := []kgRelation{ - {From: "Paris", To: "France", SourceChunkIDs: []string{"ck-3"}, DocID: "doc-1"}, - } - got := collectEvidenceIDs(entities, relations, []string{"Paris", "France"}) - ids := got["doc-1"] - if len(ids) != 2 { // ck-1 (Paris entity) + ck-3 (Paris→France relation) - t.Errorf("expected 2 evidence ids (Paris entity + Paris→France relation), got %v", ids) - } - // Berlin is not relevant → its ck-2 must be excluded. - for _, id := range ids { - if id == "ck-2" { - t.Error("Berlin's chunk must be excluded (not relevant)") - } - } -} - -// TestMentionCountReRank asserts topMentionCount re-sorts by mention_count_int -// desc and truncates to topN. -func TestMentionCountReRank(t *testing.T) { - rows := []map[string]interface{}{ - {"name_kwd": "low", "mention_count_int": float64(3)}, - {"name_kwd": "high", "mention_count_int": float64(9)}, - {"name_kwd": "mid", "mention_count_int": float64(5)}, - } - top := topMentionCount(rows, 2) - if len(top) != 2 { - t.Fatalf("topMentionCount = %d, want 2", len(top)) - } - if mentionCount(top[0]) != 9 || mentionCount(top[1]) != 5 { - t.Errorf("re-rank order wrong: [%d, %d]", mentionCount(top[0]), mentionCount(top[1])) - } -} - -// TestNormalizeWebResults asserts Tavily "results" and agent "chunks" envelopes -// both normalize to the shared evidence shape. -func TestNormalizeWebResults(t *testing.T) { - tavily := `{"results":[{"url":"https://a","content":"hello world","title":"A"}]}` - out := normalizeWebResults([]byte(tavily)) - if len(out) != 1 || out[0]["content_with_weight"] != "hello world" { - t.Fatalf("tavily envelope: got %v", out) - } - if out[0]["url"] != "https://a" { - t.Errorf("url = %v", out[0]["url"]) - } - // A result without a URL must be dropped. - noURL := `{"results":[{"content":"no url here"}]}` - if out := normalizeWebResults([]byte(noURL)); len(out) != 0 { - t.Errorf("result without URL must be dropped, got %v", out) - } -} diff --git a/internal/agent/harness/navigation.go b/internal/agent/harness/navigation.go deleted file mode 100644 index 459f0c54ca2..00000000000 --- a/internal/agent/harness/navigation.go +++ /dev/null @@ -1,281 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "encoding/json" - "fmt" - "strings" - - "github.com/cloudwego/eino/schema" - - "ragflow/internal/agent/chat" - "ragflow/internal/engine" - "ragflow/internal/engine/types" -) - -// Structure navigation mirrors Python navigation.py (ontology_navigate / -// mindmap_navigate). These live in the harness package (not agent/tool) because -// they need the chat invoker, and agent/tool → agent/component would form an -// import cycle. -const ( - toolOntologyNavigate = "ontology_navigate" - toolMindmapNavigate = "mindmap_navigate" -) - -var catalogKinds = map[string]bool{"tree": true, "timeline": true, "raptor": true, "page_index": true, "pageindex": true} -var mindmapKinds = map[string]bool{"mindmap": true, "mind_map": true} - -const navSystemPrompt = `You are given the {noun} of one or more documents — an outline of entities and their relations — and a question. - -Decide whether that outline alone already answers the question. - -Rules: -1. Answer ONLY from the outline below. Do not invent facts. -2. Set "is_sufficient" to true only when the outline genuinely answers the question; otherwise false with an empty answer. -3. Always fill "relevant_entities" with the exact ` + "`name`" + ` values of the entities most related to the question (up to 10), even when the outline is not sufficient — they are used to pull the underlying source text. - -Output ONLY JSON, no prose, no code fences: -{"is_sufficient": true/false, "answer": "", "relevant_entities": ["", ...]}` - -const ( - maxStructureEntities = 300 - maxStructureRelations = 300 - maxEvidenceChunks = 24 -) - -type structureNavArgs struct { - Topic string `json:"topic"` - Keywords string `json:"keywords,omitempty"` - DocScope []string `json:"doc_scope,omitempty"` -} - -type structureEntity struct { - Name string `json:"name"` - Type string `json:"type"` - Description string `json:"description"` - SourceChunkIDs []string `json:"source_chunk_ids"` - DocID string `json:"-"` -} - -type structureNavVerdict struct { - IsSufficient bool `json:"is_sufficient"` - Answer string `json:"answer"` - RelevantEntities []string `json:"relevant_entities"` -} - -// NavigateStructure implements ontology_navigate / mindmap_navigate. It reads -// the compiled structure (entities) of the in-scope documents, asks the chat -// model which entities answer the question, and pulls the source chunks behind -// the selected entities. Routing only — returns empty on any failure. -func NavigateStructure(ctx context.Context, tenantID string, kind string, args structureNavArgs) (string, error) { - noun := "catalog" - var kinds map[string]bool - if kind == toolMindmapNavigate { - kinds = mindmapKinds - noun = "mindmap" - } else { - kinds = catalogKinds - } - - query := strings.TrimSpace(args.Topic + " " + args.Keywords) - if query == "" || len(args.DocScope) == 0 { - return `{"chunks":[]}`, nil - } - - var entities []structureEntity - for _, docID := range args.DocScope { - es := loadStructureEntities(ctx, tenantID, docID, kinds) - for _, e := range es { - if e.Name != "" { - e.DocID = docID - entities = append(entities, e) - } - } - } - if len(entities) == 0 { - return `{"chunks":[]}`, nil - } - - selected, err := askStructureSelect(ctx, query, noun, entities) - if err != nil || len(selected) == 0 { - return `{"chunks":[]}`, nil - } - - idsByDoc := map[string][]string{} - for _, e := range selected { - idsByDoc[e.DocID] = append(idsByDoc[e.DocID], e.SourceChunkIDs...) - } - var chunks []map[string]interface{} - for _, ids := range idsByDoc { - chunks = append(chunks, loadChunksByIDs(ctx, tenantID, dedupStrings(ids))...) - if len(chunks) >= maxEvidenceChunks { - break - } - } - b, _ := json.Marshal(map[string]interface{}{"chunks": chunks}) - return string(b), nil -} - -func loadStructureEntities(ctx context.Context, tenantID, docID string, kinds map[string]bool) []structureEntity { - de := engine.Get() - if de == nil { - return nil - } - idx := fmt.Sprintf("ragflow_%s", tenantID) - req := &types.SearchRequest{ - IndexNames: []string{idx}, - Filter: map[string]interface{}{"doc_id": []string{docID}, "knowledge_graph_kwd": []string{"graph"}}, - SelectFields: []string{"content_with_weight", "compile_kwd", "compilation_template_kind_kwd"}, - Limit: 1000, - } - res, err := de.Search(ctx, req) - if err != nil { - return nil - } - var out []structureEntity - for _, row := range res.Chunks { - kind := normalizeKind(row) - if !kinds[kind] { - continue - } - payload, _ := row["content_with_weight"].(string) - var graph struct { - Entities []structureEntity `json:"entities"` - } - if err := json.Unmarshal([]byte(payload), &graph); err != nil { - continue - } - out = append(out, graph.Entities...) - } - return out -} - -func normalizeKind(row map[string]interface{}) string { - if ck, _ := row["compile_kwd"].(string); ck == "raptor_graph" { - return "raptor" - } - kind, _ := row["compilation_template_kind_kwd"].(string) - if kind == "" { - kind, _ = row["compile_kwd"].(string) - } - kind = strings.ToLower(strings.TrimSpace(strings.ReplaceAll(kind, "-", "_"))) - if kind == "pageindex" || kind == "page_index" || kind == "knowledge_graph" { - return "timeline" - } - return kind -} - -func askStructureSelect(ctx context.Context, query, noun string, entities []structureEntity) ([]structureEntity, error) { - rendered := renderStructureEntities(entities) - inv := chat.GetDefaultInvoker() - if inv == nil { - return nil, fmt.Errorf("dataset navigation: chat invoker not configured") - } - resp, err := inv.Invoke(ctx, nil, chat.Request{ - Messages: []schema.Message{ - {Role: schema.System, Content: strings.ReplaceAll(navSystemPrompt, "{noun}", noun)}, - {Role: schema.User, Content: fmt.Sprintf("Question:\n%s\n\n%s:\n%s\n\nOutput JSON:", query, noun, rendered)}, - }, - }) - if err != nil { - return nil, err - } - var v structureNavVerdict - if err := unmarshalModelJSON(resp.Content, &v); err != nil { - return nil, err - } - want := map[string]bool{} - for _, n := range v.RelevantEntities { - want[n] = true - } - var out []structureEntity - for _, e := range entities { - if want[e.Name] { - out = append(out, e) - } - } - return out, nil -} - -func renderStructureEntities(entities []structureEntity) string { - var b strings.Builder - b.WriteString("Entities:") - for i, e := range entities { - if i >= maxStructureEntities { - break - } - b.WriteString("\n- " + e.Name + " (" + orStr(e.Type, "other") + ")") - if d := strings.Join(strings.Fields(e.Description), " "); d != "" { - b.WriteString(": " + d) - } - } - return b.String() -} - -func loadChunksByIDs(ctx context.Context, tenantID string, ids []string) []map[string]interface{} { - if len(ids) == 0 { - return nil - } - de := engine.Get() - if de == nil { - return nil - } - idx := fmt.Sprintf("ragflow_%s", tenantID) - limit := maxEvidenceChunks - if len(ids) < limit { - limit = len(ids) - } - req := &types.SearchRequest{ - IndexNames: []string{idx}, - Filter: map[string]interface{}{"id": ids}, - SelectFields: []string{"content_with_weight", "docnm_kwd", "doc_id"}, - Limit: limit, - } - res, err := de.Search(ctx, req) - if err != nil { - return nil - } - var out []map[string]interface{} - for _, row := range res.Chunks { - out = append(out, map[string]interface{}{ - "chunk_id": row["id"], "content_with_weight": row["content_with_weight"], - "docnm_kwd": row["docnm_kwd"], "doc_id": row["doc_id"], - }) - } - return out -} - -func dedupStrings(in []string) []string { - seen := map[string]bool{} - var out []string - for _, s := range in { - if s != "" && !seen[s] { - seen[s] = true - out = append(out, s) - } - } - return out -} - -func orStr(v, def string) string { - if v == "" { - return def - } - return v -} diff --git a/internal/agent/harness/navigation_test.go b/internal/agent/harness/navigation_test.go deleted file mode 100644 index 52a1f9c4ef2..00000000000 --- a/internal/agent/harness/navigation_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package harness - -import ( - "strings" - "testing" -) - -// TestRenderStructureEntities asserts the prompt outline is compact and includes -// entity name/type/description. -func TestRenderStructureEntities(t *testing.T) { - entities := []structureEntity{ - {Name: "Rocket", Type: "concept", Description: "a propulsion device"}, - {Name: "Engine", Type: "part"}, - } - out := renderStructureEntities(entities) - if out == "" { - t.Fatal("expected rendered outline") - } - if !containsAll(out, "Rocket", "Engine", "concept") { - t.Errorf("rendered outline missing entities: %q", out) - } -} - -// TestNavigateStructure_NoScope asserts empty doc scope yields empty chunks -// without calling the model. -func TestNavigateStructure_NoScope(t *testing.T) { - out, err := NavigateStructure(t.Context(), "t1", toolOntologyNavigate, structureNavArgs{ - Topic: "rocket", DocScope: nil, - }) - if err != nil { - t.Fatal(err) - } - if out != `{"chunks":[]}` { - t.Errorf("no-scope result = %q, want empty chunks", out) - } -} - -// TestNormalizeKind mirrors the API's kind normalization. -func TestNormalizeKind(t *testing.T) { - cases := []struct { - row map[string]interface{} - want string - }{ - {map[string]interface{}{"compile_kwd": "raptor_graph"}, "raptor"}, - {map[string]interface{}{"compilation_template_kind_kwd": "page_index"}, "timeline"}, - {map[string]interface{}{"compilation_template_kind_kwd": "knowledge_graph"}, "timeline"}, - {map[string]interface{}{"compilation_template_kind_kwd": "mindmap"}, "mindmap"}, - {map[string]interface{}{"compile_kwd": "tree"}, "tree"}, - } - for _, c := range cases { - if got := normalizeKind(c.row); got != c.want { - t.Errorf("normalizeKind(%v) = %q, want %q", c.row, got, c.want) - } - } -} - -func containsAll(s string, subs ...string) bool { - for _, sub := range subs { - if !strings.Contains(s, sub) { - return false - } - } - return true -} diff --git a/internal/agent/harness/orchestrator.go b/internal/agent/harness/orchestrator.go deleted file mode 100644 index f64907bbeaf..00000000000 --- a/internal/agent/harness/orchestrator.go +++ /dev/null @@ -1,267 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "fmt" - "strings" -) - -// Orchestration input/output mirrors Python orchestrator (direct.py / decompose.py). -// SearchFn performs one hybrid search for a query and returns chunks + doc aggs, -// so the orchestrator is decoupled from the concrete retrieval backend. -type SearchFn func(ctx context.Context, query, keywords string) ([]map[string]interface{}, []map[string]interface{}) - -// Kbinfos is the shared accumulation store (Python tools.kbinfos). -type Kbinfos struct { - Chunks []map[string]interface{} - DocAggs []map[string]interface{} - // PreSummary is the merged claim-report summary produced by AgenticResearch - // (Python kbinfos["pre_summary"]). The final-answer call reads it when set. - PreSummary string -} - -func (k *Kbinfos) HasChunks() bool { return len(k.Chunks) > 0 } - -// Merge appends the given chunks/aggs, deduplicating by chunkKey. It returns the -// GLOBAL indices (positions in k.Chunks after the merge) of the chunks this call -// contributed, so callers can store stable evidence references across multiple -// Merge calls (per-search indices would diverge from the accumulated list). -func (k *Kbinfos) Merge(chunks, aggs []map[string]interface{}) []int { - seen := map[string]bool{} - for _, c := range k.Chunks { - seen[chunkKey(c)] = true - } - var added []int - for _, c := range chunks { - kk := chunkKey(c) - if !seen[kk] { - seen[kk] = true - k.Chunks = append(k.Chunks, c) - } - // Record the global index of every contributed chunk (dedup or new), - // so EvidenceIDs always reference the accumulated kbinfos positions. - added = append(added, indexOfChunk(k.Chunks, kk)) - } - dseen := map[string]bool{} - for _, d := range k.DocAggs { - if id, _ := d["doc_id"].(string); id != "" { - dseen[id] = true - } - } - for _, d := range aggs { - if id, _ := d["doc_id"].(string); id != "" && !dseen[id] { - dseen[id] = true - k.DocAggs = append(k.DocAggs, d) - } - } - return added -} - -// indexOfChunk returns the global index of the chunk whose key matches kk. -func indexOfChunk(chunks []map[string]interface{}, kk string) int { - for i, c := range chunks { - if chunkKey(c) == kk { - return i - } - } - return -1 -} - -// chunkKey returns a stable dedup key for a chunk. Prefers chunk_id/id when -// present; otherwise falls back to a content-derived hash so chunks without an -// id still dedup correctly (and never collide on a shared empty/"" key). -func chunkKey(c map[string]interface{}) string { - if id, ok := c["chunk_id"].(string); ok && id != "" { - return "cid:" + id - } - if id, ok := c["id"].(string); ok && id != "" { - return "id:" + id - } - content := "" - if t, ok := c["content_with_weight"].(string); ok { - content = t - } else if t, ok := c["content"].(string); ok { - content = t - } - if content == "" { - // No stable identity: fall back to the doc reference so at least - // per-document grouping is preserved (rarely reached). - content = fmt.Sprintf("%s|%s", anyString(c["doc_id"]), anyString(c["docnm_kwd"])) - } - return "h:" + fnv64(content) -} - -func anyString(v interface{}) string { - if s, ok := v.(string); ok { - return s - } - return "" -} - -// fnv64 is a deterministic non-crypto hash for dedup keys. -func fnv64(s string) string { - h := uint64(14695981039346656037) - for i := 0; i < len(s); i++ { - h ^= uint64(s[i]) - h *= 1099511628211 - } - return fmt.Sprintf("%016x", h) -} - -// OrchestratorResult mirrors the state updates returned by the Python -// orchestrator nodes. -type OrchestratorResult struct { - Verdict *SufficiencyVerdict - PartialAnswer bool - Abstain bool - EmptyResult bool - Kbinfos *Kbinfos - // Caveat is the decision-ladder explanation for a partial answer (e.g. - // "evidence partially supports the answer"), surfaced in the final answer. - Caveat string - // ForceLLM is set by the FALLBACK_LLM verdict: even with no gathered - // evidence, finalization must still call the direct LLM (rather than return - // the canned "no evidence" string). - ForceLLM bool -} - -// DirectSearch is the low-mode orchestrator: one hybrid search → merge. -func DirectSearch(ctx context.Context, search SearchFn, question, keywords string, kbinfos *Kbinfos) OrchestratorResult { - if kbinfos == nil { - kbinfos = &Kbinfos{} - } - chunks, aggs := search(ctx, question, keywords) - kbinfos.Merge(chunks, aggs) - if !kbinfos.HasChunks() { - return OrchestratorResult{EmptyResult: true, Kbinfos: kbinfos} - } - return OrchestratorResult{Kbinfos: kbinfos} -} - -// DecomposeAndSearch is the medium-mode orchestrator: decompose → parallel -// search → cross-check → fusion → iterate until a verdict stops it. -func DecomposeAndSearch(ctx context.Context, search SearchFn, question, keywords string, claims []*ClaimTarget, modeLabel string, kbinfos *Kbinfos) OrchestratorResult { - if kbinfos == nil { - kbinfos = &Kbinfos{} - } - mode, _ := GetMode(modeLabel) - if mode.Label == "" { - mode = THINKING_MODES["medium"] - } - unverified := func() []*ClaimTarget { - var out []*ClaimTarget - for _, c := range claims { - if !c.IsVerified { - out = append(out, c) - } - } - return out - } - - for cycle := 0; cycle < mode.MaxOrchestratorCycles; cycle++ { - uv := unverified() - if len(uv) == 0 { - break - } - for _, c := range uv { - chunks, aggs := search(ctx, c.Description, keywords) - if len(chunks) > 0 { - c.IsVerified = true - c.Confidence = 0.8 - // Merge returns the GLOBAL indices of this claim's chunks in the - // accumulated kbinfos, which is what CrossCheckClaim resolves - // against (allChunks is keyed by that global position). - global := kbinfos.Merge(chunks, aggs) - c.AgentResult = &AgentResult{ - ClaimID: c.ClaimID, Report: summarize(chunks), IsVerified: true, Confidence: 0.8, - EvidenceIDs: global, - } - } else { - c.AgentResult = &AgentResult{ClaimID: c.ClaimID, IsVerified: false, Confidence: 0.0} - } - } - - allChunks := map[int]map[string]interface{}{} - for i, c := range kbinfos.Chunks { - allChunks[i] = c - } - var agentResults []AgentResult - var crossResults []ClaimCrossCheckResult - for _, c := range claims { - if c.AgentResult != nil { - agentResults = append(agentResults, *c.AgentResult) - crossResults = append(crossResults, CrossCheckClaim(c.AgentResult, allChunks)) - } - } - claimTargets := make([]ClaimTarget, 0, len(claims)) - for _, c := range claims { - if c != nil { - claimTargets = append(claimTargets, *c) - } - } - verdict := ComputeFusionScore(agentResults, crossResults, mode, question, claimTargets, allChunks) - action, _, caveat := RouteSufficiencyVerdict(verdict, modeLabel, cycle, mode.MaxOrchestratorCycles, nil) - - switch action { - case "ANSWER": - return OrchestratorResult{Verdict: &verdict, Kbinfos: kbinfos} - case "ANSWER_PARTIAL": - return OrchestratorResult{Verdict: &verdict, PartialAnswer: true, Caveat: caveat, Kbinfos: kbinfos} - case "FALLBACK_LLM": - // ultra route: no grounded answer, hand off to the direct LLM. Force - // finalization to call the model even with empty evidence. - return OrchestratorResult{Verdict: &verdict, PartialAnswer: true, Caveat: caveat, ForceLLM: true, Kbinfos: kbinfos} - case "ABSTAIN": - kbinfos.Chunks = nil - return OrchestratorResult{Verdict: &verdict, Abstain: true, Kbinfos: kbinfos} - case "CONTINUE": - // fallthrough to next cycle - } - } - return OrchestratorResult{Kbinfos: kbinfos} -} - -func summarize(chunks []map[string]interface{}) string { - var parts []string - n := 3 - if len(chunks) < n { - n = len(chunks) - } - for _, c := range chunks[:n] { - text := "" - if t, ok := c["content_with_weight"].(string); ok { - text = t - } else if t, ok := c["content"].(string); ok { - text = t - } - if len(text) > 200 { - text = text[:200] - } - parts = append(parts, text) - } - return strings.Join(parts, " | ") -} - -func intRange(n int) []int { - out := make([]int, n) - for i := range out { - out[i] = i - } - return out -} diff --git a/internal/agent/harness/orchestrator_test.go b/internal/agent/harness/orchestrator_test.go deleted file mode 100644 index 18dcc16da20..00000000000 --- a/internal/agent/harness/orchestrator_test.go +++ /dev/null @@ -1,138 +0,0 @@ -package harness - -import ( - "context" - "testing" -) - -// TestCrossCheckClaim_NumberMatch asserts a verified report whose numbers appear -// in the evidence chunk passes the cross-check. -func TestCrossCheckClaim_NumberMatch(t *testing.T) { - agent := &AgentResult{ClaimID: "c0", IsVerified: true, Report: "speed is 88 and 12", EvidenceIDs: []int{0}} - chunks := map[int]map[string]interface{}{0: {"content_with_weight": "speed is 88 and 12 here"}} - r := CrossCheckClaim(agent, chunks) - if !r.CrossCheckPassed { - t.Errorf("cross-check should pass, got mismatches %v", r.Mismatches) - } -} - -// TestKbinfosMerge_GlobalIndices asserts Merge returns the GLOBAL indices of the -// contributed chunks in the accumulated list, so a later claim's EvidenceIDs -// still resolve correctly after earlier claims pushed more chunks in. -func TestKbinfosMerge_GlobalIndices(t *testing.T) { - kb := &Kbinfos{} - // First claim's search returns chunks a,b. - first := kb.Merge([]map[string]interface{}{ - {"chunk_id": "a", "content_with_weight": "alpha 7"}, - {"chunk_id": "b", "content_with_weight": "beta"}, - }, nil) - // a->0, b->1 in the global list. - if len(first) != 2 || first[0] != 0 || first[1] != 1 { - t.Fatalf("first merge global indices = %v, want [0 1]", first) - } - // Second claim's search returns chunk c (now global index 2) and a dup of a. - second := kb.Merge([]map[string]interface{}{ - {"chunk_id": "c", "content_with_weight": "gamma 9"}, - {"chunk_id": "a", "content_with_weight": "alpha 7"}, - }, nil) - // c->2, a(dup)->0; NOT per-search [0 1]. - if len(second) != 2 || second[0] != 2 || second[1] != 0 { - t.Fatalf("second merge global indices = %v, want [2 0]", second) - } - // CrossCheckClaim must resolve both claims' evidence against the global list. - allChunks := map[int]map[string]interface{}{} - for i, c := range kb.Chunks { - allChunks[i] = c - } - r1 := CrossCheckClaim(&AgentResult{ClaimID: "c1", IsVerified: true, Report: "alpha 7", EvidenceIDs: first}, allChunks) - if !r1.HasEvidence { - t.Error("claim 1 should have evidence at global indices") - } - r2 := CrossCheckClaim(&AgentResult{ClaimID: "c2", IsVerified: true, Report: "gamma 9", EvidenceIDs: second}, allChunks) - if !r2.HasEvidence { - t.Error("claim 2 should have evidence at global index 2 (not per-search 0)") - } -} - -// TestCrossCheckClaim_Unverified asserts an unverified agent fails the check. -func TestCrossCheckClaim_Unverified(t *testing.T) { - r := CrossCheckClaim(&AgentResult{ClaimID: "c0", IsVerified: false}, nil) - if r.CrossCheckPassed { - t.Error("unverified agent must fail cross-check") - } -} - -// TestComputeFusionScore_Sufficient asserts a fully-verified high-confidence set -// is SUFFICIENT. -func TestComputeFusionScore_Sufficient(t *testing.T) { - agents := []AgentResult{{ClaimID: "c0", IsVerified: true, Confidence: 0.9, Report: "value 42", EvidenceIDs: []int{0}}} - cross := []ClaimCrossCheckResult{{ClaimID: "c0", CrossCheckPassed: true, CrossCheckScore: 1.0, HasEvidence: true}} - v := ComputeFusionScore(agents, cross, THINKING_MODES["medium"], "", nil, nil) - if v.Status != "SUFFICIENT" { - t.Errorf("status = %q, want SUFFICIENT", v.Status) - } - if v.AgentConfidence != 0.9 { - t.Errorf("agent_confidence = %v, want 0.9", v.AgentConfidence) - } -} - -// TestComputeFusionScore_NoEvidence asserts a claim whose cross-check failed -// (nothing passed) is UNANSWERABLE. -func TestComputeFusionScore_NoEvidence(t *testing.T) { - cross := []ClaimCrossCheckResult{{ClaimID: "c0", CrossCheckPassed: false, CrossCheckScore: 0.0, HasEvidence: false}} - v := ComputeFusionScore([]AgentResult{{ClaimID: "c0", IsVerified: true, Confidence: 0.9}}, cross, THINKING_MODES["medium"], "", nil, nil) - if v.Status != "UNANSWERABLE" { - t.Errorf("status = %q, want UNANSWERABLE", v.Status) - } - if len(v.MissingClaims) != 1 { - t.Errorf("missing claims = %v, want [c0]", v.MissingClaims) - } -} - -// TestRouteSufficiencyVerdict asserts SUFFICIENT → ANSWER. -func TestRouteSufficiencyVerdict(t *testing.T) { - action, cont, _ := RouteSufficiencyVerdict(SufficiencyVerdict{Status: "SUFFICIENT", Score: 0.9, AgentConfidence: 0.9}, "medium", 0, 3, nil) - if action != "ANSWER" || cont { - t.Errorf("got (%q,%v), want (ANSWER,false)", action, cont) - } -} - -// TestDirectSearch_Merges asserts direct search merges chunks and flags empty. -func TestDirectSearch_Merges(t *testing.T) { - kb := &Kbinfos{} - res := DirectSearch(t.Context(), func(_ context.Context, _, _ string) ([]map[string]interface{}, []map[string]interface{}) { - return []map[string]interface{}{{"chunk_id": "a", "content_with_weight": "alpha"}}, nil - }, "q", "", kb) - if res.EmptyResult || !kb.HasChunks() { - t.Errorf("expected merged chunks, empty=%v chunks=%d", res.EmptyResult, len(kb.Chunks)) - } -} - -// TestDirectSearch_Empty asserts direct search flags empty when no chunks. -func TestDirectSearch_Empty(t *testing.T) { - kb := &Kbinfos{} - res := DirectSearch(t.Context(), func(_ context.Context, _, _ string) ([]map[string]interface{}, []map[string]interface{}) { - return nil, nil - }, "q", "", kb) - if !res.EmptyResult { - t.Error("expected empty_result=true") - } -} - -// TestDecomposeAndSearch_Verifies asserts a searchable claim gets verified and -// the loop stops on ANSWER. -func TestDecomposeAndSearch_Verifies(t *testing.T) { - claims := []*ClaimTarget{{ClaimID: "c0", Description: "fact 42 about X"}} - kb := &Kbinfos{} - res := DecomposeAndSearch(t.Context(), - func(_ context.Context, _, _ string) ([]map[string]interface{}, []map[string]interface{}) { - return []map[string]interface{}{{"chunk_id": "x", "content_with_weight": "the value is 42"}}, nil - }, - "Q", "", claims, "medium", kb) - if !claims[0].IsVerified { - t.Error("claim should be verified") - } - if res.Verdict == nil { - t.Error("expected a verdict") - } -} diff --git a/internal/agent/harness/pipeline.go b/internal/agent/harness/pipeline.go deleted file mode 100644 index 2ad343eada8..00000000000 --- a/internal/agent/harness/pipeline.go +++ /dev/null @@ -1,491 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "encoding/json" - "strings" - "sync" - - einotool "github.com/cloudwego/eino/components/tool" - - "gorm.io/gorm" - "ragflow/internal/agent/tool" - "ragflow/internal/service/nav" -) - -// ToolResult is the normalized result of executing one agent tool, mirroring -// Python harness/types.py ToolResult. -type ToolResult struct { - Chunks []map[string]interface{} - Docs []string // doc ids produced by a routing tool (dataset_navigation_*) - Answer string // direct answer (ontology_navigate / structured_query) - Error string - // EvidenceIndices holds the GLOBAL indices of Chunks after they were merged - // into the shared kbinfos (populated by Execute, under mu). Consumers must - // use these rather than re-indexing the shared slice, which is mutated - // concurrently by parallel claim research. - EvidenceIndices []int -} - -// docScopeConsumers are the tools that retrieve *within* a document set. When a -// routing tool has produced a relevant-doc set, these inherit it as doc_scope -// unless the caller passed one explicitly. -var docScopeConsumers = map[string]bool{ - "ontology_navigate": true, - "mindmap_navigate": true, - "graph_explore": true, - "hybrid_search": true, - "vector_search": true, - "bm25_search": true, - "structured_query": true, -} - -// Pipeline is the unified tool-execution dispatcher (mirrors Python -// harness/pipeline.py). It routes a tool name + args to the concrete tool, -// injects doc_scope for within-document tools, merges evidence into the shared -// Kbinfos, and filters the tool list by compilation availability. -// -// It composes a *ProductionRunner (which owns the real tool instances) so the -// agent loop drives the SAME retrieval path as the linear Run flow. -type Pipeline struct { - db *gorm.DB - tenantID string - datasetIDs []string - runner *ProductionRunner - kbinfos *Kbinfos - // compilation[kbID] = set of compiled-artifact kinds. Empty map disables - // compilation gating. - compilation map[string]map[string]bool - // routedDocs are the latest relevant-doc ids produced by a routing tool. - routedDocs []string - // lastEntity is the most recently discovered entity/document name (Step A.5). - // It gates graph_explore eligibility (mirrors OrchestratorContext.last_entity). - lastEntity string - trace []string - // mu guards kbinfos.Merge + routedDocs, which the parallel claim research in - // AgenticResearch mutates concurrently (Python relies on the single-threaded - // event loop; Go must serialize). - mu sync.Mutex -} - -// NewPipeline builds a Pipeline over the given production runner and evidence -// store. compilation may be nil (no gating). -func NewPipeline(db *gorm.DB, tenantID string, datasetIDs []string, runner *ProductionRunner, kbinfos *Kbinfos, compilation map[string]map[string]bool) *Pipeline { - if kbinfos == nil { - kbinfos = &Kbinfos{} - } - return &Pipeline{ - db: db, tenantID: tenantID, datasetIDs: datasetIDs, runner: runner, - kbinfos: kbinfos, compilation: compilation, - } -} - -// HasRoutedScope mirrors Python gating.py tool_fits_context has_routed_scope -// (agent.py:167 uses bool(pipeline._routed_docs)). ontology/mindmap/graph tools -// are only callable once a routing tool has produced a doc set. -func (p *Pipeline) HasRoutedScope() bool { return len(p.scope()) > 0 } - -// scope returns a snapshot of the routed docs under mu (mirrors Python -// pipeline._routed_docs; the parallel claim research mutates it concurrently). -func (p *Pipeline) scope() []string { - p.mu.Lock() - defer p.mu.Unlock() - return append([]string(nil), p.routedDocs...) -} - -// chunksSnapshot returns a snapshot of the accumulated evidence chunks under mu. -func (p *Pipeline) chunksSnapshot() []map[string]interface{} { - p.mu.Lock() - defer p.mu.Unlock() - return append([]map[string]interface{}(nil), p.kbinfos.Chunks...) -} - -// noteEntity records the most recently discovered entity (mirrors -// OrchestratorContext.note_entity). Ignores empty values so a fruitless round -// cannot clear a prior discovery. -func (p *Pipeline) noteEntity(name string) { - if p == nil { - return - } - if name = strings.TrimSpace(name); name != "" { - p.mu.Lock() - p.lastEntity = name - p.mu.Unlock() - } -} - -// HasDiscoveredEntity reports whether graph_explore is eligible (mirrors -// gating.py:81 `graph_explore and not context.last_entity`). -func (p *Pipeline) HasDiscoveredEntity() bool { - if p == nil { - return false - } - p.mu.Lock() - defer p.mu.Unlock() - return p.lastEntity != "" -} - -// Kbinfos returns the shared evidence store. -func (p *Pipeline) Kbinfos() *Kbinfos { return p.kbinfos } - -// Execute dispatches a tool call and merges the result into kbinfos. It mirrors -// Python Pipeline.execute: doc_scope injection + kbinfos merge + routing-tool -// doc tracking. -func (p *Pipeline) Execute(ctx context.Context, toolName string, args map[string]interface{}) ToolResult { - res := p.executeTool(ctx, toolName, args) - p.mu.Lock() - defer p.mu.Unlock() - if len(res.Docs) > 0 { - // A routing tool yielded relevant doc ids — remember them so downstream - // within-document tools inherit the scope. - p.routedDocs = res.Docs - } - if len(res.Chunks) > 0 { - res.EvidenceIndices = p.kbinfos.Merge(res.Chunks, nil) - } - p.trace = append(p.trace, toolName) - return res -} - -// executeTool runs one concrete tool. It injects doc_scope for within-document -// tools and returns the normalized result (without merging). -func (p *Pipeline) executeTool(ctx context.Context, toolName string, args map[string]interface{}) ToolResult { - if args == nil { - args = map[string]interface{}{} - } - // doc_scope inheritance: within-document tools take the routed docs unless - // the caller passed an explicit doc_scope. - if docScopeConsumers[toolName] { - if scope := p.scope(); len(scope) > 0 { - if _, has := args["doc_scope"]; !has { - args["doc_scope"] = scope - } - } - } - - switch toolName { - case "hybrid_search", "vector_search", "bm25_search": - return p.runSearchTool(ctx, toolName, args) - case "web_search": - return p.runWebTool(ctx, args) - case "dataset_navigation_by_tree": - return p.runNavTool(ctx, args) - case "wiki_query": - return p.runWikiTool(ctx, args) - case "ontology_navigate", "mindmap_navigate": - return p.runStructureTool(ctx, toolName, args) - case "graph_explore": - return p.runGraphExploreTool(ctx, args) - case "inspector_open_context", "inspector_compare", "inspector_grep_within", "inspector_request_adjacent": - return p.runInspectorTool(toolName, args) - case "structured_query": - return p.runSQLTool(ctx, args) - default: - return ToolResult{Error: "Unknown tool: " + toolName} - } -} - -// runSearchTool runs hybrid/vector/bm25 retrieval. -func (p *Pipeline) runSearchTool(ctx context.Context, toolName string, args map[string]interface{}) ToolResult { - if p.runner == nil { - return ToolResult{} - } - // Default kb_ids to the pipeline's bound datasets. - if _, has := args["kb_ids"]; !has { - args["kb_ids"] = p.datasetIDs - } - - var inv einotool.InvokableTool - if toolName == "hybrid_search" { - inv = p.runner.searchTool - } else { - base, err := tool.BuildByName(toolName, nil) - if err != nil { - return ToolResult{Error: err.Error()} - } - t, ok := base.(einotool.InvokableTool) - if !ok { - return ToolResult{Error: toolName + " is not invokable"} - } - inv = t - } - if inv == nil { - return ToolResult{} - } - raw, err := inv.InvokableRun(ctx, mustJSON(args)) - if err != nil { - return ToolResult{Error: err.Error()} - } - var res struct { - Chunks []map[string]interface{} `json:"chunks"` - } - if err := json.Unmarshal([]byte(raw), &res); err != nil { - return ToolResult{} - } - return ToolResult{Chunks: res.Chunks} -} - -// runNavTool runs the dataset-navigation router and returns its doc ids. -func (p *Pipeline) runNavTool(ctx context.Context, args map[string]interface{}) ToolResult { - if p.runner == nil { - return ToolResult{} - } - topic := stringValue(args["topic"]) - keywords := stringValue(args["keywords"]) - query := strings.TrimSpace(topic + " " + keywords) - if query == "" { - return ToolResult{} - } - ns := p.runner.navSvc - if ns == nil { - ns = nav.GetNavService() - } - if ns == nil { - return ToolResult{} - } - seen := map[string]bool{} - var docs []string - for _, kbID := range p.datasetIDs { - for _, id := range NavigateDatasetByTree(ctx, p.db, ns, p.tenantID, kbID, query) { - if id != "" && !seen[id] { - seen[id] = true - docs = append(docs, id) - } - } - } - return ToolResult{Docs: docs} -} - -// runWebTool runs web_search via the runner's configured web provider. Returns -// an empty result when no provider is configured (mirrors Python web_search -// has_web() guard). -func (p *Pipeline) runWebTool(ctx context.Context, args map[string]interface{}) ToolResult { - if p.runner == nil || p.runner.webTool == nil { - return ToolResult{} - } - query := stringValue(args["query"]) - keywords := stringValue(args["keywords"]) - raw, err := p.runner.webTool.InvokableRun(ctx, mustJSON(map[string]interface{}{"query": query, "keywords": keywords})) - if err != nil { - return ToolResult{Error: err.Error()} - } - chunks := normalizeWebResults([]byte(raw)) - return ToolResult{Chunks: chunks} -} - -// runGraphExploreTool runs graph_explore via ExploreGraph (kg_explore.go). -func (p *Pipeline) runGraphExploreTool(ctx context.Context, args map[string]interface{}) ToolResult { - // Gate: graph_explore is only offered once research has surfaced an entity - // to expand from (mirrors gating.py:81 tool_fits_context). - if !p.HasDiscoveredEntity() { - return ToolResult{} - } - topic := stringValue(args["query"]) - if topic == "" { - topic = stringValue(args["topic"]) - } - keywords := stringValue(args["keywords"]) - var scope []string - switch v := args["doc_scope"].(type) { - case []string: - scope = v - case []interface{}: - for _, x := range v { - if s, ok := x.(string); ok { - scope = append(scope, s) - } - } - } - if len(scope) == 0 { - scope = p.scope() - } - out, err := ExploreGraph(ctx, p.tenantID, p.datasetIDs, topic, keywords, scope) - if err != nil { - return ToolResult{Error: err.Error()} - } - return ToolResult{Chunks: out.Chunks, Answer: out.Answer} -} - -// runSQLTool forwards structured_query to the runner's SQL retrieval path. -func (p *Pipeline) runSQLTool(ctx context.Context, args map[string]interface{}) ToolResult { - if p.runner == nil { - return ToolResult{} - } - return p.runner.runSQLTool(ctx, args) -} - -// runInspectorTool dispatches the four inspector tools over the shared kbinfos. -func (p *Pipeline) runInspectorTool(toolName string, args map[string]interface{}) ToolResult { - chunks := p.chunksSnapshot() - switch toolName { - case "inspector_open_context": - return ToolResult{Chunks: InspectorOpenContext(chunks, stringValue(args["chunk_id"]))} - case "inspector_compare": - var ids []string - switch v := args["chunk_ids"].(type) { - case []string: - ids = v - case []interface{}: - for _, x := range v { - if s, ok := x.(string); ok { - ids = append(ids, s) - } - } - } - return ToolResult{Chunks: InspectorCompareSources(chunks, ids)} - case "inspector_grep_within": - return ToolResult{Chunks: InspectorGrepWithin(chunks, stringValue(args["doc_id"]), stringValue(args["pattern"]))} - case "inspector_request_adjacent": - count := 3 - if n, ok := args["count"].(float64); ok { - count = int(n) - } - return ToolResult{Chunks: InspectorRequestAdjacent(chunks, stringValue(args["chunk_id"]), stringValue(args["direction"]), count)} - } - return ToolResult{Error: "Unknown inspector tool: " + toolName} -} - -// runWikiTool runs wiki_query via the runner's wiki service. -func (p *Pipeline) runWikiTool(ctx context.Context, args map[string]interface{}) ToolResult { - if p.runner == nil { - return ToolResult{} - } - query := stringValue(args["query"]) - keywords := stringValue(args["keywords"]) - chunks, _ := p.runner.wikiSearch(ctx, query, keywords) - return ToolResult{Chunks: chunks} -} - -// runStructureTool runs ontology_navigate / mindmap_navigate via NavigateStructure. -func (p *Pipeline) runStructureTool(ctx context.Context, toolName string, args map[string]interface{}) ToolResult { - if !p.HasRoutedScope() { - return ToolResult{} // gated: requires a routed doc scope - } - topic := stringValue(args["topic"]) - keywords := stringValue(args["keywords"]) - var scope []string - switch v := args["doc_scope"].(type) { - case []string: - scope = v - case []interface{}: - for _, x := range v { - if s, ok := x.(string); ok { - scope = append(scope, s) - } - } - } - if len(scope) == 0 { - scope = p.scope() - } - raw, err := NavigateStructure(ctx, p.tenantID, toolName, structureNavArgs{ - Topic: topic, Keywords: keywords, DocScope: scope, - }) - if err != nil { - return ToolResult{Error: err.Error()} - } - var res struct { - Chunks []map[string]interface{} `json:"chunks"` - } - if err := json.Unmarshal([]byte(raw), &res); err != nil { - return ToolResult{} - } - return ToolResult{Chunks: res.Chunks} -} - -// GetChunks retrieves raw chunks by global evidence id (mirrors Python -// Pipeline.get_chunks). -func (p *Pipeline) GetChunks(evidenceIDs []int) map[int]map[string]interface{} { - chunks := p.chunksSnapshot() - out := map[int]map[string]interface{}{} - for _, eid := range evidenceIDs { - if eid >= 0 && eid < len(chunks) { - out[eid] = chunks[eid] - } - } - return out -} - -// implementedTools is the whitelist of tools the Pipeline can actually dispatch. -// Tools listed in a mode's AvailableTools but not here (structured_query, -// inspector_*) are NOT yet implemented in the Go harness, so they are filtered -// out to keep the LLM from calling an unknown tool. -var implementedTools = map[string]bool{ - "hybrid_search": true, - "vector_search": true, - "bm25_search": true, - "web_search": true, - "dataset_navigation_by_tree": true, - "wiki_query": true, - "ontology_navigate": true, - "mindmap_navigate": true, - "graph_explore": true, - "structured_query": true, - "inspector_open_context": true, - "inspector_compare": true, - "inspector_grep_within": true, - "inspector_request_adjacent": true, -} - -// AvailableTools filters a mode's tool list to (a) tools the Pipeline can -// actually dispatch, and (b) compilation-availability (mirrors Python -// filter_available_tools). When the compilation map is empty, compilation gating -// is disabled but the implementation whitelist still applies. -func (p *Pipeline) AvailableTools(modeTools []string) []string { - var out []string - for _, name := range modeTools { - if !implementedTools[name] { - continue - } - if len(p.compilation) > 0 { - if req, ok := toolCompilationRequirement(name); ok && !p.compilationSatisfied(req) { - continue - } - } - out = append(out, name) - } - return out -} - -func (p *Pipeline) compilationSatisfied(wanted []string) bool { - for _, comps := range p.compilation { - for _, w := range wanted { - if comps[w] { - return true - } - } - } - return false -} - -// toolCompilationRequirement returns the compilation artifact a tool needs -// (mirrors Python TOOL_REGISTRY requires_compilation / compilation_type). -func toolCompilationRequirement(name string) ([]string, bool) { - switch name { - case "ontology_navigate": - return []string{"toc", "tree", "page_index", "timeline", "raptor"}, true - case "mindmap_navigate": - return []string{"mindmap"}, true - case "graph_explore": - return []string{"graph", "knowledge_graph"}, true - case "wiki_query": - return []string{"wiki"}, true - default: - return nil, false - } -} diff --git a/internal/agent/harness/planner.go b/internal/agent/harness/planner.go deleted file mode 100644 index a7203e39ecb..00000000000 --- a/internal/agent/harness/planner.go +++ /dev/null @@ -1,164 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "fmt" - "log" - "strings" - - "github.com/cloudwego/eino/schema" - - "ragflow/internal/agent/chat" - - "gorm.io/gorm" -) - -// decomposePrompt is a faithful port of Python's DECOMPOSE_FACTUAL prompt shape. -// Question-type-specific variants share the same structure but tune the -// instructions; the Go planner selects by question_type. -const decomposePrompt = `Break down the research question into %d atomic claims (facts or sub-questions). - -Question: %s - -Detail level: %s -Grounding context (preliminary retrieval, may be empty): -%s - -Output format: -{ - "claims": [ - {"claim_id": "c0", "description": "...", "priority": 0, "suggested_tools": []} - ] -} -` - -type plannerClaim struct { - ClaimID string `json:"claim_id"` - Description string `json:"description"` - Priority int `json:"priority"` - SuggestedTools []string `json:"suggested_tools"` -} - -type plannerResult struct { - Claims []plannerClaim `json:"claims"` -} - -// PlannerNode mirrors Python planner_node. It decomposes the routed question -// into ClaimTargets. Direct mode (no decomposition) returns a single coarse -// claim. On any failure it falls back to the direct plan. -func PlannerNode(ctx context.Context, db *gorm.DB, route RouteDecision, seedChunks []string) WorkflowPlan { - if !route.RequiresDecomposition { - return directPlan(route.Question) - } - mode, ok := GetMode(route.ThinkingMode) - if !ok { - // Unknown or empty mode label: fall back to medium so the planner is not - // driven by a zero-valued mode (which would yield a degenerate plan). - mode = THINKING_MODES["medium"] - } - maxClaims := maxClaimsFor(mode.Label) - detail := detailLevelFor(mode.Label) - - prompt := fmt.Sprintf(decomposePrompt, maxClaims, route.Question, detail, formatSeedChunks(seedChunks)) - - inv := chat.GetDefaultInvoker() - if inv == nil { - log.Printf("agentic_rag: planner_node skipped (chat invoker not configured); fallback direct") - return directPlan(route.Question) - } - resp, err := inv.Invoke(ctx, db, chat.Request{ - Messages: []schema.Message{ - {Role: schema.System, Content: prompt}, - {Role: schema.User, Content: route.Question}, - }, - }) - if err != nil { - log.Printf("agentic_rag: planner_node failed (fallback direct): %v", err) - return directPlan(route.Question) - } - var res plannerResult - if err := unmarshalModelJSON(resp.Content, &res); err != nil { - log.Printf("agentic_rag: planner_node parse failed (fallback direct): %v", err) - return directPlan(route.Question) - } - claims := make([]ClaimTarget, 0, len(res.Claims)) - for i, c := range res.Claims { - desc := strings.TrimSpace(c.Description) - if desc == "" { - continue - } - claims = append(claims, ClaimTarget{ - ClaimID: orDefault(c.ClaimID, fmt.Sprintf("c%d", i)), - Description: desc, - Priority: c.Priority, - SuggestedTools: c.SuggestedTools, - }) - } - if len(claims) == 0 { - return directPlan(route.Question) - } - return WorkflowPlan{ - PlanType: planTypeFor(route.QuestionType), - Claims: claims, - MaxIterations: mode.MaxOrchestratorCycles, - } -} - -func directPlan(question string) WorkflowPlan { - return WorkflowPlan{ - PlanType: "direct", - Claims: []ClaimTarget{{ClaimID: "c0", Description: question, Priority: 0}}, - MaxIterations: 1, - } -} - -func planTypeFor(qt string) string { - switch qt { - case "factual": - return "fact_decomposition" - case "comparative": - return "comparative_decomposition" - case "procedural": - return "procedural_decomposition" - default: - return "exploratory_decomposition" - } -} - -func maxClaimsFor(modeLabel string) int { - return map[string]int{"low": 1, "medium": 3, "high": 5, "ultra": 8}[modeLabel] -} - -func detailLevelFor(modeLabel string) string { - return map[string]string{"low": "coarse", "medium": "normal", "high": "fine", "ultra": "extra_fine"}[modeLabel] -} - -func formatSeedChunks(seedChunks []string) string { - if len(seedChunks) == 0 { - return "(no preliminary results)" - } - return strings.Join(seedChunks, "\n") -} - -func orDefault(v, def string) string { - if v == "" { - return def - } - return v -} diff --git a/internal/agent/harness/production.go b/internal/agent/harness/production.go deleted file mode 100644 index d93f5731c20..00000000000 --- a/internal/agent/harness/production.go +++ /dev/null @@ -1,585 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "encoding/json" - "fmt" - "log" - "strings" - "sync" - - einotool "github.com/cloudwego/eino/components/tool" - - "gorm.io/gorm" - "ragflow/internal/agent/tool" - "ragflow/internal/common" - "ragflow/internal/dao" - "ragflow/internal/entity" - modelModule "ragflow/internal/entity/models" - "ragflow/internal/service" - "ragflow/internal/service/nav" - "ragflow/internal/service/wikisearch" -) - -// ProductionRunner wires the real agentic-search tools (hybrid_search, -// dataset_navigation_by_tree, wiki_query) into the RunAgenticRAG flow, so the -// tools are actually invoked rather than merely registered. This is the -// production counterpart to the unit-testable SearchFn seam. -type ProductionRunner struct { - db *gorm.DB - tenantID string - datasetIDs []string - searchTool einotool.InvokableTool - navSvc nav.NavService // defaults to nav.GetNavService() when nil - wikiSvc wikisearch.Service - // webTool is an optional, already-configured web search tool. When nil the - // runner never exposes web fallback (P8: no web provider configured => the - // agent does not attempt web search and no failing tool call is made). - webTool einotool.InvokableTool - // sqlKBs are the tabular (structured) KBs — those whose parser_config carries - // a field_map. structured_query only runs over these (mirrors RAGTools.sql_kbs). - sqlKBs []*entity.Knowledgebase - // fieldMap is the merged field_map across the tabular KBs (mirrors - // RAGTools.field_map). - fieldMap map[string]interface{} - // chatPipeline drives structured_query (useSQL). Lazily constructed, guarded - // by chatPipelineOnce against concurrent runSQLTool calls. - chatPipeline *service.ChatPipelineService - chatPipelineOnce sync.Once - // SystemPrompt, when non-empty, is prepended to the final-answer system - // prompt (mirrors Python RAGTools.system_prompt). - SystemPrompt string -} - -// NewProductionRunner builds a ProductionRunner backed by the real tools. The -// dataset-nav router (harness.NavigateDatasetByTree) resolves its NavService -// lazily via nav.GetNavService(). When a web provider is configured (a Tavily -// API key is present), the runner also wires the web fallback tool so -// high/ultra modes can fill an empty KB result from the web; otherwise no web -// tool is attached and no web call is ever attempted (P8/R2). -func NewProductionRunner(ctx context.Context, db *gorm.DB, tenantID string, datasetIDs []string) (*ProductionRunner, error) { - searchBase, err := tool.BuildByName("hybrid_search", nil) - if err != nil { - return nil, err - } - search, ok := searchBase.(einotool.InvokableTool) - if !ok { - return nil, fmt.Errorf("hybrid_search is not invokable") - } - r := &ProductionRunner{db: db, tenantID: tenantID, datasetIDs: datasetIDs, searchTool: search} - if common.GetEnv(common.EnvTavilyAPIKey) != "" { - r.webTool = tool.NewTavilyTool() - } - // Partition the bound KBs into tabular (field_map-bearing) vs general, - // mirroring Python RAGTools._exclude_sql_kb. Runs under the caller's context - // so request deadlines/cancellation propagate to the lookup. - r.loadSQLKBs(ctx) - return r, nil -} - -// loadSQLKBs partitions the bound KBs into tabular (structured_query) vs general -// and merges their field_map, mirroring Python RAGTools._exclude_sql_kb. -func (r *ProductionRunner) loadSQLKBs(ctx context.Context) { - if r == nil || r.db == nil { - return - } - kbs, err := dao.NewKnowledgebaseDAO().GetByIDs(ctx, r.db, r.datasetIDs) - if err != nil { - // Distinguish a database failure from "no tabular KBs": structured_query - // silently reporting no tabular KBs would otherwise mask this. - log.Printf("agentic_rag: loadSQLKBs lookup failed for %v: %v", r.datasetIDs, err) - return - } - r.fieldMap = map[string]interface{}{} - for _, kb := range kbs { - if kb == nil { - continue - } - if fm, ok := kb.ParserConfig["field_map"].(map[string]interface{}); ok && len(fm) > 0 { - for k, v := range fm { - r.fieldMap[k] = v - } - r.sqlKBs = append(r.sqlKBs, kb) - } - } -} - -// runSQLTool runs structured_query: translate the query to SQL over the tabular -// KBs and return the answer + referenced chunks. Returns empty when there are no -// tabular KBs or no chat model is configured (mirrors Python structured_query's -// sql_kbs guard). -func (r *ProductionRunner) runSQLTool(ctx context.Context, args map[string]interface{}) ToolResult { - if r == nil || len(r.sqlKBs) == 0 || len(r.fieldMap) == 0 { - return ToolResult{} - } - query := stringValue(args["query"]) - if strings.TrimSpace(query) == "" { - return ToolResult{} - } - // Resolve the tenant's default chat model (empty llmID → default). - driver, modelName, apiConfig, _, err := service.NewModelProviderService().GetChatModelConfig(ctx, r.tenantID, "") - if err != nil { - return ToolResult{} - } - chatModel := modelModule.NewChatModel(driver, &modelName, apiConfig) - r.chatPipelineOnce.Do(func() { - r.chatPipeline = service.NewChatPipelineService() - }) - ans, err := r.chatPipeline.StructuredQuery(ctx, &entity.Chat{TenantID: r.tenantID}, r.sqlKBs, query, chatModel, r.fieldMap) - if err != nil || ans == nil { - return ToolResult{} - } - answer := stringValue(ans["answer"]) - ref, _ := ans["reference"].(map[string]interface{}) - var chunks []map[string]interface{} - if ref != nil { - if c, ok := ref["chunks"].([]map[string]interface{}); ok { - chunks = c - } - } - return ToolResult{Answer: answer, Chunks: chunks} -} - -// newProductionRunnerWithTools builds a ProductionRunner with an injected -// search tool and nav service, for unit/E2E tests that want to fake the -// invocation surface without real services. -func newProductionRunnerWithTools(db *gorm.DB, tenantID string, datasetIDs []string, searchTool einotool.InvokableTool, navSvc nav.NavService) *ProductionRunner { - return &ProductionRunner{db: db, tenantID: tenantID, datasetIDs: datasetIDs, searchTool: searchTool, navSvc: navSvc} -} - -// Run executes the agentic-search graph with the real tools. It computes the -// route once and uses it to pick a search strategy: when the route suggests a -// wiki compilation and the bound KBs actually carry wiki artifacts, the runner -// tries wiki_query first and falls back to general hybrid search on an empty -// result; otherwise it uses hybrid search. Web fallback is only reachable when a -// web provider is configured (P8). Returns the final answer. -func (r *ProductionRunner) Run(ctx context.Context, question, keywords, modeLabel, systemPrompt string) AnswerResult { - if r.searchTool == nil { - log.Printf("agentic_rag: production runner not fully wired (search tool missing)") - return AnswerResult{FinalAnswer: emptyResultMessage, Empty: true} - } - route := RouteNode(ctx, r.db, question, modeLabel) - - // Base hybrid search, optionally scoped by the nav router for decomposition - // modes. - searchFn := r.hybridSearchFn(ctx, question, keywords, modeLabel) - - // P8/R4: web fallback is phase-gated — only wired for modes whose - // AvailableTools actually include web_search (high/ultra), AND only when a - // web provider is configured. Low/medium never trigger external web requests - // from an empty KB result. Unconfigured => no web tool call is ever attempted. - if modeAllowsWeb(modeLabel) { - searchFn = r.webFallbackFn(searchFn) - } - - // P5: prefer wiki when the route suggests it AND the bound KBs carry the - // artifact; fall back to hybrid on empty/absent wiki results. - if route.SuggestsCompilation == "wiki" && r.wikiAvailable(ctx) { - searchFn = r.wikiPreferredSearchFn(searchFn) - } - - // high/ultra (agentic_research / deep_research) drive the two-level research - // loop through the Pipeline (real tools + compilation gating + doc routing), - // not the SearchFn closure used by low/medium. This is the P5 strategy - // dispatch: high/ultra is a strict superset of medium. - if route.ExecutionStrategy == "agentic_research" || route.ExecutionStrategy == "deep_research" { - return r.runAgentic(ctx, question, keywords, modeLabel, route, systemPrompt) - } - return RunAgenticRAGWithRoute(ctx, r.db, question, keywords, modeLabel, route, searchFn, systemPrompt) -} - -// runAgentic drives the high/ultra two-level loop over a Pipeline. It shares the -// same route/planner as RunAgenticRAGWithRoute but researches claims via the -// research agent (inner tool loop) rather than a single hybrid search. -func (r *ProductionRunner) runAgentic(ctx context.Context, question, keywords, modeLabel string, route RouteDecision, systemPrompt string) AnswerResult { - mode, _ := GetMode(modeLabel) - if mode.Label == "" { - mode = THINKING_MODES["high"] - } - - kbinfos := &Kbinfos{} - // pre_search grounds the planner (same as the medium path). - chunks, aggs := r.hybridSearchFn(ctx, question, keywords, modeLabel)(ctx, question, keywords) - seed := extractChunkTexts(chunks) - kbinfos.Merge(chunks, aggs) - - plan := PlannerNode(ctx, r.db, route, seed) - claims := make([]*ClaimTarget, len(plan.Claims)) - for i := range plan.Claims { - claims[i] = &plan.Claims[i] - } - - compilation := buildCompilationMap(ctx, r.db, r.tenantID, r.datasetIDs) - pipeline := NewPipeline(r.db, r.tenantID, r.datasetIDs, r, kbinfos, compilation) - - orch := AgenticResearch(ctx, r.db, pipeline, question, claims, mode) - - return FormalizeAnswer(ctx, r.db, question, orch.Kbinfos, orch.PartialAnswer, orch.Abstain, orch.EmptyResult, orch.Caveat, orch.ForceLLM, systemPrompt) -} - -// buildCompilationMap reports which compiled artifacts each bound KB carries, -// so the Pipeline can gate compilation-requiring tools (ontology/mindmap/graph/ -// wiki). It mirrors Python _get_compilation_map (parser_config toggles + dataset -// nav rows). A nil/empty map disables gating (all tools pass through). - -// modeAllowsWeb reports whether the mode's AvailableTools include web_search, so -// web fallback is only reachable in the modes that are supposed to have it -// (high/ultra). Unknown modes are treated as not allowing web. -func modeAllowsWeb(modeLabel string) bool { - mode, ok := GetMode(modeLabel) - if !ok { - return false - } - for _, name := range mode.AvailableTools { - if name == "web_search" { - return true - } - } - return false -} - -// hybridSearchFn builds the base hybrid search closure (optionally doc-scoped -// for decomposition modes). -func (r *ProductionRunner) hybridSearchFn(ctx context.Context, question, keywords, modeLabel string) SearchFn { - searchFn := func(ctx context.Context, query, kws string) ([]map[string]interface{}, []map[string]interface{}) { - return r.search(ctx, query, kws, nil) - } - if mode, _ := GetMode(modeLabel); mode.RequiresDecomposition { - docs := r.routeDocs(ctx, question, keywords) - if len(docs) > 0 { - searchFn = func(ctx context.Context, query, kws string) ([]map[string]interface{}, []map[string]interface{}) { - return r.search(ctx, query, kws, docs) - } - } - } - return searchFn -} - -// wikiPreferredSearchFn wraps the hybrid searchFn so that each search first asks -// the compiled wiki for the query and only falls back to hybrid when the wiki -// returns nothing (or the wiki backend is unavailable). This is the P5 route -// consumption: a wiki suggestion selects the wiki path without discarding the -// hybrid fallback. -func (r *ProductionRunner) wikiPreferredSearchFn(hybrid SearchFn) SearchFn { - return func(ctx context.Context, query, kws string) ([]map[string]interface{}, []map[string]interface{}) { - chunks, aggs := r.wikiSearch(ctx, query, kws) - if len(chunks) > 0 { - return chunks, aggs - } - return hybrid(ctx, query, kws) - } -} - -// wikiAvailable reports whether the bound datasets carry searchable wiki -// artifacts, so the runner only selects the wiki path when it can actually serve. -func (r *ProductionRunner) wikiAvailable(ctx context.Context) bool { - ws := r.wikiSvc - if ws == nil { - ws = wikisearch.GetService() - } - if ws == nil { - return false - } - return ws.AvailableFor(ctx, r.tenantID, r.datasetIDs) -} - -// wikiSearch invokes the wiki_query tool against the compiled wiki. It returns -// empty chunks (never a hard error) when the service is unavailable or yields -// nothing, so the caller falls back to hybrid search. -func (r *ProductionRunner) wikiSearch(ctx context.Context, query, keywords string) ([]map[string]interface{}, []map[string]interface{}) { - ws := r.wikiSvc - if ws == nil { - ws = wikisearch.GetService() - } - if ws == nil || !ws.AvailableFor(ctx, r.tenantID, r.datasetIDs) { - return nil, nil - } - res, err := ws.QueryPages(ctx, r.tenantID, r.datasetIDs, query, keywords, 12) - if err != nil || len(res.Chunks) == 0 { - return nil, nil - } - // P7: backfill the original source chunks referenced by the compiled page - // hits, deduped and bounded, so the answer can cite raw evidence. - return r.expandCompiledEvidence(ctx, res.Chunks, res.DocAggs) -} - -// search invokes the hybrid_search tool and normalizes its chunk output. -func (r *ProductionRunner) search(ctx context.Context, query, keywords string, docScope []string) ([]map[string]interface{}, []map[string]interface{}) { - args := map[string]interface{}{"query": query, "keywords": keywords, "kb_ids": r.datasetIDs, "top_n": 12} - if len(docScope) > 0 { - args["doc_scope"] = docScope - } - raw, err := r.searchTool.InvokableRun(ctx, mustJSON(args)) - if err != nil { - log.Printf("agentic_rag: hybrid_search failed: %v", err) - return nil, nil - } - var res struct { - Chunks []map[string]interface{} `json:"chunks"` - } - if err := json.Unmarshal([]byte(raw), &res); err != nil { - return nil, nil - } - return res.Chunks, nil -} - -// expandCompiledEvidence backfills the ORIGINAL source chunks a compiled-page -// hit was built from (P7/R3). It collects the page hits' source_chunk_ids -// (bounded per page and in total), then asks the concrete wiki service to fetch -// them BY ID — scoped to the tenant + datasets — so the answer can cite raw -// evidence. When the page hits carry no source ids, the service is unavailable, -// or none of the ids resolve, the page results are kept as-is (safe degradation; -// nothing is fabricated). -func (r *ProductionRunner) expandCompiledEvidence(ctx context.Context, chunks, aggs []map[string]interface{}) ([]map[string]interface{}, []map[string]interface{}) { - if len(chunks) == 0 { - return chunks, aggs - } - ws := r.wikiSvc - if ws == nil { - ws = wikisearch.GetService() - } - if ws == nil { - return chunks, aggs - } - const maxEvidencePerPage = 4 - const maxEvidenceTotal = 12 - - // Collect bounded source-chunk ids from the page hits (deduped, in page - // order), grouped by dataset so the backfill stays within each KB's scope. - var sourceIDs []string - seen := map[string]bool{} - datasets := map[string]bool{} - for _, c := range chunks { - if len(sourceIDs) >= maxEvidenceTotal { - break - } - ids := stringSlice(c["source_chunk_ids"]) - count := 0 - for _, id := range ids { - if count >= maxEvidencePerPage { - break - } - if id == "" || seen[id] { - continue - } - seen[id] = true - count++ - sourceIDs = append(sourceIDs, id) - if ds := stringValue(c["dataset_id"]); ds != "" { - datasets[ds] = true - } - if len(sourceIDs) >= maxEvidenceTotal { - break - } - } - } - if len(sourceIDs) == 0 { - return chunks, aggs - } - // Scope the backfill to the page hits' datasets (fall back to all bound - // datasets when the page hits carry none). Build a fresh slice: never mutate - // r.datasetIDs. - scope := make([]string, 0, len(r.datasetIDs)) - if len(datasets) == 0 { - scope = append(scope, r.datasetIDs...) - } else { - for ds := range datasets { - scope = append(scope, ds) - } - } - evidence, err := ws.BackfillChunks(ctx, r.tenantID, scope, sourceIDs) - if err != nil || len(evidence) == 0 { - return chunks, aggs - } - - // Stable merge: page results first (in retrieval order), then the backfilled - // evidence, deduped by chunk key. - merged := append([]map[string]interface{}(nil), chunks...) - keys := map[string]bool{} - for _, c := range chunks { - if k := chunkKey(c); k != "" { - keys[k] = true - } - } - for _, e := range evidence { - k := chunkKey(e) - if k != "" && !keys[k] { - keys[k] = true - merged = append(merged, e) - } - } - // Doc aggs: union the page doc aggs with the evidence docs. - dseen := map[string]bool{} - for _, d := range aggs { - if id, _ := d["doc_id"].(string); id != "" { - dseen[id] = true - } - } - for _, e := range evidence { - id := stringValue(e["doc_id"]) - if id == "" { - continue - } - if !dseen[id] { - dseen[id] = true - aggs = append(aggs, map[string]interface{}{"doc_id": id, "doc_name": stringValue(e["docnm_kwd"])}) - } - } - return merged, aggs -} - -// webFallbackFn wraps a SearchFn so that, when the KB search returns nothing, a -// configured web provider is invoked to fill the gap (P8). It is only used when -// webTool is non-nil; otherwise it returns the hybrid path unchanged and no web -// tool call is ever attempted (no failing call when unconfigured). -func (r *ProductionRunner) webFallbackFn(hybrid SearchFn) SearchFn { - if r.webTool == nil { - return hybrid - } - return func(ctx context.Context, query, kws string) ([]map[string]interface{}, []map[string]interface{}) { - chunks, aggs := hybrid(ctx, query, kws) - if len(chunks) > 0 { - return chunks, aggs - } - raw, err := r.webTool.InvokableRun(ctx, mustJSON(map[string]interface{}{"query": query, "keywords": kws})) - if err != nil { - return nil, nil - } - out := normalizeWebResults([]byte(raw)) - if len(out) == 0 { - return nil, nil - } - return out, nil - } -} - -// normalizeWebResults parses the web provider's raw JSON and normalizes it into -// the same agentic evidence shape as KB chunks. Accepts both the agent "chunks" -// envelope and the Tavily "results" envelope (tavily.go returns -// {"results":[...]}); each result contributes content + a doc_id reference so -// the answer can retain the source URL. -func normalizeWebResults(raw []byte) []map[string]interface{} { - var res struct { - Chunks []map[string]interface{} `json:"chunks"` - Results []map[string]interface{} `json:"results"` - } - if err := json.Unmarshal(raw, &res); err != nil { - return nil - } - src := res.Chunks - if len(src) == 0 { - src = res.Results - } - out := make([]map[string]interface{}, 0, len(src)) - for i, c := range src { - url := firstNonEmpty(stringValue(c["url"]), stringValue(c["link"]), stringValue(c["source"])) - if url == "" { - continue - } - content := firstNonEmpty(stringValue(c["content"]), stringValue(c["raw_content"]), stringValue(c["text"])) - if content == "" { - continue - } - docID := stringValue(c["doc_id"]) - if docID == "" { - docID = url - } - // doc_id stays the source URL; chunk_id must be UNIQUE per snippet so - // Kbinfos.Merge (dedup by chunkKey) does not collapse several snippets - // from the same URL, or the same URL across two retrieval rounds. - chunkID := fmt.Sprintf("%s#%d", docID, i) - out = append(out, map[string]interface{}{ - "chunk_id": chunkID, "content_with_weight": content, - "doc_id": docID, "docnm_kwd": firstNonEmpty(stringValue(c["title"]), stringValue(c["source"])), - "dataset_id": stringValue(c["dataset_id"]), "url": url, "source": "web", - }) - } - return out -} - -func stringValue(v interface{}) string { - if s, ok := v.(string); ok { - return s - } - return "" -} - -func firstNonEmpty(ss ...string) string { - for _, s := range ss { - if strings.TrimSpace(s) != "" { - return s - } - } - return "" -} - -func stringSlice(v interface{}) []string { - if raw, ok := v.([]string); ok { - return raw - } - arr, ok := v.([]interface{}) - if !ok { - return nil - } - out := make([]string, 0, len(arr)) - for _, item := range arr { - if s, ok := item.(string); ok { - out = append(out, s) - } - } - return out -} - -// routeDocs derives the doc scope via the canonical dataset-nav router -// (harness.NavigateDatasetByTree — the full LLM two-round selection). It routes -// across ALL bound datasets and merges the doc ids, so every KB contributes its -// own relevant docs to the shared scope (a multi-KB session must not collapse to -// the first KB only). -func (r *ProductionRunner) routeDocs(ctx context.Context, topic, keywords string) []string { - ns := r.navSvc - if ns == nil { - ns = nav.GetNavService() - } - if ns == nil { - log.Printf("agentic_rag: dataset nav service not initialized; skipping doc routing") - return nil - } - // Combine topic + keywords into the routing query so the nav router actually - // uses the full user signal (keywords must not be dropped). - query := strings.TrimSpace(topic + " " + keywords) - seen := map[string]bool{} - var docs []string - for _, kbID := range r.datasetIDs { - for _, id := range NavigateDatasetByTree(ctx, r.db, ns, r.tenantID, kbID, query) { - if id != "" && !seen[id] { - seen[id] = true - docs = append(docs, id) - } - } - } - return docs -} - -func mustJSON(v interface{}) string { - b, err := json.Marshal(v) - if err != nil { - return "{}" - } - return string(b) -} diff --git a/internal/agent/harness/production_test.go b/internal/agent/harness/production_test.go deleted file mode 100644 index 48ffcd3c8aa..00000000000 --- a/internal/agent/harness/production_test.go +++ /dev/null @@ -1,144 +0,0 @@ -package harness - -import ( - "context" - "strings" - "sync" - "testing" - - einotool "github.com/cloudwego/eino/components/tool" - "github.com/cloudwego/eino/schema" - "gorm.io/gorm" - - "ragflow/internal/agent/component" - "ragflow/internal/service/nav" -) - -// routeChat returns a model-style response depending on the stage: nav-selection -// calls return {"relevant":[...]}, all other calls return a plain final answer. -type routeChat struct{} - -func (routeChat) Invoke(_ context.Context, _ *gorm.DB, req component.ChatInvokeRequest) (*component.ChatInvokeResponse, error) { - content := "" - msg := "" - if len(req.Messages) > 0 { - msg = req.Messages[len(req.Messages)-1].Content - } - switch { - case strings.Contains(msg, "(numbered)") || strings.Contains(msg, "Entities"): - // nav-select pass: keep every item (all relevant). - content = `{"relevant":[0,1,2,3,4,5,6,7,8,9]}` - default: - content = "final scoped answer" - } - return &component.ChatInvokeResponse{Content: content}, nil -} - -// installRouteChat installs the stage-aware chat invoker for E2E tests. -func installRouteChat(t *testing.T) { - t.Helper() - component.SetDefaultChatInvoker(routeChat{}) - t.Cleanup(func() { component.SetDefaultChatInvoker(nil) }) -} - -// fakeInvokableTool is an einotool.InvokableTool double for E2E testing. -type fakeInvokableTool struct { - name string - fn func(ctx context.Context, argsJSON string) string - mu sync.Mutex - lastArgs string -} - -func (f *fakeInvokableTool) Info(_ context.Context) (*schema.ToolInfo, error) { - return &schema.ToolInfo{Name: f.name}, nil -} - -func (f *fakeInvokableTool) InvokableRun(ctx context.Context, argsJSON string, _ ...einotool.Option) (string, error) { - f.mu.Lock() - f.lastArgs = argsJSON - f.mu.Unlock() - return f.fn(ctx, argsJSON), nil -} - -func (f *fakeInvokableTool) args() string { - f.mu.Lock() - defer f.mu.Unlock() - return f.lastArgs -} - -// TestProductionRunner_E2E_RouteToScopedSearch proves the chain -// "user question → dataset nav routes doc scope → hybrid_search retrieval is -// scoped to those docs". It injects a fake nav service (returns docs d1,d2) and -// asserts the search tool receives doc_scope=[d1,d2]. -func TestProductionRunner_E2E_RouteToScopedSearch(t *testing.T) { - installRouteChat(t) - - // Fake nav service whose two-round router returns docs d1,d2. - navSvc := &fakeNavSvcHarness{ - clusters: []nav.NavNode{{Name: "C1", Description: "cluster"}}, - children: map[string][]nav.NavNode{ - "C1": { - {Name: "DocA", Type: "doc", DocID: "d1"}, - {Name: "DocB", Type: "doc", DocID: "d2"}, - }, - }, - } - // AskNavSelect returns all items (both docs) for the doc-select pass. - searchTool := &fakeInvokableTool{name: "hybrid_search", fn: func(_ context.Context, _ string) string { - return `{"chunks":[{"chunk_id":"c1","content_with_weight":"scoped evidence"}]}` - }} - - // Multi-KB session: routing must cover every bound dataset, not just the - // first KB. - runner := newProductionRunnerWithTools(nil, "t1", []string{"kb1", "kb2"}, searchTool, navSvc) - res := runner.Run(t.Context(), "Compare A and B", "", "medium", "") - - if res.FinalAnswer != "final scoped answer" { - t.Errorf("final answer = %q, want chat output", res.FinalAnswer) - } - // The search tool must receive doc_scope=[d1,d2] — the docs the nav router - // selected — proving retrieval is scoped to those docs across KBs. - if !strings.Contains(searchTool.args(), `"doc_scope":["d1","d2"]`) { - t.Errorf("hybrid_search not scoped to routed docs; args=%s", searchTool.args()) - } - // The search tool must receive all bound KBs (not collapsed to one). - if !strings.Contains(searchTool.args(), `"kb_ids":["kb1","kb2"]`) { - t.Errorf("hybrid_search kb_ids must include all bound KBs; args=%s", searchTool.args()) - } -} - -// TestProductionRunner_E2E_NoRoute_SearchUnscoped asserts low mode (no -// decomposition) skips nav routing and searches without a doc_scope. -func TestProductionRunner_E2E_NoRoute_SearchUnscoped(t *testing.T) { - installRouteChat(t) - searchTool := &fakeInvokableTool{name: "hybrid_search", fn: func(_ context.Context, _ string) string { - return `{"chunks":[{"chunk_id":"c1","content_with_weight":"evidence"}]}` - }} - // A nav service is provided but must NOT be consulted in low mode. - navSvc := &fakeNavSvcHarness{clusters: []nav.NavNode{{Name: "C1"}}} - runner := newProductionRunnerWithTools(nil, "t1", []string{"kb1"}, searchTool, navSvc) - res := runner.Run(t.Context(), "What is X?", "", "low", "") - - if res.FinalAnswer == "" { - t.Error("expected a final answer in low mode") - } - if strings.Contains(searchTool.args(), "doc_scope") { - t.Errorf("low mode search should have no doc_scope; args=%s", searchTool.args()) - } -} - -// TestProductionRunner_E2E_EmptyRoute_SearchUnscoped asserts an empty doc route -// falls back to an unscoped search (no hard failure). -func TestProductionRunner_E2E_EmptyRoute_SearchUnscoped(t *testing.T) { - installRouteChat(t) - searchTool := &fakeInvokableTool{name: "hybrid_search", fn: func(_ context.Context, _ string) string { - return `{"chunks":[{"chunk_id":"c1","content_with_weight":"evidence"}]}` - }} - // Nav service with no clusters -> empty route. - navSvc := &fakeNavSvcHarness{clusters: nil} - runner := newProductionRunnerWithTools(nil, "t1", []string{"kb1"}, searchTool, navSvc) - res := runner.Run(t.Context(), "Compare A and B", "", "medium", "") - if res.FinalAnswer == "" { - t.Error("expected an answer even when nav routing returns no docs") - } -} diff --git a/internal/agent/harness/production_wiki_test.go b/internal/agent/harness/production_wiki_test.go deleted file mode 100644 index 764583dc2e1..00000000000 --- a/internal/agent/harness/production_wiki_test.go +++ /dev/null @@ -1,276 +0,0 @@ -package harness - -import ( - "context" - "strings" - "sync" - "testing" - - "gorm.io/gorm" - - "ragflow/internal/agent/component" - "ragflow/internal/service/wikisearch" -) - -// fakeWikiSvcHarness is a deterministic wikisearch.Service double for the -// production runner. -type fakeWikiSvcHarness struct { - available bool - // pages are pre-shaped page chunks (map form) returned by QueryPages. - pages []map[string]interface{} - // backfill maps chunk id -> evidence content for BackfillChunks. - backfill map[string]string - calls []string - queryCount int - mu sync.Mutex -} - -func (f *fakeWikiSvcHarness) AvailableFor(_ context.Context, _ string, _ []string) bool { - return f.available -} - -func (f *fakeWikiSvcHarness) QueryPages(_ context.Context, _ string, _ []string, query, _ string, _ int) (wikisearch.SearchResult, error) { - f.mu.Lock() - f.queryCount++ - f.calls = append(f.calls, query) - f.mu.Unlock() - res := wikisearch.SearchResult{Chunks: append([]map[string]interface{}(nil), f.pages...), DocAggs: []map[string]interface{}{}} - for _, c := range res.Chunks { - if docID, _ := c["doc_id"].(string); docID != "" { - res.DocAggs = append(res.DocAggs, map[string]interface{}{"doc_id": docID, "doc_name": c["docnm_kwd"]}) - } - } - return res, nil -} - -func (f *fakeWikiSvcHarness) seenQueries() []string { - f.mu.Lock() - defer f.mu.Unlock() - return append([]string(nil), f.calls...) -} - -// backfill is the fake's per-id evidence map (chunk id -> content). -func (f *fakeWikiSvcHarness) BackfillChunks(_ context.Context, _ string, _ []string, chunkIDs []string) ([]map[string]interface{}, error) { - out := make([]map[string]interface{}, 0, len(chunkIDs)) - for _, id := range chunkIDs { - content, ok := f.backfill[id] - if !ok { - continue - } - out = append(out, map[string]interface{}{ - "chunk_id": id, "content_with_weight": content, "doc_id": "d1", "docnm_kwd": "Doc", "dataset_id": "kb1", - }) - } - return out, nil -} - -// wikiRouteChat returns a route JSON suggesting wiki for the route stage and a -// plain final answer otherwise. -type wikiRouteChat struct{} - -func (wikiRouteChat) Invoke(_ context.Context, _ *gorm.DB, req component.ChatInvokeRequest) (*component.ChatInvokeResponse, error) { - // The route stage carries the route prompt (with "suggests_compilation") as - // a system message; detect it across any message (system or user). - isRoute := false - for _, m := range req.Messages { - if strings.Contains(m.Content, "suggests_compilation") { - isRoute = true - break - } - } - if isRoute { - return &component.ChatInvokeResponse{Content: `{"question_type":"analytical","requires_decomposition":false,"suggests_compilation":"wiki"}`}, nil - } - return &component.ChatInvokeResponse{Content: "final wiki answer"}, nil -} - -func installWikiRouteChat(t *testing.T) { - t.Helper() - component.SetDefaultChatInvoker(wikiRouteChat{}) - t.Cleanup(func() { component.SetDefaultChatInvoker(nil) }) -} - -// TestProductionRunner_WikiPreferred_WhenSuggested drives a low-mode run with a -// wiki suggestion and an available wiki service, and asserts the wiki service is -// queried (P5: route suggestion selects the wiki path). -func TestProductionRunner_WikiPreferred_WhenSuggested(t *testing.T) { - installWikiRouteChat(t) - hybrid := &fakeInvokableTool{name: "hybrid_search", fn: func(_ context.Context, _ string) string { - return `{"chunks":[]}` - }} - wikiSvc := &fakeWikiSvcHarness{available: true, pages: []map[string]interface{}{ - {"chunk_id": "wiki/entity/alpha", "content_with_weight": "# Alpha", "doc_id": "kb1", "docnm_kwd": "Alpha", "wiki_slug_kwd": "entity/alpha", "dataset_id": "kb1"}, - }} - runner := newProductionRunnerWithTools(nil, "t1", []string{"kb1"}, hybrid, nil) - runner.wikiSvc = wikiSvc - res := runner.Run(t.Context(), "What is Alpha?", "", "low", "") - if res.FinalAnswer != "final wiki answer" { - t.Errorf("final answer = %q, want wiki chat output", res.FinalAnswer) - } - if len(wikiSvc.seenQueries()) == 0 { - t.Errorf("wiki service was not queried despite a wiki suggestion") - } -} - -// TestProductionRunner_WikiEmpty_FallsBackToHybrid asserts that when the wiki -// service yields nothing, the runner falls back to hybrid search (P5 must not -// discard the general retrieval fallback). -func TestProductionRunner_WikiEmpty_FallsBackToHybrid(t *testing.T) { - installWikiRouteChat(t) - hybrid := &fakeInvokableTool{name: "hybrid_search", fn: func(_ context.Context, _ string) string { - return `{"chunks":[{"chunk_id":"c1","content_with_weight":"hybrid evidence"}]}` - }} - wikiSvc := &fakeWikiSvcHarness{available: true} // no pages - runner := newProductionRunnerWithTools(nil, "t1", []string{"kb1"}, hybrid, nil) - runner.wikiSvc = wikiSvc - res := runner.Run(t.Context(), "What is Alpha?", "", "low", "") - if len(wikiSvc.seenQueries()) == 0 { - t.Errorf("wiki service should have been attempted") - } - if !strings.Contains(hybrid.args(), `"query":"What is Alpha?"`) { - t.Errorf("hybrid fallback was not invoked after empty wiki; args=%s", hybrid.args()) - } - if res.FinalAnswer == "" { - t.Errorf("expected a final answer from the hybrid fallback") - } -} - -// TestProductionRunner_NoWikiWithoutSuggestion asserts the wiki service is NOT -// queried when the route does not suggest wiki. -func TestProductionRunner_NoWikiWithoutSuggestion(t *testing.T) { - // route chat returns no suggestion for a generic route call - installRouteChat(t) // routeChat returns plain text -> route falls back (no suggestion) - hybrid := &fakeInvokableTool{name: "hybrid_search", fn: func(_ context.Context, _ string) string { - return `{"chunks":[{"chunk_id":"c1","content_with_weight":"evidence"}]}` - }} - wikiSvc := &fakeWikiSvcHarness{available: true, pages: []map[string]interface{}{ - {"chunk_id": "wiki/s", "content_with_weight": "c", "doc_id": "kb1", "docnm_kwd": "T", "wiki_slug_kwd": "s", "dataset_id": "kb1"}, - }} - runner := newProductionRunnerWithTools(nil, "t1", []string{"kb1"}, hybrid, nil) - runner.wikiSvc = wikiSvc - runner.Run(t.Context(), "What is Alpha?", "", "low", "") - if len(wikiSvc.seenQueries()) != 0 { - t.Errorf("wiki service must not be queried without a wiki suggestion; calls=%v", wikiSvc.seenQueries()) - } -} - -// TestProductionRunner_WebFallback_UnconfiguredIsNoop asserts that with no web -// tool configured the runner never attempts a web call (P8 gate). -func TestProductionRunner_WebFallback_UnconfiguredIsNoop(t *testing.T) { - webTool := &fakeInvokableTool{name: "web_search", fn: func(_ context.Context, _ string) string { - return `{"chunks":[{"chunk_id":"w1","content_with_weight":"web evidence"}]}` - }} - hybrid := &fakeInvokableTool{name: "hybrid_search", fn: func(_ context.Context, _ string) string { - return `{"chunks":[]}` - }} - // webTool is NOT set on the runner -> the runner must not invoke it. - runner := newProductionRunnerWithTools(nil, "t1", []string{"kb1"}, hybrid, nil) - // With webTool nil, webFallbackFn returns the hybrid path unchanged, so the - // web tool is never called. - fn := runner.webFallbackFn(func(ctx context.Context, q, k string) ([]map[string]interface{}, []map[string]interface{}) { - return nil, nil - }) - chunks, _ := fn(t.Context(), "q", "k") - if len(chunks) != 0 { - t.Errorf("expected no chunks from the no-web fallback path") - } - if webTool.args() != "" { - t.Errorf("web tool must not be called when unconfigured; args=%s", webTool.args()) - } -} - -// TestProductionRunner_WebFallback_TavilyResultsNormalized asserts R2: the web -// fallback consumes the Tavily `{"results":[...]}` envelope (tavily.go contract) -// and normalizes each result into an agent evidence chunk with a doc_id -// reference, not the agent `chunks` shape. -func TestProductionRunner_WebFallback_TavilyResultsNormalized(t *testing.T) { - webTool := &fakeInvokableTool{name: "web_search", fn: func(_ context.Context, _ string) string { - return `{"results":[{"title":"Alpha docs","url":"https://example.com/x","content":"web evidence body","source":"example.com"}]}` - }} - runner := newProductionRunnerWithTools(nil, "t1", []string{"kb1"}, nil, nil) - runner.webTool = webTool - fn := runner.webFallbackFn(func(ctx context.Context, q, k string) ([]map[string]interface{}, []map[string]interface{}) { - return nil, nil - }) - chunks, _ := fn(t.Context(), "q", "k") - if len(chunks) != 1 { - t.Fatalf("chunks = %d, want 1 normalized Tavily result", len(chunks)) - } - if chunks[0]["content_with_weight"] != "web evidence body" { - t.Errorf("content = %v, want web evidence body", chunks[0]["content_with_weight"]) - } - if chunks[0]["doc_id"] == "" || !strings.Contains(chunks[0]["doc_id"].(string), "https://example.com/x") { - t.Errorf("doc_id must reference the source url: %v", chunks[0]["doc_id"]) - } - if chunks[0]["source"] != "web" { - t.Errorf("source = %v, want web", chunks[0]["source"]) - } - if webTool.args() == "" { - t.Errorf("web tool was not invoked when hybrid was empty") - } -} - -// TestModeAllowsWeb asserts R4 gating: only modes whose AvailableTools include -// web_search (high/ultra) allow web fallback; low/medium/unknown do not. -func TestModeAllowsWeb(t *testing.T) { - if !modeAllowsWeb("high") || !modeAllowsWeb("ultra") { - t.Errorf("high/ultra must allow web search") - } - for _, m := range []string{"low", "medium", "fast", "unknown"} { - if modeAllowsWeb(m) { - t.Errorf("mode %q must NOT allow web search", m) - } - } -} - -// TestProductionRunner_CompiledEvidenceExpansion asserts P7/R3: page hits -// carrying source_chunk_ids get the ORIGINAL chunks fetched by id (via the wiki -// service BackfillChunks) appended after the page results, deduped. -func TestProductionRunner_CompiledEvidenceExpansion(t *testing.T) { - wikiSvc := &fakeWikiSvcHarness{available: true, backfill: map[string]string{"c1": "raw chunk 1", "c2": "raw chunk 2"}} - runner := newProductionRunnerWithTools(nil, "t1", []string{"kb1"}, nil, nil) - runner.wikiSvc = wikiSvc - chunks := []map[string]interface{}{ - { - "chunk_id": "wiki/s", "content_with_weight": "# Page", "doc_id": "d1", "docnm_kwd": "Page", "dataset_id": "kb1", - "source_chunk_ids": []interface{}{"c1", "c2"}, - }, - } - merged, aggs := runner.expandCompiledEvidence(t.Context(), chunks, []map[string]interface{}{}) - if len(merged) != 3 { - t.Fatalf("merged = %d, want 3 (page + 2 backfilled evidence chunks)", len(merged)) - } - if merged[0]["chunk_id"] != "wiki/s" || merged[1]["chunk_id"] != "c1" || merged[2]["chunk_id"] != "c2" { - t.Errorf("merge order wrong: %v", merged) - } - if merged[1]["content_with_weight"] != "raw chunk 1" { - t.Errorf("evidence chunk content = %v, want raw chunk 1 (by-id backfill)", merged[1]["content_with_weight"]) - } - // Doc aggs must include the evidence doc. - found := false - for _, d := range aggs { - if d["doc_id"] == "d1" { - found = true - } - } - if !found { - t.Errorf("evidence doc not unioned into doc aggs: %v", aggs) - } -} - -// TestProductionRunner_CompiledEvidence_NoServiceIsNoop asserts P7/R3 degrades -// safely: when the wiki service is unavailable, page hits (even with -// source_chunk_ids) keep the page results unchanged and fabricate nothing. -func TestProductionRunner_CompiledEvidence_NoServiceIsNoop(t *testing.T) { - runner := newProductionRunnerWithTools(nil, "t1", []string{"kb1"}, nil, nil) // wikiSvc nil - chunks := []map[string]interface{}{ - {"chunk_id": "wiki/s", "content_with_weight": "# Page", "dataset_id": "kb1", "source_chunk_ids": []interface{}{"c1", "c2"}}, - } - merged, _ := runner.expandCompiledEvidence(t.Context(), chunks, []map[string]interface{}{}) - if len(merged) != 1 { - t.Fatalf("merged = %d, want 1 (no service => no fabricated evidence)", len(merged)) - } - if merged[0]["chunk_id"] != "wiki/s" { - t.Errorf("page result changed: %v", merged[0]) - } -} diff --git a/internal/agent/harness/research_agent.go b/internal/agent/harness/research_agent.go deleted file mode 100644 index cbfc5b12bc2..00000000000 --- a/internal/agent/harness/research_agent.go +++ /dev/null @@ -1,461 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "encoding/json" - "fmt" - "regexp" - "strings" - - "github.com/cloudwego/eino/schema" - - "gorm.io/gorm" - "ragflow/internal/agent/chat" -) - -// Research agent — inner tool-calling loop for high/ultra modes (mirrors Python -// harness/agent.py research_agent_loop + _research_text). The Go chat invoker has -// no native bind_tools, so we implement the *text-fallback* path: the tools are -// described in the prompt and the model emits `` JSON that the loop -// parses and routes to the harness Pipeline. generate_report is captured (not -// executed) and returned as the claim result. - -// Tool-call extraction patterns, compiled once at package scope. The (?s) flag -// makes `.` match newlines so a multi-line JSON body (as the prompt shows for -// generate_report) still parses. -var ( - reToolCallTag = regexp.MustCompile(`(?s)(.*?)`) - reToolCallFence = regexp.MustCompile("(?s)```(?:json)?\\s*(\\{.*?\\})\\s*```") - reToolCallBare = regexp.MustCompile(`\{\s*"name"\s*:`) -) - -// researchAgentTextPrompt mirrors rag/prompts/research_agent_prompt.py -// RESEARCH_AGENT_TEXT_PROMPT. -const researchAgentTextPrompt = `You are a research assistant. For the given research task, use the available tools to search for information. - -Research task: %s - -Current phase: %s -Phase hint: %s - -Available tools: -%s - -Rules: -1. Go coarse-to-fine: first narrow the corpus with navigation tools, then search only if needed. -2. After a navigation tool returns passages, judge whether they already answer the task. - If they do, call generate_report immediately instead of searching further. -3. Only use hybrid_search / broad search tools when navigation did not yield sufficient evidence. -4. Use think_tool to analyze results after each step. -5. When you are confident enough to answer the research task, call generate_report. - -ATTRIBUTE FIDELITY (CRITICAL): -Answer the EXACT attribute/relation the research task asks for. Do NOT substitute a similar -but different attribute (e.g. do not report HOMETOWN as BIRTHPLACE, do not swap "first" for -"largest", "age at death" for "birth year"). In SEARCH queries you MAY use synonymous, -translated, or corpus-specific terms as long as they still TARGET the exact requested -attribute. The REPORT must state the exact attribute asked for and never present a different -attribute's value as the answer. If the exact attribute cannot be found in evidence, mark the -claim unverified and list it in gaps. - -SOURCE ANCHORING (CRITICAL): -If the research task names a specific source, treat THAT named source as authoritative and -retrieve the value from it. Do NOT substitute another source's value as the answer. If the -named source is found, its value wins. Only if it cannot be located may you fall back, and -then say so in the report and lower confidence. - -Tool call format: output exactly one JSON tool call per round: -{"name": "tool_name", "arguments": {"parameter_name": "value"}} - -generate_report argument format: -{ - "report": "Research result report, factual and unformatted", - "is_verified": true/false, - "confidence": 0.0-1.0, - "evidence_ids": [0, 3], - "gaps": ["Information that was not found"], - "grounded": ["answer-critical fact verbatim from evidence"], - "numbers": ["
from "], - "discovered_claims": ["New research directions discovered during research"] -} - -Maximum %d rounds. Output one tag in each round and no other text.` - -// navChunkTools mirror Python _NAV_CHUNK_TOOLS: navigation tools that return -// passages, after which we judge sufficiency before broadening into a search. -var navChunkTools = map[string]bool{"ontology_navigate": true, "mindmap_navigate": true} - -// researchReport is the normalized generate_report output (mirrors Python -// _generate_report_schema fields). -type researchReport struct { - Report string `json:"report"` - IsVerified bool `json:"is_verified"` - Confidence float64 `json:"confidence"` - EvidenceIDs []int `json:"evidence_ids"` - Gaps []string `json:"gaps"` - Grounded []string `json:"grounded"` - Numbers []string `json:"numbers"` - DiscoveredClaims []string `json:"discovered_claims"` -} - -// researchSession accumulates evidence ids across a single claim's tool loop -// (mirrors Python ResearchToolSession). -type researchSession struct { - pipeline *Pipeline - evidenceIDs []int - seenIDs map[int]bool -} - -// runTool executes one tool call through the pipeline and records evidence. -func (s *researchSession) runTool(ctx context.Context, db *gorm.DB, name string, args map[string]interface{}) (string, bool) { - res := s.pipeline.Execute(ctx, name, args) - if res.Error != "" { - return "[tool error] " + res.Error, false - } - // Record the GLOBAL indices Execute captured under mu, so evidence_ids stay - // stable across concurrent claims (re-indexing the shared slice after the - // lock is released would race with other goroutines' merges). - if len(res.EvidenceIndices) > 0 { - s.recordEvidence(res.EvidenceIndices) - } - return formatToolResult(res), len(res.Chunks) > 0 -} - -// recordEvidence records the global evidence indices Execute already resolved, -// de-duplicating against this session's seen set. -func (s *researchSession) recordEvidence(indices []int) { - for _, idx := range indices { - if s.seenIDs[idx] { - continue - } - s.seenIDs[idx] = true - s.evidenceIDs = append(s.evidenceIDs, idx) - } -} - -// formatToolResult mirrors Python _fmt_tool_result: surface the direct answer -// and up to 6 chunks ordered by similarity, truncated. -func formatToolResult(res ToolResult) string { - parts := []string{} - if res.Answer != "" { - parts = append(parts, "Answer: "+res.Answer) - } - chunks := append([]map[string]interface{}(nil), res.Chunks...) - // Sort by similarity descending (best matches first). - for i := 0; i < len(chunks); i++ { - for j := i + 1; j < len(chunks); j++ { - if chunkSim(chunks[j]) > chunkSim(chunks[i]) { - chunks[i], chunks[j] = chunks[j], chunks[i] - } - } - } - for i, c := range chunks { - if i >= 6 { - break - } - text := chunkText(c) - if text == "" { - continue - } - if len(text) > 300 { - text = text[:300] - } - parts = append(parts, text) - } - if len(parts) == 0 { - return "[no results found]" - } - return strings.Join(parts, "\n\n") -} - -func chunkSim(c map[string]interface{}) float64 { - if v, ok := c["similarity"].(float64); ok { - return v - } - if v, ok := c["similarity"].(float32); ok { - return float64(v) - } - return 0 -} - -// ResearchAgentLoop runs the inner tool loop for one claim (mirrors Python -// research_agent_loop → _research_text). It returns the claim result as an -// AgentResult. -func ResearchAgentLoop(ctx context.Context, db *gorm.DB, pipeline *Pipeline, claim ClaimTarget, mode ExecutionStrategy, followups []string) AgentResult { - inv := chat.GetDefaultInvoker() - if inv == nil { - return AgentResult{ClaimID: claim.ClaimID, IsVerified: false, Confidence: 0, Gaps: []string{"no chat invoker configured"}} - } - - phase := determinePhase(pipeline) - phaseHint := phaseHintFor(phase) - toolList := formatToolList(pipeline.AvailableTools(mode.AvailableTools)) - - system := fmt.Sprintf(researchAgentTextPrompt, - claim.Description, phase, phaseHint, toolList, mode.MaxAgentCycles) - - history := []schema.Message{} - if len(followups) > 0 { - history = append(history, schema.Message{Role: schema.User, Content: "Previous evidence was incomplete. Run targeted searches specifically for the following missing pieces:\n- " + strings.Join(followups, "\n- ")}) - } - - session := &researchSession{pipeline: pipeline, seenIDs: map[int]bool{}} - - for cycle := 0; cycle < mode.MaxAgentCycles; cycle++ { - if err := ctx.Err(); err != nil { - return AgentResult{ClaimID: claim.ClaimID, IsVerified: false, Confidence: 0, Gaps: []string{"research cancelled: " + err.Error()}} - } - msgs := make([]schema.Message, 0, len(history)+1) - msgs = append(msgs, schema.Message{Role: schema.System, Content: system}) - msgs = append(msgs, history...) - resp, err := inv.Invoke(ctx, db, chat.Request{ - Messages: msgs, - Temperature: floatPtr(0.3), - }) - if err != nil { - if ctx.Err() != nil { - return AgentResult{ClaimID: claim.ClaimID, IsVerified: false, Confidence: 0, Gaps: []string{"research cancelled: " + ctx.Err().Error()}} - } - continue - } - ans := resp.Content - history = append(history, schema.Message{Role: schema.Assistant, Content: ans}) - - toolCall := parseToolCall(ans) - if toolCall == nil { - history = append(history, schema.Message{Role: schema.User, Content: "Please call a tool. Do not output plain text."}) - continue - } - - name, _ := toolCall["name"].(string) - if name == "generate_report" { - args, _ := toolCall["arguments"].(map[string]interface{}) - return reportToAgentResult(claim.ClaimID, args, session.evidenceIDs) - } - if name == "think_tool" { - history = append(history, schema.Message{Role: schema.User, Content: "[continue]"}) - continue - } - - args, _ := toolCall["arguments"].(map[string]interface{}) - resultText, gotEvidence := session.runTool(ctx, db, name, args) - // Post-navigation sufficiency gate: steer to finalize when nav passages - // already answer (best-effort; the LLM judge is skipped for determinism). - msg := resultText - if navChunkTools[name] && gotEvidence { - msg += "\n\n[sufficiency check] These passages may answer the task. If so, call generate_report now — do not run further searches." - } - history = append(history, schema.Message{Role: schema.User, Content: msg}) - } - - // Max cycles reached without generate_report — force a final report. - return forceGenerateReport(ctx, db, inv, claim.ClaimID, history, session) -} - -// forceGenerateReport mirrors Python _force_generate_report. -func forceGenerateReport(ctx context.Context, db *gorm.DB, inv chat.Invoker, claimID string, history []schema.Message, session *researchSession) AgentResult { - if err := ctx.Err(); err != nil { - return AgentResult{ClaimID: claimID, IsVerified: false, Confidence: 0, Gaps: []string{"research cancelled: " + err.Error()}} - } - resp, err := inv.Invoke(ctx, db, chat.Request{ - Messages: append(append([]schema.Message{}, history...), - schema.Message{Role: schema.User, Content: "We've reached the research limit. Please output a final report as JSON."}), - Temperature: floatPtr(0.3), - }) - if err != nil { - return AgentResult{ClaimID: claimID, IsVerified: false, Confidence: 0, Gaps: []string{"forced report failed: " + err.Error()}} - } - var rep researchReport - if err := unmarshalModelJSON(resp.Content, &rep); err != nil { - return AgentResult{ClaimID: claimID, IsVerified: false, Confidence: 0, Gaps: []string{"forced report — data may be incomplete"}} - } - return reportToAgentResult(claimID, map[string]interface{}{ - "report": rep.Report, "is_verified": rep.IsVerified, "confidence": rep.Confidence, - "evidence_ids": rep.EvidenceIDs, "gaps": rep.Gaps, "grounded": rep.Grounded, - "numbers": rep.Numbers, "discovered_claims": rep.DiscoveredClaims, - }, session.evidenceIDs) -} - -// reportToAgentResult normalizes a generate_report argument map into an -// AgentResult, backfilling evidence ids when the model omitted them. -func reportToAgentResult(claimID string, args map[string]interface{}, sessionEvidenceIDs []int) AgentResult { - report, _ := args["report"].(string) - isVerified, _ := args["is_verified"].(bool) - confidence := floatVal(args["confidence"]) - evidenceIDs := intSlice(args["evidence_ids"]) - if len(evidenceIDs) == 0 { - evidenceIDs = append([]int(nil), sessionEvidenceIDs...) - } - gaps := strSlice(args["gaps"]) - grounded := strSlice(args["grounded"]) - numbers := strSlice(args["numbers"]) - discovered := strSlice(args["discovered_claims"]) - - return AgentResult{ - ClaimID: claimID, Report: report, IsVerified: isVerified, Confidence: confidence, - EvidenceIDs: evidenceIDs, Gaps: gaps, Grounded: grounded, Numbers: numbers, - DiscoveredClaims: discovered, - } -} - -// parseToolCall extracts a tool-call JSON from the model output (mirrors Python -// _parse_tool_call): …, ```json … ```, or bare {"name":…}. -func parseToolCall(text string) map[string]interface{} { - // … - if m := reToolCallTag.FindStringSubmatch(text); m != nil { - if v := tryJSON(m[1]); v != nil { - return v - } - } - // ```json … ``` - if m := reToolCallFence.FindStringSubmatch(text); m != nil { - if v := tryJSON(m[1]); v != nil { - return v - } - } - // bare {"name": …} - if m := reToolCallBare.FindStringIndex(text); m != nil { - if v := tryJSON(text[m[0]:]); v != nil { - return v - } - } - return nil -} - -func tryJSON(s string) map[string]interface{} { - var out map[string]interface{} - if err := json.Unmarshal([]byte(strings.TrimSpace(s)), &out); err == nil { - return out - } - return nil -} - -func floatVal(v interface{}) float64 { - switch x := v.(type) { - case float64: - return x - case float32: - return float64(x) - case int: - return float64(x) - case json.Number: - f, _ := x.Float64() - return f - } - return 0 -} - -func intSlice(v interface{}) []int { - switch x := v.(type) { - case []int: - return x - case []interface{}: - var out []int - for _, item := range x { - switch n := item.(type) { - case int: - out = append(out, n) - case float64: - out = append(out, int(n)) - } - } - return out - } - return nil -} - -func strSlice(v interface{}) []string { - switch x := v.(type) { - case []string: - return x - case []interface{}: - var out []string - for _, item := range x { - if s, ok := item.(string); ok { - out = append(out, s) - } - } - return out - } - return nil -} - -func floatPtr(v float64) *float64 { return &v } - -// determinePhase mirrors Python determine_current_phase (simplified: no verdict). -func determinePhase(p *Pipeline) string { - if p == nil || !p.kbinfos.HasChunks() { - return "locate" - } - return "explore" -} - -func phaseHintFor(phase string) string { - switch phase { - case "locate": - return "Prefer navigation tools to locate document regions before directly searching keywords." - case "explore": - return "Prefer retrieval tools to gather detailed information within the located region." - default: - return "" - } -} - -// formatToolList mirrors Python _fmt_tool_list: name + description + params. -func formatToolList(tools []string) string { - var lines []string - for _, name := range tools { - lines = append(lines, "- "+name+": "+toolDescription(name)) - } - return strings.Join(lines, "\n") -} - -// toolDescription returns a one-line description for prompt tool listing. -func toolDescription(name string) string { - switch name { - case "hybrid_search": - return "Hybrid (vector + keyword) search over the knowledge base." - case "vector_search": - return "Dense-vector semantic search over the knowledge base." - case "bm25_search": - return "Lexical BM25 keyword search over the knowledge base." - case "dataset_navigation_by_tree": - return "Navigate the document tree to locate relevant documents." - case "ontology_navigate": - return "Navigate a document's structure/outline to find relevant sections." - case "mindmap_navigate": - return "Navigate a mindmap-structured document." - case "wiki_query": - return "Query the compiled wiki pages." - case "graph_explore": - return "Explore the knowledge graph around a discovered entity." - case "web_search": - return "Search the web for external/current facts." - case "inspector_open_context": - return "Expand context around an already-returned chunk (2 neighbours each side)." - case "inspector_compare": - return "List the document sources of given chunk ids." - case "inspector_grep_within": - return "Find a keyword within a document and narrow its chunks to matching sentences." - case "inspector_request_adjacent": - return "Get adjacent chunks before/after a given chunk." - default: - return "Search tool." - } -} diff --git a/internal/agent/harness/review_fixes_test.go b/internal/agent/harness/review_fixes_test.go deleted file mode 100644 index 89a9ce4831a..00000000000 --- a/internal/agent/harness/review_fixes_test.go +++ /dev/null @@ -1,106 +0,0 @@ -// -// 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. -// - -package harness - -import "testing" - -// TestExtractCJKSubstrings_NoPanic guards the RE2-compatible CJK regex: the -// previous `\u4e00` escape would panic at compile time (review fix R14). -func TestExtractCJKSubstrings_NoPanic(t *testing.T) { - got := extractCJKSubstrings("巴黎是法国的首都,位于欧洲。") - if len(got) == 0 { - t.Fatal("CJK substrings must be extracted (and must not panic)") - } - for _, s := range got { - if !isCJK(s) { - t.Errorf("extracted %q is not CJK", s) - } - } -} - -// TestExtractNamedEntities_LatinNil asserts Latin text yields nil (NER delegated -// to the LLM grounded review). -func TestExtractNamedEntities_LatinNil(t *testing.T) { - if got := extractNamedEntities("Paris is the capital"); got != nil { - t.Errorf("Latin text must yield nil (NER delegated), got %v", got) - } -} - -// TestParseToolCall_Multiline asserts a multi-line generate_report body parses -// (review fix R13: the (?s) flag makes `.` span newlines). -func TestParseToolCall_Multiline(t *testing.T) { - text := `{"name": "generate_report", "arguments": { - "report": "Paris has 2 million people", - "is_verified": true, - "confidence": 0.9, - "evidence_ids": [0, 3], - "gaps": [] - }}` - call := parseToolCall(text) - if call == nil { - t.Fatal("multi-line tool call must parse") - } - if call["name"] != "generate_report" { - t.Errorf("name = %v, want generate_report", call["name"]) - } - args, _ := call["arguments"].(map[string]interface{}) - if args["report"] != "Paris has 2 million people" { - t.Errorf("report = %v", args["report"]) - } -} - -// TestParseToolCall_Fence asserts the fenced-JSON path still works. -func TestParseToolCall_Fence(t *testing.T) { - text := "```json\n{\"name\":\"hybrid_search\",\"arguments\":{\"query\":\"rocket\"}}\n```" - call := parseToolCall(text) - if call == nil || call["name"] != "hybrid_search" { - t.Fatalf("fenced tool call = %v", call) - } -} - -// TestNormalizeWebResults_UniqueChunkID asserts several snippets from the SAME -// URL get distinct chunk_id values so Kbinfos.Merge does not collapse them -// (review fix R11). -func TestNormalizeWebResults_UniqueChunkID(t *testing.T) { - raw := []byte(`{"results":[ - {"url":"https://a","content":"snippet one","title":"A"}, - {"url":"https://a","content":"snippet two","title":"A"} - ]}`) - out := normalizeWebResults(raw) - if len(out) != 2 { - t.Fatalf("normalizeWebResults = %d results, want 2 (distinct snippets)", len(out)) - } - if chunkIDOf(out[0]) == chunkIDOf(out[1]) { - t.Errorf("chunk_id collision: %q == %q", chunkIDOf(out[0]), chunkIDOf(out[1])) - } - // doc_id stays the URL. - if docIDOf(out[0]) != "https://a" || docIDOf(out[1]) != "https://a" { - t.Errorf("doc_id must stay the URL, got %q / %q", docIDOf(out[0]), docIDOf(out[1])) - } -} - -// TestChunkText_TextFallback asserts the "text" field is used when neither -// content_with_weight nor content is present (review fix: _evidence_md parity). -func TestChunkText_TextFallback(t *testing.T) { - if got := chunkText(map[string]interface{}{"text": "plain text field"}); got != "plain text field" { - t.Errorf("chunkText(text) = %q, want the text field", got) - } - // content_with_weight still wins over text. - if got := chunkText(map[string]interface{}{"content_with_weight": "cw", "text": "plain"}); got != "cw" { - t.Errorf("chunkText must prefer content_with_weight, got %q", got) - } -} diff --git a/internal/agent/harness/route.go b/internal/agent/harness/route.go deleted file mode 100644 index f6af095b875..00000000000 --- a/internal/agent/harness/route.go +++ /dev/null @@ -1,152 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "encoding/json" - "log" - "regexp" - "strings" - - "github.com/cloudwego/eino/schema" - - "ragflow/internal/agent/chat" - "ragflow/internal/common" - - "gorm.io/gorm" -) - -// routePrompt mirrors Python harness/prompts/route_prompt.py. -const routePrompt = `Analyze the following question and output a structured query analysis. - -Question: %s - -Analyze it across these dimensions: -1. Question type: factual / comparative / analytical / procedural / exploratory / verification / summarization. -2. Whether it needs decomposition into atomic facts, meaning whether multiple independent pieces of information must be retrieved separately before answering: true/false. -3. Suggested knowledge compilation tool: null (none) / toc (document table of contents) / graph (knowledge graph) / wiki (compiled domain knowledge). - -Output format (JSON): -{ - "question_type": "comparative", - "requires_decomposition": true, - "suggests_compilation": null, - "reasoning": "This is a comparative question, so it needs to be decomposed into two independent facts and one comparison relation." -} -` - -type routeResult struct { - QuestionType string `json:"question_type"` - RequiresDecomp *bool `json:"requires_decomposition"` - SuggestsCompilation string `json:"suggests_compilation"` - Reasoning string `json:"reasoning"` -} - -// RouteNode mirrors Python route_node. It classifies the question into a -// RouteDecision using the default chat invoker. Pure classification, no KB -// dependency. Never fails — falls back to a factual/direct decision. -func RouteNode(ctx context.Context, db *gorm.DB, question, modeLabel string) RouteDecision { - if strings.TrimSpace(question) == "" { - return fallbackRoute(question, modeLabel, "fallback: empty question") - } - inv := chat.GetDefaultInvoker() - if inv == nil { - return fallbackRoute(question, modeLabel, "fallback: chat invoker not configured") - } - resp, err := inv.Invoke(ctx, db, chat.Request{ - Messages: []schema.Message{ - {Role: schema.System, Content: strings.ReplaceAll(routePrompt, "%s", question)}, - {Role: schema.User, Content: question}, - }, - }) - if err != nil { - log.Printf("agentic_rag: route_node failed (fallback): %v", err) - return fallbackRoute(question, modeLabel, "fallback: LLM error") - } - var res routeResult - if err := unmarshalModelJSON(resp.Content, &res); err != nil { - log.Printf("agentic_rag: route_node parse failed (fallback): %v", err) - return fallbackRoute(question, modeLabel, "fallback: parse error") - } - return decide(question, modeLabel, res) -} - -// decide applies the mode's execution strategy to the LLM route output. -func decide(question, modeLabel string, res routeResult) RouteDecision { - mode, ok := GetMode(modeLabel) - if !ok { - mode = THINKING_MODES["medium"] - } - qType := res.QuestionType - if qType == "" { - qType = "factual" - } - needDecomp := true - if res.RequiresDecomp != nil { - needDecomp = *res.RequiresDecomp - } - return RouteDecision{ - Question: question, - ThinkingMode: modeLabel, - QuestionType: qType, - RequiresDecomposition: mode.RequiresDecomposition && needDecomp, - ExecutionStrategy: mode.Strategy, - SuggestsCompilation: normalizeCompilationSuggestion(res.SuggestsCompilation), - Reasoning: res.Reasoning, - } -} - -// normalizeCompilationSuggestion maps the LLM's free-text suggestion to a -// canonical compiled-artifact key: "", "toc", "graph", or "wiki". Anything else -// (including "null") collapses to "" so the production runner never routes on an -// unknown artifact name. -func normalizeCompilationSuggestion(s string) string { - switch strings.ToLower(strings.TrimSpace(s)) { - case "toc": - return "toc" - case "graph", "knowledge_graph", "kg": - return "graph" - case "wiki", "compiled": - return "wiki" - default: - return "" - } -} - -func fallbackRoute(question, modeLabel, reason string) RouteDecision { - return RouteDecision{ - Question: question, ThinkingMode: modeLabel, QuestionType: "factual", - RequiresDecomposition: false, ExecutionStrategy: "direct_search", Reasoning: reason, - } -} - -var ( - reFence = regexp.MustCompile("```(?:json)?\\s*|\\s*```") -) - -// unmarshalModelJSON mirrors Python's _extract_json: strip thinking preamble and -// Markdown fences, then parse JSON. -func unmarshalModelJSON(text string, out interface{}) error { - text = common.StripThinkTrailing(text) - text = reFence.ReplaceAllString(text, "") - text = strings.TrimSpace(text) - if text == "" { - return json.Unmarshal([]byte("{}"), out) - } - return json.Unmarshal([]byte(text), out) -} diff --git a/internal/agent/harness/route_test.go b/internal/agent/harness/route_test.go deleted file mode 100644 index 7f1e0b1306b..00000000000 --- a/internal/agent/harness/route_test.go +++ /dev/null @@ -1,210 +0,0 @@ -package harness - -import ( - "context" - "reflect" - "testing" - - "gorm.io/gorm" - - "ragflow/internal/agent/component" -) - -// fakeChatInvoker returns a fixed content for the chat call, so tests can drive -// the route/planner LLM output deterministically. -type fakeChatInvoker struct{ content string } - -func (f *fakeChatInvoker) Invoke(_ context.Context, _ *gorm.DB, _ component.ChatInvokeRequest) (*component.ChatInvokeResponse, error) { - return &component.ChatInvokeResponse{Content: f.content}, nil -} - -func installChat(t *testing.T, content string) { - t.Helper() - component.SetDefaultChatInvoker(&fakeChatInvoker{content: content}) - t.Cleanup(func() { component.SetDefaultChatInvoker(nil) }) -} - -// TestRouteNode_Classifies asserts route classification drives the execution -// strategy from the mode and the LLM's question_type. -func TestRouteNode_Classifies(t *testing.T) { - installChat(t, `{"question_type":"comparative","requires_decomposition":true,"reasoning":"cmp"}`) - r := RouteNode(t.Context(), nil, "Compare A and B", "medium") - if r.QuestionType != "comparative" { - t.Errorf("question_type = %q, want comparative", r.QuestionType) - } - // medium mode requires decomposition AND LLM says true -> true. - if !r.RequiresDecomposition { - t.Errorf("requires_decomposition = false, want true") - } - if r.ExecutionStrategy != "decompose_and_search" { - t.Errorf("execution_strategy = %q, want decompose_and_search", r.ExecutionStrategy) - } -} - -// TestRouteNode_LowModeDisablesDecomposition asserts low mode never decomposes -// even if the LLM requests it. -func TestRouteNode_LowModeDisablesDecomposition(t *testing.T) { - installChat(t, `{"question_type":"analytical","requires_decomposition":true}`) - r := RouteNode(t.Context(), nil, "Analyze X", "low") - if r.RequiresDecomposition { - t.Errorf("low mode must disable decomposition, got true") - } - if r.ExecutionStrategy != "direct_search" { - t.Errorf("low mode execution_strategy = %q, want direct_search", r.ExecutionStrategy) - } -} - -// TestRouteNode_FencedJSON asserts think-tag/fence stripping works. -func TestRouteNode_FencedJSON(t *testing.T) { - installChat(t, "Sure!\n```json\n{\"question_type\":\"factual\",\"requires_decomposition\":false}\n```") - r := RouteNode(t.Context(), nil, "What is X?", "medium") - if r.QuestionType != "factual" { - t.Errorf("question_type = %q, want factual", r.QuestionType) - } - if r.RequiresDecomposition { - t.Errorf("requires_decomposition = true, want false") - } -} - -// TestRouteNode_EmptyQuestionFallsBack asserts an empty question yields a -// direct factual decision without calling the LLM. -func TestRouteNode_EmptyQuestionFallsBack(t *testing.T) { - r := RouteNode(t.Context(), nil, "", "medium") - if r.QuestionType != "factual" || r.RequiresDecomposition { - t.Errorf("empty question must fall back to direct factual, got %+v", r) - } -} - -// TestRouteNode_SuggestsCompilation asserts the route preserves a normalized -// compiled-artifact suggestion (P5) so the production runner can prefer the wiki -// tool. -func TestRouteNode_SuggestsCompilation(t *testing.T) { - installChat(t, `{"question_type":"analytical","requires_decomposition":true,"suggests_compilation":"wiki"}`) - r := RouteNode(t.Context(), nil, "What does the domain say about X?", "medium") - if r.SuggestsCompilation != "wiki" { - t.Errorf("suggests_compilation = %q, want wiki", r.SuggestsCompilation) - } -} - -// TestNormalizeCompilationSuggestion asserts free-text suggestions map to the -// canonical keys and unknown/null collapse to "". -func TestNormalizeCompilationSuggestion(t *testing.T) { - cases := map[string]string{ - "wiki": "wiki", - "WIKI": "wiki", - "compiled": "wiki", - "graph": "graph", - "kg": "graph", - "toc": "toc", - "null": "", - "": "", - "spaghetti": "", - } - for in, want := range cases { - if got := normalizeCompilationSuggestion(in); got != want { - t.Errorf("normalizeCompilationSuggestion(%q) = %q, want %q", in, got, want) - } - } -} - -// TestRouteNode_WikiSuggestionSurvivesFence asserts a fenced JSON route still -// carries the wiki suggestion through decide(). -func TestRouteNode_WikiSuggestionSurvivesFence(t *testing.T) { - installChat(t, "```json\n{\"question_type\":\"procedural\",\"requires_decomposition\":false,\"suggests_compilation\":\"graph\"}\n```") - r := RouteNode(t.Context(), nil, "How is this structured?", "medium") - if r.SuggestsCompilation != "graph" { - t.Errorf("suggests_compilation = %q, want graph", r.SuggestsCompilation) - } -} - -// TestPlannerNode_DirectMode asserts a non-decomposed route yields one coarse -// claim without calling the LLM. -func TestPlannerNode_DirectMode(t *testing.T) { - plan := PlannerNode(t.Context(), nil, RouteDecision{ - Question: "What is X?", RequiresDecomposition: false, - }, nil) - if plan.PlanType != "direct" || len(plan.Claims) != 1 { - t.Fatalf("direct plan = %+v, want 1 direct claim", plan) - } -} - -// TestPlannerNode_Decomposes asserts the planner builds claims from the LLM -// output and applies the mode's max iterations. -func TestPlannerNode_Decomposes(t *testing.T) { - installChat(t, `{"claims":[ - {"claim_id":"c0","description":"fact one","priority":0}, - {"claim_id":"c1","description":"fact two","priority":1} - ]}`) - plan := PlannerNode(t.Context(), nil, RouteDecision{ - Question: "Compare A and B", QuestionType: "comparative", RequiresDecomposition: true, ThinkingMode: "medium", - }, nil) - if plan.PlanType != "comparative_decomposition" { - t.Errorf("plan_type = %q, want comparative_decomposition", plan.PlanType) - } - if len(plan.Claims) != 2 { - t.Fatalf("claims = %d, want 2", len(plan.Claims)) - } - if plan.Claims[1].Priority != 1 { - t.Errorf("claim priority = %d, want 1", plan.Claims[1].Priority) - } - // medium maxOrchestratorCycles = 3 - if plan.MaxIterations != 3 { - t.Errorf("max_iterations = %d, want 3", plan.MaxIterations) - } -} - -// TestPlannerNode_UnknownModeFallsBack asserts an unknown (non-empty) mode label -// falls back to medium so the planner is not driven by a zero-valued mode -// (which would produce a degenerate plan with max_claims=0). -func TestPlannerNode_UnknownModeFallsBack(t *testing.T) { - installChat(t, `{"claims":[{"claim_id":"c0","description":"fact one","priority":0}]}`) - plan := PlannerNode(t.Context(), nil, RouteDecision{ - Question: "Q", RequiresDecomposition: true, ThinkingMode: "turbo-unknown", - }, nil) - // medium maxOrchestratorCycles = 3, and claims must still be built. - if plan.MaxIterations != 3 { - t.Errorf("max_iterations = %d, want 3 (medium fallback)", plan.MaxIterations) - } - if len(plan.Claims) != 1 { - t.Errorf("claims = %d, want 1", len(plan.Claims)) - } -} - -// TestPlannerNode_BadJSONFallsBack asserts unparseable planner output falls back -// to the direct plan. -func TestPlannerNode_BadJSONFallsBack(t *testing.T) { - installChat(t, "not json at all") - plan := PlannerNode(t.Context(), nil, RouteDecision{ - Question: "Q", RequiresDecomposition: true, ThinkingMode: "medium", - }, nil) - if plan.PlanType != "direct" || len(plan.Claims) != 1 { - t.Fatalf("fallback plan = %+v, want direct", plan) - } -} - -// TestUnmarshalModelJSON pins unmarshalModelJSON: think preamble and Markdown -// fences are stripped before JSON parsing, and an empty payload yields {}. -func TestUnmarshalModelJSON(t *testing.T) { - tests := []struct { - name string - in string - want map[string]any - }{ - {name: "plain json", in: `{"answer":"42"}`, want: map[string]any{"answer": "42"}}, - {name: "think prefix", in: `reason{"answer":"42"}`, want: map[string]any{"answer": "42"}}, - {name: "json fence", in: "```json\n{\"answer\":\"42\"}\n```", want: map[string]any{"answer": "42"}}, - {name: "think then fence", in: "r```json\n{\"answer\":\"42\"}\n```", want: map[string]any{"answer": "42"}}, - {name: "empty becomes empty object", in: "", want: map[string]any{}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - var out map[string]any - if err := unmarshalModelJSON(tt.in, &out); err != nil { - t.Fatalf("unmarshalModelJSON(%q): %v", tt.in, err) - } - if !reflect.DeepEqual(out, tt.want) { - t.Errorf("unmarshalModelJSON(%q) = %#v, want %#v", tt.in, out, tt.want) - } - }) - } -} diff --git a/internal/agent/harness/split_sentences_test.go b/internal/agent/harness/split_sentences_test.go deleted file mode 100644 index 3140a56597c..00000000000 --- a/internal/agent/harness/split_sentences_test.go +++ /dev/null @@ -1,72 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "reflect" - "testing" -) - -// TestSplitSentences_TerminatorsKept asserts terminators stay attached and empty -// segments are dropped. -func TestSplitSentences_TerminatorsKept(t *testing.T) { - got := splitSentences("Paris has people. It is in France! Really?") - want := []string{"Paris has people.", "It is in France!", "Really?"} - if !reflect.DeepEqual(got, want) { - t.Errorf("splitSentences = %#v, want %#v", got, want) - } -} - -// TestSplitSentences_DecimalGuard asserts "3.14" / "v1.2" do not split. -func TestSplitSentences_DecimalGuard(t *testing.T) { - got := splitSentences("Value is 3.14 today. Version v1.2 released.") - if len(got) != 2 { - t.Fatalf("splitSentences = %#v, want 2 sentences (decimals not split)", got) - } - if got[0] != "Value is 3.14 today." { - t.Errorf("first = %q, want decimal intact", got[0]) - } -} - -// TestSplitSentences_CJK asserts Chinese terminators split and are kept. -func TestSplitSentences_CJK(t *testing.T) { - got := splitSentences("巴黎有两百万人。它在法国!") - want := []string{"巴黎有两百万人。", "它在法国!"} - if !reflect.DeepEqual(got, want) { - t.Errorf("splitSentences(CJK) = %#v, want %#v", got, want) - } -} - -// TestSplitSentences_TableAtomic asserts a markdown table is one atomic sentence. -func TestSplitSentences_TableAtomic(t *testing.T) { - text := "Intro here.\n| a | b |\n| - | - |\n| 1 | 2 |\nAfter table." - got := splitSentences(text) - if len(got) != 3 { - t.Fatalf("splitSentences(table) = %#v, want 3 (table atomic)", got) - } - // The table block must be a single sentence. - if got[1] != "| a | b |\n| - | - |\n| 1 | 2 |" { - t.Errorf("table sentence = %q, want atomic table", got[1]) - } -} - -// TestSplitSentences_Empty asserts empty input yields nil. -func TestSplitSentences_Empty(t *testing.T) { - if got := splitSentences(""); got != nil { - t.Errorf("splitSentences(\"\") = %#v, want nil", got) - } -} diff --git a/internal/agent/harness/sufficiency.go b/internal/agent/harness/sufficiency.go deleted file mode 100644 index a30d9c2b72a..00000000000 --- a/internal/agent/harness/sufficiency.go +++ /dev/null @@ -1,639 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "fmt" - "regexp" - "sort" - "strconv" - "strings" -) - -// Sufficiency scoring (code-only, mirrors Python sufficiency.py): cross-check an -// agent result against the evidence chunks, fuse agent confidence + cross-check -// pass rate, then route to a 5-way verdict. -// -// Cross-check alignment (Sufficient Context redesign, mirrors sufficiency.py): -// - number extraction + noise filtering (drop 0= 0.5 -// -// NER is intentionally NOT implemented in Go (no maintained native spaCy-level -// NER library; see plan §cross-check). Entity extraction is delegated to the -// LLM grounded review (grounded_llm.go). TODO(candle): adopt -// github.com/huggingface/candle via Rust↔Go binding + model conversion to -// restore spaCy-parity multilingual NER (en/zh/de/fr/es/pt/ja). - -var reNumber = regexp.MustCompile(`\d+\.?\d*`) - -// reCJKRun matches a run of CJK characters (RE2 requires \x{...} escapes; the -// Python-style \u escapes would panic at compile time). -var reCJKRun = regexp.MustCompile(`[\x{4e00}-\x{9fff}]+`) - -// extractNumbers returns numeric values found in text (mirrors Python -// extract_numbers). -func extractNumbers(text string) []float64 { - var out []float64 - for _, m := range reNumber.FindAllString(text, -1) { - if f, err := strconv.ParseFloat(m, 64); err == nil { - out = append(out, f) - } - } - return out -} - -// filterRelevantNumbers drops numbers with no factual-claim signal (mirrors -// Python _filter_relevant_numbers): values in (0,1) are ratios/confidences, and -// duplicates are checked once. -func filterRelevantNumbers(numbers []float64) []float64 { - var kept []float64 - for _, n := range numbers { - if n > 0 && n < 1 { - continue - } - dup := false - for _, k := range kept { - if k == n { - dup = true - break - } - } - if !dup { - kept = append(kept, n) - } - } - return kept -} - -// isCJK reports whether text contains Chinese/Japanese characters (mirrors -// Python _is_cjk). -func isCJK(text string) bool { - for _, r := range text { - if r >= '\u4e00' && r <= '\u9fff' { - return true - } - } - return false -} - -// extractNamedEntities is a degraded stub: CJK substrings are still extracted -// (they need no word boundaries), but Latin-script NER is delegated to the LLM -// grounded review. See the TODO(candle) note in the package comment. -func extractNamedEntities(text string) []string { - if text == "" { - return nil - } - // CJK entities: every Han run is a candidate; the LLM review disambiguates. - // This keeps number-adjacent Chinese evidence verifiable without spaCy. - if isCJK(text) { - return extractCJKSubstrings(text) - } - return nil -} - -// extractCJKSubstrings returns runs of CJK characters as entity candidates. -// This is intentionally coarse (no NER): it only preserves the substring-match -// path for CJK evidence that the union matcher below can still use. -func extractCJKSubstrings(text string) []string { - seen := map[string]bool{} - var out []string - for _, m := range reCJKRun.FindAllString(text, -1) { - // Skip single-char connective tissue noise; keep meaningful runs. - if len([]rune(m)) < 2 || seen[m] { - continue - } - seen[m] = true - out = append(out, m) - } - return out -} - -// boundedPhraseMatch mirrors Python's bounded word/phrase match -// `(? 0 && isWordChar(rune(text[idx-1])) - after := idx+len(needle) < len(text) && isWordChar(rune(text[idx+len(needle)])) - if !before && !after { - return true - } - start = idx + 1 - } -} - -// isWordChar mirrors Python \w (word chars are also bounded by the match). -func isWordChar(r rune) bool { - if r >= '0' && r <= '9' { - return true - } - if r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' { - return true - } - return r == '_' -} - -// detectNumericConflict mirrors Python _detect_numeric_conflict: flag pairs of -// disclosed figures that are close-but-not-equal (ratio in (1, 1.3]) — the -// signature of a multi-source口径 conflict. -func detectNumericConflict(disclosed []string) []string { - type fig struct { - val float64 - text string - } - reLead := regexp.MustCompile(`([\d][\d,]*(?:\.\d+)?)`) - var figures []fig - for _, entry := range disclosed { - m := reLead.FindStringSubmatch(entry) - if m == nil { - continue - } - v, err := strconv.ParseFloat(strings.ReplaceAll(m[1], ",", ""), 64) - if err != nil { - continue - } - text := entry - if rs := []rune(text); len(rs) > 80 { - text = string(rs[:80]) // Python entry[:80] is a character truncation - } - figures = append(figures, fig{val: v, text: text}) - } - var conflicts []string - for i := 0; i < len(figures); i++ { - for j := i + 1; j < len(figures); j++ { - a, b := figures[i].val, figures[j].val - if a <= 0 || b <= 0 { - continue - } - hi, lo := a, b - if lo > hi { - hi, lo = b, a - } - ratio := hi / lo - if ratio > 1 && ratio <= 1.3 { - conflicts = append(conflicts, fmt.Sprintf("%s vs %s", figures[i].text, figures[j].text)) - } - } - } - return conflicts -} - -// CrossCheckClaim performs a code-level cross-check of an agent result against -// the accumulated evidence chunks (number matching + CJK entity presence). -func CrossCheckClaim(agent *AgentResult, allChunks map[int]map[string]interface{}) ClaimCrossCheckResult { - if agent == nil { - return ClaimCrossCheckResult{ClaimID: "", CrossCheckPassed: false, Mismatches: []string{"nil agent result"}} - } - if !agent.IsVerified { - return ClaimCrossCheckResult{ClaimID: agent.ClaimID, CrossCheckPassed: false, Mismatches: []string{"agent self-reported as unverified"}} - } - rawNumbers := extractNumbers(agent.Report) - numbers := filterRelevantNumbers(rawNumbers) - entities := extractNamedEntities(agent.Report) - - // Gather evidence chunk texts (union) — a fact supported by ONE chunk is - // verified; the old per-chunk loop demanded every chunk confirm every fact. - var chunkTexts []string - for _, eid := range agent.EvidenceIDs { - chunk, ok := allChunks[eid] - if !ok { - continue - } - text := "" - if c, ok := chunk["content_with_weight"].(string); ok { - text = strings.ToLower(c) - } else if c, ok := chunk["content"].(string); ok { - text = strings.ToLower(c) - } - chunkTexts = append(chunkTexts, text) - } - - // Numeric multi-source conflict detection: several close-but-different - // disclosed figures cap the claim below the pass floor. - if disclosed := agent.Numbers; len(disclosed) > 0 { - if conflict := detectNumericConflict(disclosed); len(conflict) > 0 { - var m []string - for _, c := range conflict { - m = append(m, "numeric source conflict: "+c) - } - return ClaimCrossCheckResult{ClaimID: agent.ClaimID, CrossCheckPassed: false, CrossCheckScore: 0.0, Mismatches: m, HasEvidence: len(chunkTexts) > 0} - } - } - - anywhere := func(needle string) bool { - for _, t := range chunkTexts { - if strings.Contains(t, needle) { - return true - } - } - return false - } - - var matches, mismatches []string - for _, num := range numbers { - // Numbers extracted as floats ("1976" → 1976.0) while chunk text spells - // "1976" — match both raw and integral forms, bounded. - var forms []string - if num == float64(int64(num)) { - forms = []string{strconv.FormatFloat(num, 'f', -1, 64), strconv.FormatInt(int64(num), 10)} - } else { - forms = []string{strconv.FormatFloat(num, 'f', -1, 64)} - } - found := false - for _, f := range forms { - if anyBounded(chunkTexts, f) { - found = true - break - } - } - if found { - matches = append(matches, fmt.Sprintf("number %s found in evidence", strconv.FormatFloat(num, 'f', -1, 64))) - } else { - mismatches = append(mismatches, fmt.Sprintf("number %s not found in any evidence chunk", strconv.FormatFloat(num, 'f', -1, 64))) - } - } - - for _, ent := range entities { - found := false - if isCJK(ent) { - found = anywhere(strings.ToLower(ent)) - } else { - found = anyBounded(chunkTexts, strings.ToLower(ent)) - } - if found { - matches = append(matches, fmt.Sprintf("entity '%s' found in evidence", ent)) - } else { - mismatches = append(mismatches, fmt.Sprintf("entity '%s' not found in any evidence chunk", ent)) - } - } - - total := len(matches) + len(mismatches) - hasEvidence := len(chunkTexts) > 0 - - if total == 0 { - // No evidence examined → fail; ids but nothing extractable → neutral 0.5. - if len(agent.EvidenceIDs) == 0 { - return ClaimCrossCheckResult{ClaimID: agent.ClaimID, CrossCheckPassed: false, CrossCheckScore: 0.0, Mismatches: []string{"no evidence"}, HasEvidence: false} - } - return ClaimCrossCheckResult{ClaimID: agent.ClaimID, CrossCheckPassed: false, CrossCheckScore: 0.5, Mismatches: []string{"nothing extractable to cross-check"}, HasEvidence: hasEvidence} - } - - crossScore := float64(len(matches)) / float64(total) - crossPassed := crossScore >= 0.5 - return ClaimCrossCheckResult{ - ClaimID: agent.ClaimID, CrossCheckPassed: crossPassed, CrossCheckScore: crossScore, - EvidenceMatches: matches, Mismatches: mismatches, HasEvidence: hasEvidence, - } -} - -// anyBounded reports whether needle appears in any chunk text with word -// boundaries (mirrors Python `(? 0 { - requiredGaps = requiredEntityGaps(question, claims, allChunks) - } - gappedIDs := map[string]bool{} - for cid := range requiredGaps { - gappedIDs[cid] = true - } - - // Signal A: agent self-assessed confidence (continuous). Only self-verified, - // non-gapped claims count; a gapped claim's confidence is zeroed so it cannot - // mask an evidence gap. - var verified []AgentResult - for _, r := range agentResults { - if r.IsVerified && !gappedIDs[r.ClaimID] { - verified = append(verified, r) - } - } - agentScore := 0.0 - if len(verified) > 0 { - total := 0.0 - for _, r := range verified { - total += r.Confidence - } - agentScore = total / float64(len(verified)) - } - - // Signal B: cross-check score, excluding unrelated/ungrounded noise claims - // (cross<0.2 AND agent self-unverified) so an invented claim doesn't punish - // an otherwise sufficient verdict. - noiseThreshold := 0.2 - agentVerified := map[string]bool{} - for _, r := range agentResults { - agentVerified[r.ClaimID] = r.IsVerified - } - var noiseIDs []string - var kept []ClaimCrossCheckResult - for _, r := range crossResults { - if r.CrossCheckScore < noiseThreshold && !r.CrossCheckPassed && !agentVerified[r.ClaimID] { - noiseIDs = append(noiseIDs, r.ClaimID) - continue - } - kept = append(kept, r) - } - if len(noiseIDs) > 0 && len(kept) > 0 { - crossResults = kept - } - - // ── Hard-veto floor ── - minCrossFloor := 0.5 - selfVerifiedIDs := map[string]bool{} - for _, r := range agentResults { - if r.IsVerified { - selfVerifiedIDs[r.ClaimID] = true - } - } - weakSet := map[string]bool{} - for _, r := range crossResults { - if selfVerifiedIDs[r.ClaimID] && r.CrossCheckScore < minCrossFloor { - weakSet[r.ClaimID] = true - } - } - for cid := range gappedIDs { - weakSet[cid] = true - } - weak := sortedKeys(weakSet) - - // Conflict detection based on the kept (non-noisy) claims. - hasConflicts := false - for _, r := range crossResults { - if len(r.Mismatches) > 0 { - hasConflicts = true - break - } - } - - // Cross-check status (code-only preliminary view, no AutoRater). - anyPassed := false - for _, r := range crossResults { - if r.CrossCheckPassed { - anyPassed = true - break - } - } - status := "INSUFFICIENT" - switch { - case !anyPassed: - status = "UNANSWERABLE" - case hasConflicts: - status = "CONFLICTING" - case len(weak) > 0: - status = "INSUFFICIENT" - case agentScore >= mode.SufficiencyThreshold: - status = "SUFFICIENT" - default: - status = "USEFUL_BUT_INCOMPLETE" - } - - var missing []string - for _, r := range crossResults { - if !r.CrossCheckPassed { - missing = append(missing, r.ClaimID) - } - } - missing = append(missing, noiseIDs...) - for _, c := range weak { - if !containsStr(missing, c) { - missing = append(missing, c) - } - } - - assessments := make([]map[string]interface{}, 0, len(crossResults)) - for _, r := range crossResults { - assessments = append(assessments, map[string]interface{}{ - "claim_id": r.ClaimID, "is_verified": r.CrossCheckPassed, "score": r.CrossCheckScore, - "mismatches": r.Mismatches, "has_evidence": r.HasEvidence, - }) - } - - return SufficiencyVerdict{ - Status: status, Score: agentScore, AgentScore: agentScore, CrossScore: 0, - ClaimAssessments: assessments, HasConflicts: hasConflicts, MissingClaims: missing, - Feedback: buildFeedback(missing, crossResults), OverallReason: fmt.Sprintf("%s agent_conf=%.2f hard_veto=%d", status, agentScore, len(weak)), - HardViolations: weak, AgentConfidence: agentScore, - } -} - -// requiredEntityGaps mirrors Python required_entity_gaps. NER-degraded: entity -// extraction yields only CJK substrings (see extractNamedEntities TODO), so the -// AND-semantics veto is partial for Latin-script questions. -func requiredEntityGaps(question string, claims []ClaimTarget, allChunks map[int]map[string]interface{}) map[string][]string { - var chunkTexts []string - for _, chunk := range allChunks { - text := "" - if c, ok := chunk["content_with_weight"].(string); ok { - text = c - } else if c, ok := chunk["content"].(string); ok { - text = c - } - if text != "" { - chunkTexts = append(chunkTexts, strings.ToLower(text)) - } - } - qEntities := extractNamedEntities(question) - gaps := map[string][]string{} - for _, claim := range claims { - if claim.ClaimID == "" || claim.Description == "" { - continue - } - descEntities := extractNamedEntities(claim.Description) - descLower := map[string]bool{} - for _, e := range descEntities { - descLower[strings.ToLower(e)] = true - } - var required []string - required = append(required, descEntities...) - for _, e := range qEntities { - if descLower[strings.ToLower(e)] { - required = append(required, e) - } - } - var missing []string - for _, e := range required { - if !entityPresent(e, chunkTexts) { - missing = append(missing, e) - } - } - if len(missing) > 0 { - gaps[claim.ClaimID] = missing - } - } - return gaps -} - -// entityPresent mirrors Python _entity_present: CJK → substring, else bounded. -func entityPresent(ent string, chunkTexts []string) bool { - if isCJK(ent) { - lower := strings.ToLower(ent) - for _, t := range chunkTexts { - if strings.Contains(t, lower) { - return true - } - } - return false - } - return anyBounded(chunkTexts, strings.ToLower(ent)) -} - -func containsStr(list []string, s string) bool { - for _, x := range list { - if x == s { - return true - } - } - return false -} - -func buildFeedback(missing []string, results []ClaimCrossCheckResult) string { - if len(missing) == 0 { - return "all claims verified" - } - var hints []string - for _, r := range results { - if !r.CrossCheckPassed { - hints = append(hints, fmt.Sprintf("claim %s: %d mismatch(es)", r.ClaimID, len(r.Mismatches))) - } - } - return "missing: " + strings.Join(hints, "; ") -} - -// AutoRating is the LLM Sufficient Context AutoRater output (mirrors the dict -// returned by Python llm_sufficiency_boost). -type AutoRating struct { - IsSufficient bool - Confidence float64 - Missing []string - Contradictions []string - Followups []string -} - -// RouteSufficiencyVerdict returns (action, shouldContinue, caveat) from the -// verdict via the decision ladder + orchestrator action mapping. It mirrors -// Python route_sufficiency_verdict (sufficiency.py:791), which is the -// orchestrator-facing wrapper that calls sufficiency_ladder then maps the -// ladder action onto orchestrator actions. -// -// The AutoRater (auto) is the primary judge; when nil, the verdict's code-level -// status is used as a fallback so the loop still terminates (medium mode, or a -// missing LLM judge). -func RouteSufficiencyVerdict(v SufficiencyVerdict, modeLabel string, cycle, maxCycles int, auto *AutoRating) (string, bool, string) { - mode, _ := GetMode(modeLabel) - if mode.Label == "" { - mode = THINKING_MODES["medium"] - } - - // AutoRater signals, with sane defaults when it was not invoked. - autoSufficient := v.Status == "SUFFICIENT" - autoConfidence := 1.0 - missing := v.MissingClaims - contradictions := []string{} - if auto != nil { - autoSufficient = auto.IsSufficient - autoConfidence = auto.Confidence - missing = auto.Missing - contradictions = auto.Contradictions - } else if v.HasConflicts { - contradictions = []string{v.Feedback} - } - - hardViolations := map[string][]string{} - for _, id := range v.HardViolations { - hardViolations[id] = []string{} - } - - out := SufficiencyLadder(LadderInput{ - AutoSufficient: autoSufficient, - AutoConfidence: autoConfidence, - Missing: missing, - Contradictions: contradictions, - AgentConfidence: v.AgentConfidence, - CHigh: mode.CHigh, - CLow: mode.CLow, - LLMFloor: mode.LLMFloor, - AllowsReconcile: mode.AllowsReconcile, - Cycle: cycle, - MaxCycles: maxCycles, - HardViolations: hardViolations, - }) - - // Map ladder action onto orchestrator actions (mirrors sufficiency.py:842-858). - switch out.Action { - case ActionAnswerWithCaveat: - return "ANSWER_PARTIAL", false, out.Caveat - case ActionReconcile: - // medium has no reconcile loop → degrade to CONTINUE (keep searching). - return "CONTINUE", true, out.Caveat - case ActionUnanswerable: - if mode.FallbackToDirectLLM { - return "FALLBACK_LLM", false, out.Caveat - } - return "ABSTAIN", false, out.Caveat - case ActionGap: - return "CONTINUE", true, out.Caveat - default: // ActionAnswer - return "ANSWER", out.ShouldContinue, out.Caveat - } -} diff --git a/internal/agent/harness/sufficiency_ladder.go b/internal/agent/harness/sufficiency_ladder.go deleted file mode 100644 index 9e059ca5780..00000000000 --- a/internal/agent/harness/sufficiency_ladder.go +++ /dev/null @@ -1,164 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "sort" - "strings" -) - -// Action constants (shared with orchestrators), mirroring Python -// sufficiency_ladder.py. The ladder decides *presentation*: full answer vs. -// caveated answer vs. re-investigate vs. unanswerable. -const ( - ActionAnswer = "ANSWER" - ActionAnswerWithCaveat = "ANSWER_WITH_CAVEAT" - ActionGap = "GAP" - ActionReconcile = "RECONCILE" - ActionUnanswerable = "UNANSWERABLE" -) - -// LadderInput is the decision-ladder input set, mirroring the keyword arguments -// of Python sufficiency_ladder(). AutoSufficient/AutoConfidence are the LLM -// AutoRater's judgment; Missing/Contradictions are its concrete gaps; and -// AgentConfidence is the aggregated agent self-confidence (risk gate). -type LadderInput struct { - AutoSufficient bool - AutoConfidence float64 - Missing []string - Contradictions []string - AgentConfidence float64 - CHigh float64 - CLow float64 - LLMFloor float64 - AllowsReconcile bool - Cycle int - MaxCycles int - HardViolations map[string][]string // claimID -> gaps (or empty slices as markers) -} - -// LadderOutput is the decision-ladder result. -type LadderOutput struct { - Action string - ShouldContinue bool - Caveat string - Missing []string -} - -// AggregateAgentConfidence mirrors Python aggregate_agent_confidence: mean -// self-confidence over the trusted (self-verified, non-violating) claims. -// HardViolations keys are claim IDs that must be excluded regardless of their -// self-reported verification. -func AggregateAgentConfidence(results []AgentResult, hardViolations map[string][]string) float64 { - violated := map[string]bool{} - for id := range hardViolations { - violated[id] = true - } - total := 0.0 - count := 0 - for _, r := range results { - if !r.IsVerified || violated[r.ClaimID] { - continue - } - total += r.Confidence - count++ - } - if count == 0 { - return 0.0 - } - return total / float64(count) -} - -// SufficiencyLadder evaluates the monotonic decision ladder and returns the -// action. It is a pure function (no LLM dependency), mirroring Python -// sufficiency_ladder() decision-by-decision. -func SufficiencyLadder(in LadderInput) LadderOutput { - violations := map[string][]string{} - for id, gaps := range in.HardViolations { - violations[id] = gaps - } - - // 1. Hard veto floor: code-proven evidence gap beats the LLM's "good enough". - if len(violations) > 0 { - ids := make([]string, 0, len(violations)) - for id := range violations { - ids = append(ids, id) - } - sort.Strings(ids) - first := ids - if len(first) > 6 { - first = first[:6] - } - return LadderOutput{ - Action: ActionAnswerWithCaveat, - ShouldContinue: false, - Caveat: "hard evidence gap in claim(s): " + strings.Join(first, ", "), - Missing: in.Missing, - } - } - - // 2. AutoRater says insufficient. - if !in.AutoSufficient { - if len(in.Missing) > 0 { - return LadderOutput{Action: ActionGap, ShouldContinue: true, Missing: in.Missing} - } - return LadderOutput{Action: ActionUnanswerable, ShouldContinue: false, Missing: in.Missing} - } - - // 3. AutoRater is not confident in its own sufficiency call. - if in.AutoConfidence < in.LLMFloor { - if in.AllowsReconcile && in.Cycle < in.MaxCycles-1 { - return LadderOutput{ - Action: ActionReconcile, - ShouldContinue: true, - Caveat: "AutoRater itself is unsure; re-investigating", - } - } - return LadderOutput{ - Action: ActionAnswerWithCaveat, - ShouldContinue: false, - Caveat: "AutoRater sufficiency judgment is low-confidence", - } - } - - // 4. Sufficient + confident: agent confidence sets the presentation. - caveat := "" - shouldContinue := false - action := ActionAnswer - switch { - case in.AgentConfidence >= in.CHigh: - action = ActionAnswer - case in.AgentConfidence >= in.CLow: - action = ActionAnswerWithCaveat - caveat = "evidence partially supports the answer" - case in.AllowsReconcile && in.Cycle < in.MaxCycles-1: - action = ActionReconcile - shouldContinue = true - default: - action = ActionAnswerWithCaveat - caveat = "evidence partially supports the answer" - } - - if len(in.Contradictions) > 0 { - // Never silently pick one side of a contradiction; surface it. - caveat = "evidence contains conflicting figures" - action = ActionAnswerWithCaveat - shouldContinue = false - } - - return LadderOutput{Action: action, ShouldContinue: shouldContinue, Caveat: caveat, Missing: in.Missing} -} diff --git a/internal/agent/harness/sufficiency_ladder_test.go b/internal/agent/harness/sufficiency_ladder_test.go deleted file mode 100644 index 5609536b74e..00000000000 --- a/internal/agent/harness/sufficiency_ladder_test.go +++ /dev/null @@ -1,123 +0,0 @@ -// -// 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. -// - -package harness - -import "testing" - -// TestSufficiencyLadder_HardVeto asserts a code-proven evidence gap vetoes a full -// answer even when the AutoRater says sufficient. -func TestSufficiencyLadder_HardVeto(t *testing.T) { - out := SufficiencyLadder(LadderInput{ - AutoSufficient: true, AutoConfidence: 0.9, AgentConfidence: 0.9, - CHigh: 0.7, CLow: 0.4, LLMFloor: 0.5, AllowsReconcile: true, - Cycle: 0, MaxCycles: 3, - HardViolations: map[string][]string{"c2": {}}, - }) - if out.Action != ActionAnswerWithCaveat || out.ShouldContinue { - t.Errorf("hard veto → caveated non-continuing answer, got action=%s continue=%v", out.Action, out.ShouldContinue) - } -} - -// TestSufficiencyLadder_InsufficientGap asserts !auto_sufficient with missing -// pieces → GAP (continue searching). -func TestSufficiencyLadder_InsufficientGap(t *testing.T) { - out := SufficiencyLadder(LadderInput{ - AutoSufficient: false, AutoConfidence: 0.8, Missing: []string{"population figure"}, - AgentConfidence: 0.3, CHigh: 0.7, CLow: 0.4, LLMFloor: 0.5, - AllowsReconcile: true, Cycle: 0, MaxCycles: 3, - }) - if out.Action != ActionGap || !out.ShouldContinue { - t.Errorf("insufficient with missing → GAP + continue, got action=%s continue=%v", out.Action, out.ShouldContinue) - } -} - -// TestSufficiencyLadder_UnanswerableNoMissing asserts !auto_sufficient without -// missing pieces → UNANSWERABLE. -func TestSufficiencyLadder_UnanswerableNoMissing(t *testing.T) { - out := SufficiencyLadder(LadderInput{ - AutoSufficient: false, AutoConfidence: 0.8, AgentConfidence: 0.1, - CHigh: 0.7, CLow: 0.4, LLMFloor: 0.5, AllowsReconcile: true, - Cycle: 0, MaxCycles: 3, - }) - if out.Action != ActionUnanswerable { - t.Errorf("insufficient + no missing → UNANSWERABLE, got %s", out.Action) - } -} - -// TestSufficiencyLadder_Reconcile asserts low AutoRater confidence with reconcile -// enabled → RECONCILE (continue). -func TestSufficiencyLadder_Reconcile(t *testing.T) { - out := SufficiencyLadder(LadderInput{ - AutoSufficient: true, AutoConfidence: 0.3, AgentConfidence: 0.6, - CHigh: 0.7, CLow: 0.4, LLMFloor: 0.5, AllowsReconcile: true, - Cycle: 0, MaxCycles: 3, - }) - if out.Action != ActionReconcile || !out.ShouldContinue { - t.Errorf("low AutoRater confidence + reconcile → RECONCILE, got action=%s continue=%v", out.Action, out.ShouldContinue) - } -} - -// TestSufficiencyLadder_AnswerConfidenceTiers asserts agent confidence drives -// ANSWER vs ANSWER_WITH_CAVEAT. -func TestSufficiencyLadder_AnswerConfidenceTiers(t *testing.T) { - // high confidence → ANSWER. - hi := SufficiencyLadder(LadderInput{ - AutoSufficient: true, AutoConfidence: 0.9, AgentConfidence: 0.9, - CHigh: 0.7, CLow: 0.4, LLMFloor: 0.5, AllowsReconcile: true, - Cycle: 0, MaxCycles: 3, - }) - if hi.Action != ActionAnswer { - t.Errorf("high confidence → ANSWER, got %s", hi.Action) - } - // mid confidence → ANSWER_WITH_CAVEAT. - mid := SufficiencyLadder(LadderInput{ - AutoSufficient: true, AutoConfidence: 0.9, AgentConfidence: 0.5, - CHigh: 0.7, CLow: 0.4, LLMFloor: 0.5, AllowsReconcile: true, - Cycle: 0, MaxCycles: 3, - }) - if mid.Action != ActionAnswerWithCaveat { - t.Errorf("mid confidence → ANSWER_WITH_CAVEAT, got %s", mid.Action) - } -} - -// TestSufficiencyLadder_ContradictionSurfacesCaveat asserts contradictions force a -// caveated answer regardless of confidence. -func TestSufficiencyLadder_ContradictionSurfacesCaveat(t *testing.T) { - out := SufficiencyLadder(LadderInput{ - AutoSufficient: true, AutoConfidence: 0.9, AgentConfidence: 0.9, - Contradictions: []string{"2,161,000 vs 2,145,906"}, - CHigh: 0.7, CLow: 0.4, LLMFloor: 0.5, AllowsReconcile: true, - Cycle: 0, MaxCycles: 3, - }) - if out.Action != ActionAnswerWithCaveat { - t.Errorf("contradiction → ANSWER_WITH_CAVEAT, got %s", out.Action) - } -} - -// TestAggregateAgentConfidence asserts the mean excludes unverified claims and -// hard-violated claims. -func TestAggregateAgentConfidence(t *testing.T) { - results := []AgentResult{ - {ClaimID: "a", IsVerified: true, Confidence: 0.9}, - {ClaimID: "b", IsVerified: true, Confidence: 0.5}, - {ClaimID: "c", IsVerified: false, Confidence: 0.9}, // unverified → excluded - } - got := AggregateAgentConfidence(results, map[string][]string{"b": {}}) // b violated → excluded - if got != 0.9 { - t.Errorf("AggregateAgentConfidence = %v, want 0.9 (only a counts)", got) - } -} diff --git a/internal/agent/harness/sufficiency_llm.go b/internal/agent/harness/sufficiency_llm.go deleted file mode 100644 index 53aa1338968..00000000000 --- a/internal/agent/harness/sufficiency_llm.go +++ /dev/null @@ -1,499 +0,0 @@ -// -// 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. -// - -package harness - -import ( - "context" - "fmt" - "regexp" - "sort" - "strings" - - "github.com/cloudwego/eino/schema" - - "gorm.io/gorm" - "ragflow/internal/agent/chat" -) - -// LLM Sufficient Context AutoRater (mirrors Python sufficiency_llm.py + -// rag/prompts/sufficiency_select.md). It is the *primary* sufficiency judge in -// the decision-ladder design: it decides whether the retrieved evidence supports -// a plausible answer, and on "insufficient" returns concrete missing information -// that becomes follow-up search queries. - -// sufficiencySelectPrompt mirrors rag/prompts/sufficiency_select.md. -const sufficiencySelectPrompt = `You are an information retrieval evaluation expert. Determine whether the retrieved content is sufficient to answer the user's question(s), following the "Sufficient Context" criterion: - -The CONTEXT is sufficient to answer the question if and only if a PLAUSIBLE answer can be inferred from it — that is, the retrieved content either directly contains or logically entails an answer to the question. The answer does NOT need to be proven correct; it only needs to be a reasonable, supportable answer. If the context cannot be used to infer any plausible answer, it is INSUFFICIENT. - -Each retrieved chunk is labeled with an integer ID on a line like ` + "`ID: 3`" + `. - -User question(s): -%s - -Retrieved content: -%s - -Reasoning procedure (do this step-by-step before answering): -1. Identify the REQUIRED ENTITIES or key facts that a plausible answer to the question must involve. -2. For each required entity, check whether the retrieved content provides evidence about it. Record this in "coverage". -3. Check for multi-hop inference: if answering requires combining facts not present in the context, or inferring a connection the context does not state, that is NOT inferable from the context. -4. Check whether the context is ambiguous: if it could support multiple mutually exclusive plausible answers and nothing in the context lets you distinguish them, mark it insufficient. -5. Note any internally conflicting figures/statements in the context ("contradictions"). -6. Decide whether a plausible answer can be inferred; give your confidence in that decision. - -Output format (JSON): -{ - "Sufficient Context": true/false, - "is_sufficient": true/false, - "required_entities": ["Entity 1", "Entity 2"], - "coverage": {"Entity 1": true, "Entity 2": false}, - "missing_information": ["Missing information 1", "Missing information 2"], - "contradictions": ["conflicting figures/statements if any"], - "confidence": 0.0, - "reasoning": "Step-by-step reasoning for the judgment", - "useful_chunk_ids": [0, 3, 7] -} - -Requirements: -1. ` + "`Sufficient Context`" + ` / ` + "`is_sufficient`" + ` must be true if and only if a plausible answer can be inferred from the context (per the definition above). A missing detail that a reasonable answer would still require makes it false. -2. If not sufficient, list the concrete ` + "`missing_information`" + `. -3. ` + "`coverage`" + ` must mark, for each required entity, whether the context provides evidence about it. Missing required entities belong in ` + "`missing_information`" + `. -4. ` + "`confidence`" + ` (0-1): how confident you are in your sufficiency decision. 0.9-1.0 if the context clearly supports or clearly fails a plausible answer; 0.5-0.7 if evidence is partial or ambiguous; below 0.5 if you cannot tell. -5. ` + "`contradictions`" + `: list any internally conflicting figures/statements that would make a single answer ambiguous. Empty array when none. -6. ` + "`useful_chunk_ids`" + ` must contain ONLY the integer IDs (taken from the ` + "`ID:`" + ` labels above) of chunks that provide information useful for answering the question(s). Exclude irrelevant or redundant chunks. Use an empty array when none are useful. -7. The ` + "`missing_information`" + ` should only be filled when insufficient, otherwise an empty array. -8. The ` + "`reasoning`" + ` should be concise and clear.` - -const ( - maxEvidenceChunksLLM = 24 - maxChunkCharsLLM = 800 - maxEvidenceCharsLLM = 24000 -) - -type sufficiencySelectResult struct { - SufficientContext bool `json:"Sufficient Context"` - IsSufficient bool `json:"is_sufficient"` - RequiredEntities []string `json:"required_entities"` - Coverage map[string]bool `json:"coverage"` - MissingInfo []string `json:"missing_information"` - Contradictions []string `json:"contradictions"` - Confidence float64 `json:"confidence"` - Reasoning string `json:"reasoning"` - UsefulChunkIDs []int `json:"useful_chunk_ids"` -} - -var reNarrowTokens = regexp.MustCompile(`[a-zA-Z0-9]+|[\x{4e00}-\x{9fff}]+`) - -// narrowKeywords mirrors Python _narrow_keywords: language-agnostic keywords for -// snippet narrowing (numeric tokens, latin len>=4, CJK character bigrams). -func narrowKeywords(question string) []string { - tokens := reNarrowTokens.FindAllString(strings.ToLower(question), -1) - var kw []string - for _, t := range tokens { - if isDigits(t) { - kw = append(kw, t) - } else if containsLatin(t) { - if len(t) >= 4 { - kw = append(kw, t) - } - } else { - // CJK run → character bigrams - rs := []rune(t) - for i := 0; i+1 < len(rs); i++ { - kw = append(kw, string(rs[i:i+2])) - } - } - } - return kw -} - -func isDigits(s string) bool { - for _, r := range s { - if r < '0' || r > '9' { - return false - } - } - return len(s) > 0 -} - -func containsLatin(s string) bool { - for _, r := range s { - if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') { - return true - } - } - return false -} - -// renderEvidenceMD renders the cited evidence chunks with "ID: n" markers, -// mirroring Python _evidence_md. Prefers the chunks referenced by evidenceIDs; -// falls back to a bounded prefix of the pool when none are given. -func renderEvidenceMD(kb *Kbinfos, evidenceIDs []int, keywords []string) string { - if kb == nil || len(kb.Chunks) == 0 { - return "" - } - var picked []int - if len(evidenceIDs) > 0 { - seen := map[int]bool{} - for _, eid := range evidenceIDs { - if eid >= 0 && eid < len(kb.Chunks) && !seen[eid] { - seen[eid] = true - picked = append(picked, eid) - } - if len(picked) >= maxEvidenceChunksLLM { - break - } - } - } - if len(picked) == 0 { - n := len(kb.Chunks) - if n > maxEvidenceChunksLLM { - n = maxEvidenceChunksLLM - } - for i := 0; i < n; i++ { - picked = append(picked, i) - } - } - - var blocks []string - used := 0 - for _, idx := range picked { - c := kb.Chunks[idx] - raw := chunkText(c) - title := chunkDoc(c) - if len(keywords) > 0 { - if narrowed := narrowSnippetSafe(raw, keywords); narrowed != "" { - raw = narrowed - } - } - if len(raw) > maxChunkCharsLLM { - raw = raw[:maxChunkCharsLLM] - } - if used+len(raw) > maxEvidenceCharsLLM { - break - } - blocks = append(blocks, fmt.Sprintf("ID: %d | %s\n%s", idx, title, raw)) - used += len(raw) + 8 - } - return strings.Join(blocks, "\n\n") -} - -// narrowSnippetSafe mirrors Python _narrow_snippet_safe: keep keyword-bearing -// sentences (plus one neighbour) only when keywords cover a meaningful share. -// Returns "" to signal "keep the whole chunk". -func narrowSnippetSafe(content string, kw []string) string { - sents := splitSentences(content) - if len(sents) <= 3 { - return "" - } - lower := make([]string, len(sents)) - for i, s := range sents { - lower[i] = strings.ToLower(s) - } - var hitIdx []int - for i, s := range lower { - for _, k := range kw { - if strings.Contains(s, k) { - hitIdx = append(hitIdx, i) - break - } - } - } - if len(hitIdx) < 2 { - return "" - } - keep := map[int]bool{} - for _, i := range hitIdx { - for j := i - 1; j <= i+1; j++ { - if j >= 0 && j < len(sents) { - keep[j] = true - } - } - } - // Preserve order. - var out []string - for i := 0; i < len(sents); i++ { - if keep[i] { - out = append(out, sents[i]) - } - } - return strings.Join(out, " ") -} - -// Sentence splitting mirrors Python tools/search.py _split_sentences: -// - terminators are KEPT on their sentence (。!?;!?; plus a digit-guarded -// English period so "3.14" / "v1.2" do not split); -// - table blocks (HTML and markdown tables) are ATOMIC — never split -// internally. -// -// Go's RE2 lacks lookbehind, so the digit-guard is handled by a manual scan. -var ( - reHTMLTable = regexp.MustCompile(`(?is)]*>.*?
`) - reMDTable = regexp.MustCompile("(?m)^[ \t]*\\|?[^\n]*\\|[^\n]*\r?\n[ \t]*\\|?[ \t]*:?-{1,}:?[ \t]*(?:\\|[ \t]*:?-{1,}:?[ \t]*)+\\|?[ \t]*\r?\n(?:[ \t]*\\|?[^\n]*\\|[^\n]*\r?\n?)*") -) - -func splitSentences(text string) []string { - if text == "" { - return nil - } - // Collect non-overlapping table spans (HTML + markdown), in order. - var spans [][2]int - spans = append(spans, matchSpans(reHTMLTable, text)...) - spans = append(spans, matchSpans(reMDTable, text)...) - sort.Slice(spans, func(i, j int) bool { return spans[i][0] < spans[j][0] }) - var merged [][2]int - lastEnd := -1 - for _, s := range spans { - if s[0] < lastEnd { - continue - } - merged = append(merged, s) - lastEnd = s[1] - } - - var sents []string - pos := 0 - for _, m := range merged { - if m[0] > pos { - sents = append(sents, splitPlainSentences(text[pos:m[0]])...) - } - if block := strings.TrimSpace(text[m[0]:m[1]]); block != "" { - sents = append(sents, block) - } - pos = m[1] - } - if pos < len(text) { - sents = append(sents, splitPlainSentences(text[pos:])...) - } - return sents -} - -func matchSpans(re *regexp.Regexp, text string) [][2]int { - matches := re.FindAllStringIndex(text, -1) - out := make([][2]int, 0, len(matches)) - for _, m := range matches { - out = append(out, [2]int{m[0], m[1]}) - } - return out -} - -// splitPlainSentences splits plain text (no table blocks) into sentences, -// keeping each terminator attached and guarding decimal periods. Operates on -// runes; rune indices == byte indices for the ASCII terminators we emit. -func splitPlainSentences(text string) []string { - rs := []rune(text) - var sents []string - start := 0 - for i := 0; i < len(rs); i++ { - r := rs[i] - if !isSentTerminator(r) { - continue - } - // ASCII period guarded against decimals (digit on BOTH sides). - if r == '.' && i > 0 && i+1 < len(rs) && isASCIIDigit(rs[i-1]) && isASCIIDigit(rs[i+1]) { - continue - } - // Consume a run of terminators (e.g. "。!?" or "..."). - j := i + 1 - for j < len(rs) && isSentTerminator(rs[j]) && rs[j] != '.' { - j++ - } - seg := strings.TrimSpace(string(rs[start:j])) - if seg != "" { - sents = append(sents, seg) - } - start = j - i = j - 1 - } - if start < len(rs) { - if tail := strings.TrimSpace(string(rs[start:])); tail != "" { - sents = append(sents, tail) - } - } - return sents -} - -func isSentTerminator(r rune) bool { - switch r { - case '。', '!', '?', ';', '!', '?', ';', '.': - return true - } - return false -} - -func isASCIIDigit(r rune) bool { return r >= '0' && r <= '9' } - -// LLMSufficiencyBoost mirrors Python llm_sufficiency_boost: run the AutoRater on -// the cited evidence and return an AutoRating. Returns nil when no LLM judge is -// available or the verdict is already clear (SUFFICIENT/UNANSWERABLE). -func LLMSufficiencyBoost(ctx context.Context, db *gorm.DB, question string, verdict *SufficiencyVerdict, kb *Kbinfos, evidenceIDs []int) *AutoRating { - if verdict == nil { - return nil - } - switch verdict.Status { - case "USEFUL_BUT_INCOMPLETE", "INSUFFICIENT", "CONFLICTING": - // boost applicable - default: - return nil - } - inv := chat.GetDefaultInvoker() - if inv == nil { - return nil - } - evidenceMD := renderEvidenceMD(kb, evidenceIDs, narrowKeywords(question)) - if evidenceMD == "" { - return nil - } - prompt := fmt.Sprintf(sufficiencySelectPrompt, question, evidenceMD) - resp, err := inv.Invoke(ctx, db, chat.Request{ - Messages: []schema.Message{ - {Role: schema.System, Content: prompt}, - }, - }) - if err != nil { - return nil - } - var res sufficiencySelectResult - if err := unmarshalModelJSON(resp.Content, &res); err != nil { - return nil - } - isSuff := res.IsSufficient || res.SufficientContext - missing := filterNonEmpty(res.MissingInfo) - contradictions := filterNonEmpty(res.Contradictions) - confidence := clamp01(res.Confidence) - rating := &AutoRating{ - IsSufficient: isSuff, - Confidence: confidence, - Missing: missing, - Contradictions: contradictions, - } - // Phase-2: when the AutoRater says insufficient with concrete gaps, generate - // complementary follow-up search queries for the next round (mirrors Python - // gen_followups → multi_queries_gen). This is the missing-piece feedback loop. - if !isSuff && len(missing) > 0 { - rating.Followups = genFollowups(ctx, db, question, missing, evidenceMD) - } - return rating -} - -// multiQueriesGenPrompt mirrors rag/prompts/multi_queries_gen.md. -const multiQueriesGenPrompt = `You are a query optimization expert. -The user's original query failed to retrieve sufficient information; -please generate multiple complementary improved questions and corresponding queries. - -Original query: -%s - -Original question: -%s - -Currently, retrieved content: -%s - -Missing information: -%s - -Please generate 2-3 complementary queries to help find the missing information. These queries should: -1. Focus on different missing information points. -2. Use different expressions. -3. Avoid being identical to the original query. -4. Remain concise and clear. - -Output format (JSON): -{ - "reasoning": "Explanation of query generation strategy", - "questions": [ - {"question": "Improved question 1", "query": "Improved query 1"} - ] -} - -Requirements: -1. Questions array contains 1-3 questions and corresponding queries. -2. Each question length is between 5-200 characters. -3. Each query length is between 1-5 keywords. -4. Each query MUST be in the same language as the retrieved content in. -5. DO NOT generate question and query that is similar to the original query. -6. Reasoning explains the generation strategy.` - -type multiQueriesResult struct { - Reasoning string `json:"reasoning"` - Questions []multiQueriesItem `json:"questions"` -} - -type multiQueriesItem struct { - Question string `json:"question"` - Query string `json:"query"` -} - -// genFollowups mirrors Python gen_followups → multi_queries_gen: generate -// complementary follow-up search queries for the missing information. Returns -// the "query or question" strings the research agent injects as targeted -// follow-up searches (mirrors agentic.py:98). -func genFollowups(ctx context.Context, db *gorm.DB, question string, missing []string, evidenceMD string) []string { - inv := chat.GetDefaultInvoker() - if inv == nil { - return nil - } - // Fit evidence (mirrors _fit_evidence: bounded truncation already done by - // renderEvidenceMD, so reuse it verbatim). - missingStr := "\n - " + strings.Join(missing, "\n - ") - prompt := fmt.Sprintf(multiQueriesGenPrompt, question, question, evidenceMD, missingStr) - resp, err := inv.Invoke(ctx, db, chat.Request{ - Messages: []schema.Message{ - {Role: schema.System, Content: prompt}, - }, - }) - if err != nil { - return nil - } - var res multiQueriesResult - if err := unmarshalModelJSON(resp.Content, &res); err != nil { - return nil - } - var out []string - for _, q := range res.Questions { - v := strings.TrimSpace(q.Query) - if v == "" { - v = strings.TrimSpace(q.Question) - } - if v != "" { - out = append(out, v) - } - } - return out -} - -func filterNonEmpty(in []string) []string { - var out []string - for _, s := range in { - if strings.TrimSpace(s) != "" { - out = append(out, strings.TrimSpace(s)) - } - } - return out -} - -func clamp01(v float64) float64 { - if v < 0 { - return 0 - } - if v > 1 { - return 1 - } - return v -} diff --git a/internal/agent/harness/types.go b/internal/agent/harness/types.go deleted file mode 100644 index e4069498010..00000000000 --- a/internal/agent/harness/types.go +++ /dev/null @@ -1,187 +0,0 @@ -// -// 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. -// - -// Package harness ports Python's rag/advanced_rag/harness (agentic-RAG): -// route → planner → orchestrator → formalize_answer. This is a phased port; see -// tasks/agentic_search_port_plan.md §P4. -package harness - -// RouteDecision mirrors Python RouteDecision. -type RouteDecision struct { - Question string - ThinkingMode string - QuestionType string // factual | comparative | analytical | procedural | exploratory | verification | summarization - RequiresDecomposition bool - ExecutionStrategy string // direct_search | decompose_and_search | agentic_research | deep_research - // SuggestsCompilation is the compiled-artifact type the route suggests using - // for retrieval: "" (none) | "toc" | "graph" | "wiki". Mirrors Python's - // route `suggests_compilation`. It is preserved so the production runner can - // prefer a compiled wiki/graph tool when the bound KBs actually carry the - // artifact, and fall back to general hybrid search otherwise. - SuggestsCompilation string - Reasoning string -} - -// ClaimTarget mirrors Python ClaimTarget. -type ClaimTarget struct { - ClaimID string - Description string - Priority int - SuggestedTools []string - IsVerified bool - Confidence float64 - AgentResult *AgentResult -} - -// WorkflowPlan mirrors Python WorkflowPlan. -type WorkflowPlan struct { - PlanType string // direct | fact_decomposition | ... - Claims []ClaimTarget - MaxIterations int -} - -// ExecutionStrategy mirrors Python ExecutionStrategy and is instantiated by the -// four thinking modes. -type ExecutionStrategy struct { - Label string - Strategy string - RequiresDecomposition bool - MaxOrchestratorCycles int - MaxAgentCycles int - MaxParallelAgents int - AvailableTools []string - SufficiencyThreshold float64 - PartialThreshold float64 - FallbackToDirectLLM bool - RequiresSelectiveGen bool - AllowsReplan bool - // Decision-ladder thresholds (Sufficient Context redesign). CHigh/CLow gate - // full vs. caveated answer from aggregated agent confidence; LLMFloor is the - // minimum AutoRater confidence before a reconcile/re-investigation. - CHigh float64 - CLow float64 - LLMFloor float64 - // AllowsReconcile mirrors Python allows_reconcile: whether the mode may force - // a re-investigation when confidence is low (medium=false). - AllowsReconcile bool - // AllowsDynamicClaims mirrors Python allows_dynamic_claims: ultra only. - AllowsDynamicClaims bool -} - -// AgentResult mirrors Python AgentResult. -type AgentResult struct { - ClaimID string - Report string - IsVerified bool - Confidence float64 - EvidenceIDs []int - Gaps []string - DiscoveredClaims []string - // Grounded lists the key assertions the agent claims are evidence-backed - // (Python schema field `grounded`). Unused at the code level while the - // lexical grounded-fact check is disabled (_ENABLE_NER_GROUNDED=False); - // reserved for the grounded review path. - Grounded []string - // Numbers lists the distinct figures the agent *disclosed* in its report, - // used for multi-source numeric-conflict detection (Python `numbers`). - Numbers []string -} - -// ClaimCrossCheckResult mirrors Python ClaimCrossCheckResult. -type ClaimCrossCheckResult struct { - ClaimID string - CrossCheckPassed bool - CrossCheckScore float64 - EvidenceMatches []string - Mismatches []string - // HasEvidence reports whether any evidence chunk was actually examined. When - // false the claim had no resolvable evidence, so it cannot be considered - // verified regardless of the other fields. - HasEvidence bool -} - -// SufficiencyVerdict mirrors Python SufficiencyVerdict. -type SufficiencyVerdict struct { - Status string // SUFFICIENT | USEFUL_BUT_INCOMPLETE | INSUFFICIENT | CONFLICTING | UNANSWERABLE - Score float64 - AgentScore float64 - CrossScore float64 - ClaimAssessments []map[string]interface{} - HasConflicts bool - MissingClaims []string - Feedback string - OverallReason string - // Decision-ladder inputs (Sufficient Context redesign): - // - HardViolations: claim IDs with a code-proven evidence gap that veto a - // full answer even when the AutoRater says sufficient. - // - AgentConfidence: mean self-confidence over the trusted claim subset. - HardViolations []string - AgentConfidence float64 -} - -// OrchestratorContext mirrors Python OrchestratorContext. -type OrchestratorContext struct { - Question string - Claims []*ClaimTarget - Mode string - Iteration int -} - -// THINKING_MODES mirrors Python config.THINKING_MODES. -var THINKING_MODES = map[string]ExecutionStrategy{ - "low": { - Label: "low", Strategy: "direct_search", RequiresDecomposition: false, - MaxOrchestratorCycles: 1, MaxAgentCycles: 0, MaxParallelAgents: 1, - AvailableTools: []string{"hybrid_search"}, SufficiencyThreshold: 0.85, PartialThreshold: 0.50, - }, - "medium": { - Label: "medium", Strategy: "decompose_and_search", RequiresDecomposition: true, - MaxOrchestratorCycles: 3, MaxAgentCycles: 0, MaxParallelAgents: 1, - AvailableTools: []string{"hybrid_search"}, SufficiencyThreshold: 0.75, PartialThreshold: 0.40, - RequiresSelectiveGen: true, - CHigh: 0.75, CLow: 0.45, LLMFloor: 0.55, AllowsReconcile: false, - }, - "high": { - Label: "high", Strategy: "agentic_research", RequiresDecomposition: true, - MaxOrchestratorCycles: 3, MaxAgentCycles: 2, MaxParallelAgents: 2, - AvailableTools: []string{ - "hybrid_search", "web_search", "ontology_navigate", "dataset_navigation_by_tree", - "graph_explore", "inspector_open_context", "inspector_compare", - }, - SufficiencyThreshold: 0.65, PartialThreshold: 0.30, - RequiresSelectiveGen: true, AllowsReplan: true, - CHigh: 0.70, CLow: 0.40, LLMFloor: 0.50, AllowsReconcile: true, - }, - "ultra": { - Label: "ultra", Strategy: "deep_research", RequiresDecomposition: true, - MaxOrchestratorCycles: 4, MaxAgentCycles: 2, MaxParallelAgents: 3, - AvailableTools: []string{ - "hybrid_search", "bm25_search", "web_search", "structured_query", - "ontology_navigate", "dataset_navigation_by_tree", "mindmap_navigate", - "graph_explore", "wiki_query", "inspector_open_context", "inspector_compare", - "inspector_grep_within", "inspector_request_adjacent", - }, - SufficiencyThreshold: 0.55, PartialThreshold: 0.20, FallbackToDirectLLM: true, - RequiresSelectiveGen: true, AllowsReplan: true, - CHigh: 0.65, CLow: 0.35, LLMFloor: 0.45, AllowsReconcile: true, AllowsDynamicClaims: true, - }, -} - -// GetMode mirrors Python get_mode(label). -func GetMode(label string) (ExecutionStrategy, bool) { - m, ok := THINKING_MODES[label] - return m, ok -} diff --git a/internal/agent/retrievalbridge/runtime_adapter.go b/internal/agent/retrievalbridge/runtime_adapter.go new file mode 100644 index 00000000000..2feae1dc842 --- /dev/null +++ b/internal/agent/retrievalbridge/runtime_adapter.go @@ -0,0 +1,112 @@ +// +// 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. +// + +package retrievalbridge + +import ( + "context" + + agentrunt "ragflow/internal/agent/runtime" + agenttool "ragflow/internal/agent/tool" + "ragflow/internal/dao" + + "gorm.io/gorm" +) + +// RuntimeAdapter exposes the agent tool's NLPRetrievalAdapter (the production +// hybrid-retrieval backend installed by the server) through the runtime +// RetrievalService singleton that the agentic-RAG harness reads via +// harness.RuntimeRetriever. The wrapped tool service is read on every call (not +// captured at construction) because the server installs it during boot. +// +// This keeps a single retrieval implementation: the harness and the canvas both +// search through the same NLPRetrievalAdapter. +type RuntimeAdapter struct{} + +// NewRuntimeAdapter creates the runtime RetrievalService bridge. +func NewRuntimeAdapter() *RuntimeAdapter { + return &RuntimeAdapter{} +} + +// Search forwards a runtime retrieval request to the installed tool service and +// translates the result back to the runtime chunk shape. +func (a *RuntimeAdapter) Search(ctx context.Context, db *gorm.DB, req agentrunt.RetrievalRequest) ([]agentrunt.RetrievalChunk, error) { + svc := agenttool.GetRetrievalService() + if svc == nil { + return nil, agenttool.ErrRetrievalServiceMissing + } + // The harness calls the runtime service with a nil *gorm.DB (see + // harness.RuntimeRetriever.Retrieve), while the underlying NLPRetrievalAdapter + // needs a real connection to resolve knowledge bases. Fall back to the + // process-wide DB handle used by the rest of the chat pipeline. + if db == nil { + db = dao.DB + } + toolReq := agenttool.RetrievalRequest{ + Query: req.Query, + DatasetIDs: req.DatasetIDs, + MemoryIDs: req.MemoryIDs, + TopN: req.TopN, + RerankCandidatesCount: req.RerankCandidatesCount, + TopK: req.TopK, + KeywordsSimilarityWeight: req.KeywordsSimilarityWeight, + UseKG: req.UseKG, + SimilarityThreshold: req.SimilarityThreshold, + CrossLanguages: req.CrossLanguages, + RetrievalFrom: req.RetrievalFrom, + DocScope: req.DocScope, + TenantID: req.TenantID, + // rank_feature (Python retrieve: rank_feature=label_question(question, + // self.kbs)) — forwarded from the RAGTools-computed value so the agentic + // tool stays authoritative; the adapter falls back to its own resolution. + RankFeature: rankFeatureOrNil(req.RankFeature), + // OnlyOriginalText restricts retrieval to ordinary document chunks (no + // compile_kwd) — Python hybrid_search's must_not={"exists":"compile_kwd"}. + ExcludeCompiled: req.OnlyOriginalText, + } + chunks, err := svc.Search(ctx, db, toolReq) + if err != nil { + return nil, err + } + out := make([]agentrunt.RetrievalChunk, 0, len(chunks)) + for _, c := range chunks { + out = append(out, agentrunt.RetrievalChunk{ + ID: c.ID, + Content: c.Content, + DocumentID: c.DocumentID, + DocumentName: c.DocumentName, + DatasetID: c.DatasetID, + ImageID: c.ImageID, + URL: c.URL, + Positions: c.Positions, + Score: c.Score, + TermSimilarity: c.TermSimilarity, + VectorSimilarity: c.VectorSimilarity, + MomID: c.MomID, + }) + } + return out, nil +} + +// rankFeatureOrNil converts a map-valued rank feature into the pointer form the +// tool request expects, returning nil when empty so a missing feature is +// distinguished from an empty one (Python passes None for "no rank feature"). +func rankFeatureOrNil(m map[string]float64) *map[string]float64 { + if len(m) == 0 { + return nil + } + return &m +} diff --git a/internal/agent/runtime/helpers.go b/internal/agent/runtime/helpers.go index 31e3b35b2d5..fd6df02856c 100644 --- a/internal/agent/runtime/helpers.go +++ b/internal/agent/runtime/helpers.go @@ -104,7 +104,7 @@ func WithProgressMessageCallback(ctx context.Context, cb ProgressMessageCallback // ReportProgressMessage forwards a detailed component message when a sink is // attached. Components can call this without depending on the persistence -// layer or changing the lifecycle progress contract. +// layer or changing the lifecycle progress func ReportProgressMessage(ctx context.Context, component, message string) { if cb, ok := ctx.Value(progressMessageCallbackKey{}).(ProgressMessageCallback); ok && cb != nil { cb(component, message) diff --git a/internal/agent/runtime/registry_test.go b/internal/agent/runtime/registry_test.go index 039b9bfaf87..0d56d03c71d 100644 --- a/internal/agent/runtime/registry_test.go +++ b/internal/agent/runtime/registry_test.go @@ -313,7 +313,7 @@ func TestRegistry_ThreadSafe(t *testing.T) { func TestRegistry_FactoryErrorPropagates(t *testing.T) { // A factory that returns an error must propagate that error through // the Lookup → invoke path. This is not directly tested by the - // plan checklist but it confirms the factory closure contract. + // plan checklist but it confirms the factory closure r := NewMemoryRegistry() wantErr := errors.New("boom") if err := r.Register("Bad", CategoryAgent, errFactory(wantErr), Metadata{Version: "legacy"}); err != nil { diff --git a/internal/agent/runtime/retrieval.go b/internal/agent/runtime/retrieval.go index e83e19ab751..e7fe3c05bd1 100644 --- a/internal/agent/runtime/retrieval.go +++ b/internal/agent/runtime/retrieval.go @@ -17,7 +17,7 @@ // Retrieval contracts shared by the canvas agent runtime (internal/agent/tool) // and the smart-reasoning agent (internal/agentic_rag). Keeping these here — // in the engine-agnostic runtime package — means neither agent layer depends on -// the other: both depend on this shared contract. +// the other: both depend on this shared package runtime import ( @@ -46,7 +46,12 @@ type RetrievalChunk struct { // a document sequentially rather than in arbitrary match order. ChunkIndex int // PageNum is the chunk's page number within its document (ES `page_num_int`). - PageNum int + PageNum int + // MomID is the parent chunk id when this chunk is a child fragment; empty + // for top-level chunks. It is threaded through so the harness can run + // retrieval_by_children (child fragments are promoted to their parent chunk) + // after search, mirroring Python settings.retriever.retrieval_by_children. + MomID string Score float64 TermSimilarity float64 VectorSimilarity float64 @@ -72,6 +77,10 @@ type RetrievalRequest struct { DocScope []string // TenantID is the calling tenant (== user_id in RAGFlow's data model). TenantID string + // RankFeature is the label_question term→weight map passed through to the + // engine so retrieval is biased toward the query's predicted topic class. + // Mirrors engine nlp.RetrievalRequest.RankFeature. + RankFeature map[string]float64 // OnlyOriginalText, when true, restricts retrieval to ordinary document // text chunks (available_int=1 and no compile_kwd), excluding // knowledge-compiled products. diff --git a/internal/agent/tool/agentic_search.go b/internal/agent/tool/agentic_search.go index 3cbd2cb43c1..98ab03eea3a 100644 --- a/internal/agent/tool/agentic_search.go +++ b/internal/agent/tool/agentic_search.go @@ -28,12 +28,15 @@ import ( ) // Agentic search tool names mirror Python rag/advanced_rag/harness/tools/search.py. +// +// Only the three retrieval modes are canvas tools. The harness' other names +// (web_search, structured_query) have no canvas counterpart and are therefore +// deliberately absent: Python's canvas reaches the web through its provider +// tools (tavily / duckduckgo / …) and registers neither name in agent/tools/. const ( - toolHybridSearch = "hybrid_search" - toolVectorSearch = "vector_search" - toolBM25Search = "bm25_search" - toolWebSearch = "web_search" - toolStructuredQuery = "structured_query" + toolHybridSearch = "hybrid_search" + toolVectorSearch = "vector_search" + toolBM25Search = "bm25_search" ) // hybridSearchArgs is the shared JSON schema for the three retrieval tools. diff --git a/internal/agent/tool/dataset_navigation.go b/internal/agent/tool/dataset_navigation.go index 0f33b6749ef..191d27fc725 100644 --- a/internal/agent/tool/dataset_navigation.go +++ b/internal/agent/tool/dataset_navigation.go @@ -151,7 +151,10 @@ func (d *DatasetNavigationByTree) InvokableRun(ctx context.Context, argumentsInJ // Primary: semantic search over each dataset's nav tree. for _, datasetID := range datasetIDs { - hits, err := ns.Search(ctx, tenantID, datasetID, query, nil, maxDocs) + // No doc scope: Python's dataset_navigation_by_tree applies + // tools.scoped_doc_ids(None), but this canvas tool's context carries no + // session document scope, so the read stays dataset-wide. + hits, err := ns.Search(ctx, tenantID, datasetID, query, nil, nil, maxDocs) if err != nil { continue } diff --git a/internal/agent/tool/dataset_navigation_test.go b/internal/agent/tool/dataset_navigation_test.go index 8491d8d34f2..75d7ad8821f 100644 --- a/internal/agent/tool/dataset_navigation_test.go +++ b/internal/agent/tool/dataset_navigation_test.go @@ -24,7 +24,7 @@ func (f *navRoutingFake) UpsertDoc(context.Context, nav.UpsertDocInput) error { func (f *navRoutingFake) RemoveDoc(context.Context, string, string, string) error { return nil } -func (f *navRoutingFake) Search(_ context.Context, _, _ string, query string, _ []float32, _ int) ([]nav.NavHit, error) { +func (f *navRoutingFake) Search(_ context.Context, _, _ string, query string, _ []float32, _ []string, _ int) ([]nav.NavHit, error) { f.mu.Lock() f.searched = append(f.searched, query) f.mu.Unlock() @@ -36,6 +36,9 @@ func (f *navRoutingFake) ListClusters(context.Context, string, string, int, int) func (f *navRoutingFake) ListChildren(_ context.Context, _, _, name string, _, _ int) ([]nav.NavNode, int64, error) { return f.children[name], int64(len(f.children[name])), nil } +func (f *navRoutingFake) SummariesByDocIDs(context.Context, string, string, []string) map[string]string { + return map[string]string{} +} func (f *navRoutingFake) searchedTopics() []string { f.mu.Lock() defer f.mu.Unlock() diff --git a/internal/agent/tool/retrieval_nlp.go b/internal/agent/tool/retrieval_nlp.go index e8c1e09bbab..d4ae6c70d9d 100644 --- a/internal/agent/tool/retrieval_nlp.go +++ b/internal/agent/tool/retrieval_nlp.go @@ -254,8 +254,14 @@ func (a *NLPRetrievalAdapter) Search(ctx context.Context, db *gorm.DB, req Retri } } query = retrievalUserPrefixPattern.ReplaceAllString(query, "") + // rank_feature (Python retrieve: rank_feature=label_question(question, + // self.kbs)). Prefer a feature supplied on the request (computed by RAGTools + // from its own KB objects) so the agentic tool stays authoritative; fall + // back to the enhancer, which resolves the KB objects itself. var rankFeature map[string]float64 - if a.enhancer != nil { + if req.RankFeature != nil && len(*req.RankFeature) > 0 { + rankFeature = *req.RankFeature + } else if a.enhancer != nil { rankFeature = a.enhancer.LabelQuestion(ctx, query, datasets.kbs) } rerankModel, err := a.resolveRerankModel(ctx, req, datasets.kbs[0].TenantID) @@ -266,7 +272,7 @@ func (a *NLPRetrievalAdapter) Search(ctx context.Context, db *gorm.DB, req Retri preparedReq.Query = query preparedReq.DocScope = docIDs preparedReq.DatasetIDs = append([]string(nil), datasets.kbIDs...) - nlpReq := nlpRequestFromRetrieval(preparedReq, datasets.tenantIDs, topN, embeddingModel) + nlpReq := nlpRequestFromRetrieval(preparedReq, datasets.tenantIDs, topN, embeddingModel, preparedReq.ExcludeCompiled) nlpReq.RerankModel = rerankModel if rankFeature != nil { nlpReq.RankFeature = &rankFeature @@ -313,6 +319,7 @@ func nlpRequestFromRetrieval( tenantIDs []string, topN int, embeddingModel *modelModule.EmbeddingModel, + excludeCompiled bool, ) *nlp.RetrievalRequest { nlpReq := &nlp.RetrievalRequest{ Question: req.Query, @@ -325,6 +332,15 @@ func nlpRequestFromRetrieval( Aggs: boolPtr(false), Highlight: boolPtr(false), } + if excludeCompiled { + // Python hybrid_search excludes compiled products from plain retrieval + // via must_not={"exists":"compile_kwd"} (search.py:171). Compiled rows + // carry the compile_kwd field; the nlp backend merges req.Filter into + // the doc-store term filter, so a must_not.exists excludes them. + nlpReq.Filter = map[string]interface{}{ + "must_not": map[string]interface{}{"exists": "compile_kwd"}, + } + } if req.RerankCandidatesCount != 0 { nlpReq.RerankCandidatesCount = &req.RerankCandidatesCount } @@ -544,6 +560,7 @@ func translateChunk(raw map[string]any) RetrievalChunk { ImageID: firstStringFromMap(raw, "image_id", "img_id"), URL: firstStringFromMap(raw, "url", "document_url", "doc_url"), Positions: firstValueFromMap(raw, "positions", "position_int"), + MomID: stringFromMap(raw, "mom_id"), Score: scoreFromMap(raw), TermSimilarity: scoreValueFromMap(raw, "term_similarity"), VectorSimilarity: scoreValueFromMap(raw, "vector_similarity"), diff --git a/internal/agent/tool/retrieval_nlp_test.go b/internal/agent/tool/retrieval_nlp_test.go index a6a1aa34ca4..e57d497c0aa 100644 --- a/internal/agent/tool/retrieval_nlp_test.go +++ b/internal/agent/tool/retrieval_nlp_test.go @@ -246,7 +246,7 @@ func TestNLPRequestFromRetrieval_ThreadsSearchControls(t *testing.T) { TopK: 99, KeywordsSimilarityWeight: &keywordWeight, SimilarityThreshold: &similarityThreshold, - }, []string{"tenant-a"}, 3, embeddingModel) + }, []string{"tenant-a"}, 3, embeddingModel, false) if got.Question != "hi" { t.Fatalf("Question=%q want hi", got.Question) @@ -279,7 +279,7 @@ func TestNLPRequestFromRetrieval_FallsBackToTopNHeadroom(t *testing.T) { Query: "hi", DatasetIDs: []string{"kb-1"}, TopN: 3, - }, []string{"tenant-a"}, 3, &modelModule.EmbeddingModel{}) + }, []string{"tenant-a"}, 3, &modelModule.EmbeddingModel{}, false) if got.KNNTopK == nil || *got.KNNTopK != 12 { t.Fatalf("KNNTopK=%v want 12", got.KNNTopK) @@ -295,13 +295,41 @@ func TestNLPRequestFromRetrieval_PreservesExplicitZeroSimilarityThreshold(t *tes Query: "hi", DatasetIDs: []string{"kb-1"}, SimilarityThreshold: &similarityThreshold, - }, []string{"tenant-a"}, 3, &modelModule.EmbeddingModel{}) + }, []string{"tenant-a"}, 3, &modelModule.EmbeddingModel{}, false) if got.SimilarityThreshold == nil || *got.SimilarityThreshold != 0 { t.Fatalf("SimilarityThreshold = %v; want explicit zero", got.SimilarityThreshold) } } +// TestNLPRequestFromRetrieval_ExcludeCompiled verifies the compiled-product +// exclusion reaches the nlp request as must_not={"exists":"compile_kwd"}, +// mirroring Python hybrid_search (search.py:171). +func TestNLPRequestFromRetrieval_ExcludeCompiled(t *testing.T) { + // excludeCompiled=false leaves Filter nil (no exclusion). + got := nlpRequestFromRetrieval(RetrievalRequest{ + Query: "hi", + DatasetIDs: []string{"kb-1"}, + }, []string{"tenant-a"}, 3, &modelModule.EmbeddingModel{}, false) + if got.Filter != nil { + t.Fatalf("Filter = %v; want nil when not excluding compiled", got.Filter) + } + // excludeCompiled=true sets must_not exists compile_kwd. + got = nlpRequestFromRetrieval(RetrievalRequest{ + Query: "hi", + DatasetIDs: []string{"kb-1"}, + }, []string{"tenant-a"}, 3, &modelModule.EmbeddingModel{}, true) + mustNot, ok := got.Filter["must_not"].(map[string]interface{}) + if !ok { + t.Fatalf("Filter.must_not = %v; want map", got.Filter["must_not"]) + } + // Python hybrid_search: must_not={"exists":"compile_kwd"} — the exists + // clause names the compile_kwd field, mirroring dataset/search.go:292. + if exists, ok := mustNot["exists"].(string); !ok || exists != "compile_kwd" { + t.Fatalf("must_not.exists = %v; want \"compile_kwd\"", mustNot["exists"]) + } +} + func TestNLPRetrievalAdapter_ResolveDatasetsRequiresEveryDataset(t *testing.T) { a := &NLPRetrievalAdapter{ kbDAO: fakeKnowledgebaseLookup{ diff --git a/internal/agent/tool/retrieval_service.go b/internal/agent/tool/retrieval_service.go index 005591a3384..a4ccfdbf559 100644 --- a/internal/agent/tool/retrieval_service.go +++ b/internal/agent/tool/retrieval_service.go @@ -44,6 +44,10 @@ type RetrievalChunk struct { Score float64 TermSimilarity float64 VectorSimilarity float64 + // MomID is the parent chunk id when this chunk is a child fragment; empty + // for top-level chunks. Threaded through so the harness can run + // retrieval_by_children (child fragments are promoted to their parent chunk). + MomID string } // RetrievalRequest is the input to RetrievalService.Search. @@ -60,8 +64,13 @@ type RetrievalRequest struct { RerankID string CrossLanguages []string TOCEnhance bool - MetaDataFilter map[string]any - RetrievalFrom string + // RankFeature mirrors Python RAGTools.retrieve's rank_feature argument: + // question-type tags (from label_question) the retriever uses to boost + // matching chunks. The Go engine consumes it as a tag → weight map, so it + // is *map[string]float64. Nil means no tag boost (fall back to enhancer). + RankFeature *map[string]float64 + MetaDataFilter map[string]any + RetrievalFrom string // DocScope restricts retrieval to a set of document ids (the doc_id list // routed by the dataset_navigation_by_tree tool). Empty = no doc filter. DocScope []string @@ -75,6 +84,11 @@ type RetrievalRequest struct { // from sys.user_id). Empty = no user filter. Only meaningful for // retrieval_from=memory. UserID string + // ExcludeCompiled excludes compiled-product rows from plain retrieval + // (Python hybrid_search passes must_not={"exists": "compile_kwd"}, + // search.py:171). Compiled products have their own expansion step, so the + // base retrieval should surface ordinary document chunks only. + ExcludeCompiled bool } // RetrievalService is the knowledge-base search interface used by the tool. diff --git a/internal/agent/workflowx/parallel_test.go b/internal/agent/workflowx/parallel_test.go index 03fec18eb28..38596103e84 100644 --- a/internal/agent/workflowx/parallel_test.go +++ b/internal/agent/workflowx/parallel_test.go @@ -248,7 +248,7 @@ func TestParallel_Concurrent_UsesSemaphoreFanout(t *testing.T) { } // TestParallel_SingleItemError_Wrapped asserts the "item %d: %w" -// wrapping contract. The lambda must return the wrapped error, +// wrapping The lambda must return the wrapped error, // other items must be drained. func TestParallel_SingleItemError_Wrapped(t *testing.T) { ctx := t.Context() diff --git a/internal/common/logger.go b/internal/common/logger.go index 74b322919d5..f52e2c0f9e9 100644 --- a/internal/common/logger.go +++ b/internal/common/logger.go @@ -18,9 +18,11 @@ package common import ( "fmt" + "log" "os" "path/filepath" "strings" + "sync" "time" "github.com/pkg/errors" @@ -35,6 +37,9 @@ var ( Logger *zap.Logger Sugar *zap.SugaredLogger atomicLevel zap.AtomicLevel + + stdLogOnce sync.Once + stdLogger *log.Logger ) // FileOutput describes the rotated log file destination. @@ -219,6 +224,21 @@ func Warn(msg string, fields ...zap.Field) { Logger.Warn(msg, fields...) } +// StdLogger returns a *log.Logger that routes writes through the global zap +// logger, so call sites that keep a *log.Logger facade still land in the +// project's structured logs. When the project logger has not been initialized +// yet (e.g. before InitLogger runs or in standalone tests) it falls back to the +// standard-library default. The returned logger writes at Info level. +func StdLogger() *log.Logger { + if Logger == nil { + return log.Default() + } + stdLogOnce.Do(func() { + stdLogger = zap.NewStdLog(Logger) + }) + return stdLogger +} + // IsDebugEnabled returns true if debug logging is enabled. func IsDebugEnabled() bool { return atomicLevel.Enabled(zapcore.DebugLevel) diff --git a/internal/dao/tenant_model.go b/internal/dao/tenant_model.go index 6e8c17ac670..2a237cf1950 100644 --- a/internal/dao/tenant_model.go +++ b/internal/dao/tenant_model.go @@ -85,6 +85,20 @@ func (dao *TenantModelDAO) GetByID(ctx context.Context, db *gorm.DB, id string) return &model, nil } +// GetByIDs get tenant models by primary keys (id), mirroring Python +// TenantModelService.get_by_ids. Unknown ids are simply absent from the result. +func (dao *TenantModelDAO) GetByIDs(ctx context.Context, db *gorm.DB, ids []string) ([]*entity.TenantModel, error) { + if len(ids) == 0 { + return nil, nil + } + var models []*entity.TenantModel + err := db.WithContext(ctx).Where("id IN ?", ids).Find(&models).Error + if err != nil { + return nil, err + } + return models, nil +} + func (dao *TenantModelDAO) GetModelByProviderIDAndInstanceIDAndModelName(ctx context.Context, db *gorm.DB, providerID, instanceID, modelName string) (*entity.TenantModel, error) { var model entity.TenantModel err := db.WithContext(ctx).Where("provider_id = ? AND instance_id = ? AND model_name = ?", providerID, instanceID, modelName).First(&model).Error diff --git a/internal/entity/models/aliyun.go b/internal/entity/models/aliyun.go index ffffb019f19..471ba55468a 100644 --- a/internal/entity/models/aliyun.go +++ b/internal/entity/models/aliyun.go @@ -23,7 +23,10 @@ import ( "fmt" "io" "net/http" + "net/url" + "os" "strings" + "sync" "ragflow/internal/common" ) @@ -182,25 +185,6 @@ func aliyunToolChoice(modelName string, messages []Message, configured *string) return choice } -type aliyunEmbeddingResponse struct { - Data []aliyunEmbeddingData `json:"data"` - Model string `json:"model"` - Object string `json:"object"` - Usage aliyunUsage `json:"usage"` - ID string `json:"id"` -} - -type aliyunEmbeddingData struct { - Embedding []float64 `json:"embedding"` - Index int `json:"index"` - Object string `json:"object"` -} - -type aliyunUsage struct { - PromptTokens int `json:"prompt_tokens"` - TotalTokens int `json:"total_tokens"` -} - // Embed embeds a list of texts into embeddings func (a *AliyunModel) Embed(ctx context.Context, modelName *string, request EmbedRequest, apiConfig *APIConfig, embeddingConfig *EmbeddingConfig, modelUsage *common.ModelUsage) ([]EmbeddingData, error) { if err := a.baseModel.APIConfigCheck(apiConfig); err != nil { @@ -221,61 +205,219 @@ func (a *AliyunModel) Embed(ctx context.Context, modelName *string, request Embe } baseURL := resolvedBaseURL - url := fmt.Sprintf("%s/%s", strings.TrimSuffix(baseURL, "/"), a.baseModel.URLSuffix.Embedding) - - reqBody := map[string]interface{}{ - "model": *modelName, - "input": request.Texts, + // Tongyi-Qianwen text embeddings are asymmetric (query vs document), and only + // the native API can express that distinction (text_type). Every call therefore + // goes to the native API, exactly as Python's QWenEmbed does + // (embedding_model.py): a recognized DashScope host is mapped onto its /api/v1 + // root, and an unrecognized base URL is IGNORED — the dashscope SDK keeps its own + // endpoint (DASHSCOPE_HTTP_BASE_URL, else + // https://dashscope.aliyuncs.com/api/) and QWenEmbed + // only warns once at construction time (:121-127, :134-138). There is + // deliberately no OpenAI-compatible fallback: that endpoint cannot send + // text_type, so it would encode query-side embeddings (dense seed / retrieval + // query) in document space. Use the OpenAI-API-Compatible / vLLM factory for a + // private gateway — Python requires the same choice. + if nativeRoot := aliyunNativeEmbeddingRoot(baseURL); nativeRoot != "" { + return a.embedNative(ctx, nativeRoot, *modelName, request, apiConfig, modelUsage) + } + + // Unrecognized host: warn once per host, then use the SDK's default native root. + aliyunWarnIgnoredBaseURL(baseURL) + return a.embedNative(ctx, aliyunSDKDefaultNativeRoot(), *modelName, request, apiConfig, modelUsage) +} + +// aliyunIgnoredHostWarned dedups the unrecognized-host warning to once per host. +var aliyunIgnoredHostWarned sync.Map + +// aliyunWarnSink writes the warning line. Tests replace it to capture the warning +// without going through the logger. +var aliyunWarnSink = func(format string, args ...any) { common.StdLogger().Printf(format, args...) } + +// aliyunWarnIgnoredBaseURL reports, once per host and never per call, that the +// configured base URL is not a DashScope host and is therefore ignored in favour +// of the SDK default endpoint — Python QWenEmbed warns once at construction time +// instead (embedding_model.py:121-127). +func aliyunWarnIgnoredBaseURL(baseURL string) { + host := aliyunBaseURLHost(baseURL) + if host == "" { + return } - - jsonData, err := json.Marshal(reqBody) - if err != nil { - return nil, fmt.Errorf("failed to marshal request: %w", err) + if _, seen := aliyunIgnoredHostWarned.LoadOrStore(host, struct{}{}); seen { + return } - - ctx, cancel := context.WithTimeout(ctx, nonStreamCallTimeout) - defer cancel() - - req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonData)) + aliyunWarnSink( + "[Qwen embedding] base URL host %q is not a DashScope host, so the configured base URL is ignored: "+ + "using the native text-embedding API at %s instead (Python QWenEmbed behaviour). Point the base URL at "+ + "dashscope.aliyuncs.com / dashscope-intl.aliyuncs.com, or end it with /api/v1 to address a "+ + "native-compatible endpoint directly.", host, aliyunSDKDefaultNativeRoot()) +} + +// aliyunSDKDefaultNativeRoot mirrors the dashscope SDK's default native API root +// (dashscope/common/env.py:14-23): DASHSCOPE_HTTP_BASE_URL when set, else +// https://dashscope.aliyuncs.com/api/. It is where +// Python's QWenEmbed ends up when the configured base URL is not a DashScope host, +// and the only override that still carries text_type. +func aliyunSDKDefaultNativeRoot() string { + if root := strings.TrimSpace(os.Getenv("DASHSCOPE_HTTP_BASE_URL")); root != "" { + return strings.TrimRight(root, "/") + } + version := strings.TrimSpace(os.Getenv("DASHSCOPE_API_VERSION")) + if version == "" { + version = "v1" + } + return fmt.Sprintf("https://dashscope.aliyuncs.com/api/%s", version) +} + +// aliyunBaseURLHost returns the lowercase host of a configured base URL for log +// lines. Only the host is used, so credentials, path and query string cannot leak +// (Python's _dashscope_base_url_for_log is strict the same way, +// embedding_model.py:73-75). +func aliyunBaseURLHost(baseURL string) string { + raw := strings.TrimSpace(baseURL) + if raw == "" { + return "" + } + if parsed, err := url.Parse(raw); err == nil && parsed.Hostname() != "" { + return strings.ToLower(parsed.Hostname()) + } + // Schemeless config (e.g. "gateway.internal/v1"): the first path segment is the + // host. + return strings.ToLower(strings.SplitN(strings.TrimPrefix(raw, "//"), "/", 2)[0]) +} + +// aliyunNativeEmbeddingPath is the DashScope native text-embedding endpoint, +// appended to the native API root ("https:///api/v1"). +const aliyunNativeEmbeddingPath = "services/embeddings/text-embedding/text-embedding" + +// aliyunNativeEmbedBatchSize mirrors Python QWenEmbed.encode's batch_size = 4. +const aliyunNativeEmbedBatchSize = 4 + +// aliyunNativeEmbeddingRoot maps a configured DashScope base URL onto the native +// API root, mirroring Python embedding_model._dashscope_native_http_api_url +// (rag/llm/embedding_model.py:80-128): an already-native base is kept as-is, +// known DashScope hosts (CN and international) are mapped to their /api/v1 root, +// and anything else returns "" so the caller falls back to the dashscope SDK's +// default native root (aliyunSDKDefaultNativeRoot), as Python QWenEmbed does. +// Matching on the parsed hostname (never a substring of the full URL) prevents a +// crafted query string from selecting the native API. +func aliyunNativeEmbeddingRoot(baseURL string) string { + u := strings.TrimRight(strings.TrimSpace(baseURL), "/") + if u == "" { + return "" + } + if strings.HasSuffix(u, "/api/v1") { + return u + } + parsed, err := url.Parse(u) if err != nil { - return nil, fmt.Errorf("failed to create request: %w", err) + return "" } + host := strings.ToLower(parsed.Hostname()) + switch { + case host == "dashscope-intl.aliyuncs.com" || strings.HasSuffix(host, ".dashscope-intl.aliyuncs.com"): + return "https://dashscope-intl.aliyuncs.com/api/v1" + case host == "dashscope.aliyuncs.com" || strings.HasSuffix(host, ".dashscope.aliyuncs.com"): + return "https://dashscope.aliyuncs.com/api/v1" + default: + return "" + } +} - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) +type aliyunNativeEmbedInput struct { + Texts []string `json:"texts"` +} - resp, err := a.baseModel.httpClient.Do(req) - if err != nil { - return nil, fmt.Errorf("failed to send request: %w", err) - } - defer resp.Body.Close() +type aliyunNativeEmbedRequest struct { + Model string `json:"model"` + Input aliyunNativeEmbedInput `json:"input"` + Parameters map[string]interface{} `json:"parameters,omitempty"` +} - body, err := io.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("failed to read response: %w", err) - } +type aliyunNativeEmbedResponse struct { + Code string `json:"code"` + Message string `json:"message"` + // RequestID is the DashScope request id every native response carries (the same + // id Python surfaces in its ModelException messages). + RequestID string `json:"request_id"` + Output struct { + Embeddings []struct { + TextIndex int `json:"text_index"` + Embedding []float64 `json:"embedding"` + } `json:"embeddings"` + } `json:"output"` + Usage struct { + TotalTokens int `json:"total_tokens"` + } `json:"usage"` +} - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("aliyun embeddings API error: %s, body: %s", resp.Status, string(body)) - } +// embedNative calls the DashScope native text-embedding API, the only transport +// that carries text_type ("document" for encode, "query" for encode_queries — +// Python QWenEmbed). Inputs are sent in batches of 4 like Python; the response's +// text_index is relative to the batch, so it is offset back to the caller's +// slice before being returned. +func (a *AliyunModel) embedNative(ctx context.Context, root, modelName string, request EmbedRequest, apiConfig *APIConfig, modelUsage *common.ModelUsage) ([]EmbeddingData, error) { + textType := "document" + if request.Query { + textType = "query" + } + endpoint := fmt.Sprintf("%s/%s", strings.TrimRight(root, "/"), aliyunNativeEmbeddingPath) + + embeddings := make([]EmbeddingData, 0, len(request.Texts)) + for start := 0; start < len(request.Texts); start += aliyunNativeEmbedBatchSize { + end := min(start+aliyunNativeEmbedBatchSize, len(request.Texts)) + batch := request.Texts[start:end] + + jsonData, err := json.Marshal(aliyunNativeEmbedRequest{ + Model: modelName, + Input: aliyunNativeEmbedInput{Texts: batch}, + Parameters: map[string]interface{}{"text_type": textType}, + }) + if err != nil { + return nil, fmt.Errorf("failed to marshal request: %w", err) + } - var parsed aliyunEmbeddingResponse - if err = json.Unmarshal(body, &parsed); err != nil { - return nil, fmt.Errorf("failed to parse response: %w", err) - } + callCtx, cancel := context.WithTimeout(ctx, nonStreamCallTimeout) + req, err := http.NewRequestWithContext(callCtx, http.MethodPost, endpoint, bytes.NewBuffer(jsonData)) + if err != nil { + cancel() + return nil, fmt.Errorf("failed to create request: %w", err) + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", *apiConfig.ApiKey)) - var embeddings []EmbeddingData - for _, dataElem := range parsed.Data { - var embeddingData EmbeddingData - embeddingData.Embedding = dataElem.Embedding - embeddingData.Index = dataElem.Index - embeddings = append(embeddings, embeddingData) - } - recordResponseUsage(modelUsage, parsed.ID, &TokenUsage{ - PromptTokens: parsed.Usage.PromptTokens, - TotalTokens: parsed.Usage.TotalTokens, - }, "embedding") + resp, err := a.baseModel.httpClient.Do(req) + if err != nil { + cancel() + return nil, fmt.Errorf("failed to send request: %w", err) + } + body, readErr := io.ReadAll(resp.Body) + resp.Body.Close() + cancel() + if readErr != nil { + return nil, fmt.Errorf("failed to read response: %w", readErr) + } + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("aliyun native embeddings API error: %s, body: %s", resp.Status, string(body)) + } + var parsed aliyunNativeEmbedResponse + if err = json.Unmarshal(body, &parsed); err != nil { + return nil, fmt.Errorf("failed to parse response: %w", err) + } + if parsed.Code != "" { + return nil, fmt.Errorf("aliyun native embeddings API error: %s: %s", parsed.Code, parsed.Message) + } + for _, item := range parsed.Output.Embeddings { + if item.TextIndex < 0 || item.TextIndex >= len(batch) { + return nil, fmt.Errorf("aliyun native embeddings response index %d out of range for batch of %d", item.TextIndex, len(batch)) + } + embeddings = append(embeddings, EmbeddingData{ + Embedding: item.Embedding, + Index: start + item.TextIndex, + }) + } + recordResponseUsage(modelUsage, parsed.RequestID, &TokenUsage{TotalTokens: parsed.Usage.TotalTokens}, "embedding") + } return embeddings, nil } diff --git a/internal/entity/models/aliyun_test.go b/internal/entity/models/aliyun_test.go index 3959425bebd..6a962220cdb 100644 --- a/internal/entity/models/aliyun_test.go +++ b/internal/entity/models/aliyun_test.go @@ -571,3 +571,170 @@ func TestAliyunAudioSpeechWithSenderSendsSingleChunk(t *testing.T) { t.Fatalf("chunks = %v, want [fake-wav-bytes]", chunks) } } + +// TestAliyunNativeEmbeddingRootMapping pins Python +// _dashscope_native_http_api_url (embedding_model.py:80-128): an already-native +// base is kept, known DashScope hosts map to their /api/v1 root, and anything +// else (private gateways) leaves the compatible endpoint in place. +func TestAliyunNativeEmbeddingRootMapping(t *testing.T) { + cases := []struct{ in, want string }{ + {"", ""}, + {"https://dashscope.aliyuncs.com/compatible-mode/v1", "https://dashscope.aliyuncs.com/api/v1"}, + {"https://dashscope-intl.aliyuncs.com/compatible-mode/v1/", "https://dashscope-intl.aliyuncs.com/api/v1"}, + {"https://dashscope.aliyuncs.com/api/v1", "https://dashscope.aliyuncs.com/api/v1"}, + {"https://private-gateway.example.com/v1", ""}, + // Hostname matching, not substring: a crafted query string must not + // select the native API. + {"https://attacker.example/?u=dashscope.aliyuncs.com", ""}, + } + for _, c := range cases { + if got := aliyunNativeEmbeddingRoot(c.in); got != c.want { + t.Errorf("aliyunNativeEmbeddingRoot(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +// TestAliyunEmbedIgnoresNonDashScopeHost pins the Python QWenEmbed contract for a +// base URL that is not a DashScope host: the configured host is IGNORED and the +// call goes to the dashscope SDK's default native root — still carrying +// text_type, so the query/document distinction survives — with a single warning +// naming the ignored host (embedding_model.py:121-127, :134-138, :448-450). +func TestAliyunEmbedIgnoresNonDashScopeHost(t *testing.T) { + withSSRFBypass(t) + + var paths []string + var bodies []map[string]interface{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + paths = append(paths, r.URL.Path) + var body map[string]interface{} + _ = json.NewDecoder(r.Body).Decode(&body) + bodies = append(bodies, body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"output":{"embeddings":[{"text_index":0,"embedding":[0.5]}]},"usage":{"total_tokens":1}}`)) + })) + defer srv.Close() + // DASHSCOPE_HTTP_BASE_URL is the SDK endpoint Python leaves in place when the + // configured base URL is unrecognized (dashscope/common/env.py:20-23). + t.Setenv("DASHSCOPE_HTTP_BASE_URL", srv.URL) + + var warnings []string + prev := aliyunWarnSink + t.Cleanup(func() { aliyunWarnSink = prev }) + aliyunWarnSink = func(format string, args ...any) { warnings = append(warnings, fmt.Sprintf(format, args...)) } + + apiKey := "test-key" + model := "text-embedding-v4" + // A private gateway that is not a DashScope host: it must be ignored, not used. + m := NewAliyunModel(map[string]string{"default": "https://ignored-gateway.internal/v1"}, + URLSuffix{Embedding: "embeddings", Chat: "chat/completions"}) + + if _, err := m.Embed(t.Context(), &model, EmbedRequest{Texts: []string{"d"}}, &APIConfig{ApiKey: &apiKey}, nil, nil); err != nil { + t.Fatalf("Embed(document): %v", err) + } + if _, err := m.Embed(t.Context(), &model, EmbedRequest{Texts: []string{"q"}, Query: true}, &APIConfig{ApiKey: &apiKey}, nil, nil); err != nil { + t.Fatalf("Embed(query): %v", err) + } + if _, err := m.Embed(t.Context(), &model, EmbedRequest{Texts: []string{"q2"}, Query: true}, &APIConfig{ApiKey: &apiKey}, nil, nil); err != nil { + t.Fatalf("Embed(query 2): %v", err) + } + + // Every call lands on the native text-embedding path of the SDK endpoint. + if len(paths) != 3 { + t.Fatalf("requests = %d, want 3 (the ignored host must not be contacted)", len(paths)) + } + for i, p := range paths { + if want := "/" + aliyunNativeEmbeddingPath; p != want { + t.Errorf("path[%d] = %q, want %q", i, p, want) + } + } + // text_type survives the fallback: document for the plain call, query after. + for i, want := range []string{"document", "query", "query"} { + params, _ := bodies[i]["parameters"].(map[string]interface{}) + if params["text_type"] != want { + t.Errorf("body[%d] text_type = %v, want %q", i, bodies[i]["parameters"], want) + } + } + // One warning, naming the host that was ignored. + if len(warnings) != 1 { + t.Fatalf("warnings = %v, want exactly one (once per host, not per call)", warnings) + } + if !strings.Contains(warnings[0], "ignored-gateway.internal") { + t.Errorf("warning %q does not name the ignored host", warnings[0]) + } +} + +// TestAliyunBaseURLHostIsHostOnly pins that the warning can only ever log a host: +// credentials, path and query string from a configured base URL stay out of the +// log line. +func TestAliyunBaseURLHostIsHostOnly(t *testing.T) { + for _, c := range []struct{ in, want string }{ + {"https://user:secret@gateway.internal/v1?key=abc", "gateway.internal"}, + {"https://dashscope.aliyuncs.com/compatible-mode/v1", "dashscope.aliyuncs.com"}, + {"gateway.internal/v1", "gateway.internal"}, + {"", ""}, + } { + if got := aliyunBaseURLHost(c.in); got != c.want { + t.Errorf("aliyunBaseURLHost(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +// embedding call used for Tongyi-Qianwen: text_type follows EmbedRequest.Query, +// inputs are sent in batches of 4 (Python QWenEmbed.encode), and each response's +// batch-relative text_index is offset back into the caller's slice. +func TestAliyunEmbedNativeSendsTextTypeAndBatches(t *testing.T) { + withSSRFBypass(t) + var paths []string + var bodies []map[string]interface{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + paths = append(paths, r.URL.Path) + var body map[string]interface{} + _ = json.NewDecoder(r.Body).Decode(&body) + bodies = append(bodies, body) + input, _ := body["input"].(map[string]interface{}) + texts, _ := input["texts"].([]interface{}) + parts := make([]string, 0, len(texts)) + for i := range texts { + parts = append(parts, fmt.Sprintf(`{"text_index":%d,"embedding":[%d]}`, i, i)) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"output":{"embeddings":[` + strings.Join(parts, ",") + `]},"usage":{"total_tokens":1}}`)) + })) + defer srv.Close() + + m := NewAliyunModel(map[string]string{"default": srv.URL}, URLSuffix{Embedding: "embeddings"}) + apiKey := "test-key" + got, err := m.embedNative(t.Context(), srv.URL, "text-embedding-v4", + EmbedRequest{Texts: []string{"a", "b", "c", "d", "e"}}, &APIConfig{ApiKey: &apiKey}, nil) + if err != nil { + t.Fatalf("embedNative: %v", err) + } + if len(paths) != 2 { + t.Fatalf("requests = %d, want 2 (batch of 4 + 1)", len(paths)) + } + if want := "/" + aliyunNativeEmbeddingPath; paths[0] != want { + t.Errorf("path = %q, want %q", paths[0], want) + } + if params, ok := bodies[0]["parameters"].(map[string]interface{}); !ok || params["text_type"] != "document" { + t.Errorf("document text_type = %v, want document", bodies[0]["parameters"]) + } + byIndex := map[int]EmbeddingData{} + for _, e := range got { + byIndex[e.Index] = e + } + if len(byIndex) != 5 { + t.Fatalf("embeddings cover indexes %v, want 0..4", byIndex) + } + if _, ok := byIndex[4]; !ok { + t.Errorf("second batch's text_index was not offset to the global index 4: %v", byIndex) + } + + // The query path flips text_type. + if _, err := m.embedNative(t.Context(), srv.URL, "text-embedding-v4", + EmbedRequest{Texts: []string{"q"}, Query: true}, &APIConfig{ApiKey: &apiKey}, nil); err != nil { + t.Fatalf("embedNative(query): %v", err) + } + if params, ok := bodies[len(bodies)-1]["parameters"].(map[string]interface{}); !ok || params["text_type"] != "query" { + t.Errorf("query text_type = %v, want query", bodies[len(bodies)-1]["parameters"]) + } +} diff --git a/internal/entity/models/bedrock.go b/internal/entity/models/bedrock.go index 0f4dcf99cf1..382bd07a45f 100644 --- a/internal/entity/models/bedrock.go +++ b/internal/entity/models/bedrock.go @@ -1033,7 +1033,7 @@ func (b *BedrockModel) Embed(ctx context.Context, modelName *string, request Emb return b.embedTitan(ctx, modelID, request.Texts, region, key, embeddingConfig, modelUsage) } if strings.HasPrefix(modelID, "cohere.embed-") { - return b.embedCohere(ctx, modelID, request.Texts, region, key, embeddingConfig, modelUsage) + return b.embedCohere(ctx, modelID, request.Texts, request.Query, region, key, embeddingConfig, modelUsage) } return nil, fmt.Errorf("bedrock: unsupported embedding model %q", modelID) } @@ -1101,10 +1101,17 @@ func (b *BedrockModel) embedTitan(ctx context.Context, modelID string, texts []s return embeddings, nil } -func (b *BedrockModel) embedCohere(ctx context.Context, modelID string, texts []string, region string, key *bedrockKey, embeddingConfig *EmbeddingConfig, modelUsage *common.ModelUsage) ([]EmbeddingData, error) { +func (b *BedrockModel) embedCohere(ctx context.Context, modelID string, texts []string, query bool, region string, key *bedrockKey, embeddingConfig *EmbeddingConfig, modelUsage *common.ModelUsage) ([]EmbeddingData, error) { + // Python BedrockEmbed.encode uses input_type="search_document" and + // encode_queries uses "search_query" for the Cohere models; Titan has no + // query/document distinction (see embedTitan). + inputType := "search_document" + if query { + inputType = "search_query" + } req := bedrockCohereEmbeddingRequest{ Texts: texts, - InputType: "search_document", + InputType: inputType, } if embeddingConfig != nil && embeddingConfig.Dimension > 0 && strings.HasPrefix(modelID, "cohere.embed-v4") { req.OutputDimension = &embeddingConfig.Dimension diff --git a/internal/entity/models/bedrock_test.go b/internal/entity/models/bedrock_test.go index fd26f72a07b..1202db8a636 100644 --- a/internal/entity/models/bedrock_test.go +++ b/internal/entity/models/bedrock_test.go @@ -886,6 +886,37 @@ func TestBedrockCohereEmbedHappyPath(t *testing.T) { } } +// TestBedrockCohereEmbedQueryUsesSearchQuery pins Python BedrockEmbed: the +// Cohere path sends input_type="search_query" for encode_queries, while encode +// sends "search_document" (see TestBedrockCohereEmbedHappyPath). +func TestBedrockCohereEmbedQueryUsesSearchQuery(t *testing.T) { + withSSRFBypass(t) + ctx := t.Context() + srv := newBedrockServer(t, http.MethodPost, + "/model/cohere.embed-english-v3/invoke", + func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + var body bedrockCohereEmbeddingRequest + if err := json.Unmarshal(raw, &body); err != nil { + t.Errorf("unmarshal body: %v", err) + return + } + if body.InputType != "search_query" { + t.Errorf("input_type=%q want search_query", body.InputType) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"embeddings":[[1,2]]}`)) + }) + defer srv.Close() + + m := newBedrockForTest(srv.URL) + key := validBedrockKey() + model := "cohere.embed-english-v3" + if _, err := m.Embed(ctx, &model, EmbedRequest{Texts: []string{"q"}, Query: true}, &APIConfig{ApiKey: &key}, nil, nil); err != nil { + t.Fatalf("Embed: %v", err) + } +} + func TestBedrockCohereV4ForwardsDimensionAndParsesTypedResponse(t *testing.T) { withSSRFBypass(t) ctx := t.Context() diff --git a/internal/entity/models/chat_tools.go b/internal/entity/models/chat_tools.go index 933cf3f8067..4149787827c 100644 --- a/internal/entity/models/chat_tools.go +++ b/internal/entity/models/chat_tools.go @@ -154,7 +154,18 @@ func runToolLoop(ctx context.Context, cm *ChatModel, history []Message, toolsLis return answer, totalTokens, nil } - history = appendToolResults(history, resp.ToolCalls, cm.ToolConfig.ToolCallSession) + // Execute the round's tool calls and fold their results into history. + // If one of them is a terminal tool and succeeded, its result is already + // the final answer — return it directly instead of re-invoking the model + // (Python chat_model.py:619-627). + var hit bool + var toolAnswer string + history, toolAnswer, hit = appendToolResults(history, resp.ToolCalls, cm.ToolConfig.ToolCallSession, terminalSet(cm)) + if hit { + addRoundUsage(resp) + return toolAnswer, totalTokens, nil + } + // history now carries this round's tool results; continue to the next round. } // Exceeded max rounds @@ -178,6 +189,14 @@ func runToolLoop(ctx context.Context, cm *ChatModel, history []Message, toolsLis return *resp.Answer, totalTokens, nil } +// terminalSet returns the configured terminal-tool name set, or nil when none. +func terminalSet(cm *ChatModel) map[string]struct{} { + if cm.ToolConfig == nil { + return nil + } + return cm.ToolConfig.TerminalTools +} + // ChatStreamlyWithTools runs the streaming tool-calling loop. func (cm *ChatModel) ChatStreamlyWithTools(ctx context.Context, system string, history []Message, chatCfg *ChatConfig, sender func(*string, *string) error) (int, error) { tc := cm.ToolConfig @@ -338,7 +357,19 @@ func runStreamToolLoop(ctx context.Context, cm *ChatModel, history []Message, to return totalTokens, fmt.Errorf("round %d: no content and no tool_calls", round) } - history = appendToolResults(history, toolCalls, cm.ToolConfig.ToolCallSession) + // A terminal tool's successful result is already the final answer: + // stream it to the caller and stop instead of asking the model again + // (Python chat_model.py:2574-2582). sendTerminal streams the result. + var termAnswer string + var termHit bool + history, termAnswer, termHit = appendToolResults(history, toolCalls, cm.ToolConfig.ToolCallSession, terminalSet(cm)) + if termHit { + if err := sendTerminal(sender, &termAnswer); err != nil { + return totalTokens, err + } + return totalTokens, nil + } + // history now carries this round's tool results; continue to the next round. } // Exceeded max rounds @@ -363,7 +394,13 @@ func runStreamToolLoop(ctx context.Context, cm *ChatModel, history []Message, to // appendToolResults executes tool calls concurrently, appends the assistant // message with tool_calls and individual tool result messages to history. -func appendToolResults(history []Message, toolCalls []map[string]interface{}, session ToolCallSession) []Message { +// +// When terminal is non-empty, a successful call to one of those tools +// short-circuits: the loop returns (history, that result, true) so the caller +// treats it as the final answer instead of re-invoking the model (mirrors +// Python chat_model.py:619-627 / :2574-2582). When terminal is empty or no +// terminal tool fired, it returns (history, "", false). +func appendToolResults(history []Message, toolCalls []map[string]interface{}, session ToolCallSession, terminal map[string]struct{}) ([]Message, string, bool) { if session == nil { history = append(history, Message{ Role: "assistant", @@ -378,13 +415,15 @@ func appendToolResults(history []Message, toolCalls []map[string]interface{}, se ToolCallID: tcID, }) } - return history + return history, "", false } var mu sync.Mutex var wg sync.WaitGroup type toolResult struct { index int tcID string + name string + err error content string } results := make([]toolResult, len(toolCalls)) @@ -405,6 +444,7 @@ func appendToolResults(history []Message, toolCalls []map[string]interface{}, se name, _ := fn["name"].(string) argsStr, _ := fn["arguments"].(string) result.tcID, _ = tcMap["id"].(string) + result.name = name var args map[string]interface{} if err := json.Unmarshal([]byte(argsStr), &args); err != nil { @@ -413,6 +453,7 @@ func appendToolResults(history []Message, toolCalls []map[string]interface{}, se res, err := session.ToolCall(name, args) if err != nil { + result.err = err result.content = fmt.Sprintf("Error: %s", err.Error()) } else { result.content = res @@ -430,17 +471,46 @@ func appendToolResults(history []Message, toolCalls []map[string]interface{}, se ToolCalls: toolCalls, }) + // A successful terminal tool is the final answer; remember its result but + // still append every tool message so history stays well-formed if the + // caller ignores the short-circuit (defensive). + var terminalAnswer string + var terminalHit bool for _, r := range results { history = append(history, Message{ Role: "tool", Content: r.content, ToolCallID: r.tcID, }) + if !terminalHit && r.err == nil && r.name != "" { + if _, ok := terminal[r.name]; ok { + terminalAnswer = r.content + terminalHit = true + } + } } - return history + // A terminal tool short-circuits on success regardless of what it returned. + // Tools that stream their own answer through the caller's sender return an + // empty string to say "nothing more to emit", and sendTerminal's empty guard + // then keeps the loop from re-streaming it (mirrors Python, where the + // terminal result is ignored once the inner answer_sink has streamed). + if terminalHit { + return history, terminalAnswer, true + } + return history, "", false } func boolPtr(b bool) *bool { return &b } + +// sendTerminal streams a terminal tool's already-final answer to the sender as +// plain text deltas (no reasoning), mirroring how Python yields the terminal +// result and stops. +func sendTerminal(sender func(*string, *string) error, answer *string) error { + if answer == nil || *answer == "" { + return nil + } + return sender(answer, nil) +} diff --git a/internal/entity/models/chat_tools_test.go b/internal/entity/models/chat_tools_test.go new file mode 100644 index 00000000000..4cb98e8ffbd --- /dev/null +++ b/internal/entity/models/chat_tools_test.go @@ -0,0 +1,172 @@ +// +// 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. +// + +package models + +import "testing" + +// stubSession returns a canned result per tool name. +type stubSession struct { + results map[string]string +} + +func (s *stubSession) ToolCall(name string, _ map[string]interface{}) (string, error) { + if r, ok := s.results[name]; ok { + return r, nil + } + return "ok:" + name, nil +} + +func toolCallMsg(id, name, args string) map[string]interface{} { + return map[string]interface{}{ + "id": id, + "function": map[string]interface{}{ + "name": name, + "arguments": args, + }, + } +} + +// A successful terminal tool short-circuits and surfaces its result. +func TestAppendToolResultsTerminalHit(t *testing.T) { + history := []Message{{Role: "user", Content: "summarise onboarding"}} + sess := &stubSession{results: map[string]string{"summarize_document": "[SUMMARY]"}} + term := map[string]struct{}{"rag": {}, "summarize_document": {}} + + hist, answer, hit := appendToolResults(history, []map[string]interface{}{ + toolCallMsg("call-1", "summarize_document", `{"doc_id":"abc"}`), + }, sess, term) + + if !hit { + t.Fatal("terminal tool success must short-circuit") + } + if answer != "[SUMMARY]" { + t.Fatalf("answer = %q, want the terminal result", answer) + } + // History must still carry the assistant tool_calls + tool result so it is + // well-formed even though the caller ignores it on short-circuit. + if len(hist) != 3 { + t.Fatalf("history length = %d, want 3 (user + assistant + tool)", len(hist)) + } +} + +// A failing terminal tool must NOT short-circuit. +func TestAppendToolResultsTerminalErrorDoesNotShortCircuit(t *testing.T) { + history := []Message{{Role: "user", Content: "q"}} + term := map[string]struct{}{"rag": {}} + + _, answer, hit := appendToolResults(history, []map[string]interface{}{ + toolCallMsg("call-1", "nonterminal", `{}`), + }, &stubSession{}, term) + if hit || answer != "" { + t.Fatal("non-terminal call must not short-circuit") + } +} + +// With no terminal set configured, behaviour is unchanged: no short-circuit. +func TestAppendToolResultsNoTerminalConfigured(t *testing.T) { + history := []Message{{Role: "user", Content: "q"}} + hist, answer, hit := appendToolResults(history, []map[string]interface{}{ + toolCallMsg("call-1", "rag", `{}`), + }, &stubSession{}, nil) + if hit || answer != "" { + t.Fatal("no terminal set must never short-circuit") + } + if len(hist) != 3 { + t.Fatalf("history length = %d, want 3 (user + assistant + tool)", len(hist)) + } +} + +// A non-terminal tool among terminal-configured set must not short-circuit. +func TestAppendToolResultsNonTerminalIgnoresSet(t *testing.T) { + history := []Message{{Role: "user", Content: "q"}} + term := map[string]struct{}{"rag": {}} + _, answer, hit := appendToolResults(history, []map[string]interface{}{ + toolCallMsg("call-1", "retrieve", `{}`), + }, &stubSession{}, term) + if hit || answer != "" { + t.Fatal("non-terminal tool must not short-circuit even with a terminal set present") + } +} + +// SetTerminalTools registers the names on the bound ToolConfig. +func TestSetTerminalToolsRegistersNames(t *testing.T) { + cm := NewChatModel(&DummyModel{}, strPtr("m"), nil) + cm.BindTools(&stubSession{}, []map[string]interface{}{}) + cm.SetTerminalTools("rag", "summarize_document") + + term := terminalSet(cm) + if _, ok := term["rag"]; !ok { + t.Fatal("rag must be terminal") + } + if _, ok := term["summarize_document"]; !ok { + t.Fatal("summarize_document must be terminal") + } + if _, ok := term["retrieve"]; ok { + t.Fatal("retrieve must not be terminal") + } +} + +// SetTerminalTools on a model with no bound tools is a no-op. +func TestSetTerminalToolsWithoutToolsIsNoop(t *testing.T) { + cm := NewChatModel(&DummyModel{}, strPtr("m"), nil) + cm.SetTerminalTools("rag") // must not panic + if terminalSet(cm) != nil { + t.Fatal("no ToolConfig means no terminal set") + } +} + +// A terminal tool that already streamed its answer returns "" to say "nothing +// more to emit". It must still short-circuit, so the loop stops instead of +// asking the model again. +func TestAppendToolResultsTerminalHitWithEmptyResult(t *testing.T) { + history := []Message{{Role: "user", Content: "q"}} + sess := &stubSession{results: map[string]string{"rag": ""}} + term := map[string]struct{}{"rag": {}} + + hist, answer, hit := appendToolResults(history, []map[string]interface{}{ + toolCallMsg("call-1", "rag", `{"question":"q"}`), + }, sess, term) + + if !hit { + t.Fatal("a successful terminal tool must short-circuit even with an empty result") + } + if answer != "" { + t.Fatalf("answer = %q, want empty", answer) + } + if len(hist) != 3 { + t.Fatalf("history length = %d, want 3 (user + assistant + tool)", len(hist)) + } +} + +// sendTerminal must stay silent for an empty answer, so a streamed terminal +// result is not emitted a second time by the short-circuit. +func TestSendTerminalEmptyAnswerIsSilent(t *testing.T) { + var got []string + sender := func(delta *string, _ *string) error { + if delta != nil { + got = append(got, *delta) + } + return nil + } + empty := "" + if err := sendTerminal(sender, &empty); err != nil { + t.Fatalf("sendTerminal: %v", err) + } + if len(got) != 0 { + t.Fatalf("streamed %v, want nothing for an empty terminal answer", got) + } +} diff --git a/internal/entity/models/cohere.go b/internal/entity/models/cohere.go index 20b5d30126d..f08194b04c7 100644 --- a/internal/entity/models/cohere.go +++ b/internal/entity/models/cohere.go @@ -374,10 +374,15 @@ func (c *CoHereModel) Embed(ctx context.Context, modelName *string, request Embe suffix := strings.TrimPrefix(c.baseModel.URLSuffix.Embedding, "/") url := fmt.Sprintf("%s/%s", baseURL, suffix) + inputType := "search_document" + if request.Query { + // Python CoHereEmbed.encode_queries uses input_type="search_query". + inputType = "search_query" + } reqBody := map[string]interface{}{ "model": *modelName, "texts": request.Texts, - "input_type": "search_document", + "input_type": inputType, "embedding_types": []string{"float"}, } // This is only available for embed-v4 and newer models. Possible values are 256, 512, 1024, and 1536. The default is 1536. diff --git a/internal/entity/models/cohere_test.go b/internal/entity/models/cohere_test.go index 97facea5806..a908edf60b3 100644 --- a/internal/entity/models/cohere_test.go +++ b/internal/entity/models/cohere_test.go @@ -5,9 +5,10 @@ import ( "io" "net/http" "net/http/httptest" - "ragflow/internal/common" "strings" "testing" + + "ragflow/internal/common" ) func newCohereForTest(baseURL string) *CoHereModel { @@ -127,3 +128,30 @@ func TestCohereStreamRecordsDeltaUsage(t *testing.T) { t.Fatalf("model usage=(%d,%d,%d), want (4,2,6)", usage.InputTokens, usage.OutputTokens, usage.TotalTokens) } } + +// TestCohereEmbedInputTypeFollowsQuery pins Python CoHereEmbed: encode sends +// input_type="search_document", encode_queries sends "search_query". +func TestCohereEmbedInputTypeFollowsQuery(t *testing.T) { + withSSRFBypass(t) + ctx := t.Context() + baseURL, bodies := captureEmbedBodies(t, `{"embeddings":{"float":[[0.1]]}}`) + m := newCohereForTest(baseURL) + apiKey := "test-key" + model := "embed-v4.0" + + if _, err := m.Embed(ctx, &model, EmbedRequest{Texts: []string{"a"}}, &APIConfig{ApiKey: &apiKey}, nil, nil); err != nil { + t.Fatalf("Embed: %v", err) + } + if _, err := m.Embed(ctx, &model, EmbedRequest{Texts: []string{"a"}, Query: true}, &APIConfig{ApiKey: &apiKey}, nil, nil); err != nil { + t.Fatalf("Embed(query): %v", err) + } + if got := (*bodies)[0]["input_type"]; got != "search_document" { + t.Errorf("document input_type = %v, want search_document", got) + } + if got := (*bodies)[1]["input_type"]; got != "search_query" { + t.Errorf("query input_type = %v, want search_query", got) + } +} + +// TestVoyageEmbedInputTypeFollowsQuery pins Python VoyageEmbed: encode sends +// input_type="document", encode_queries sends "query". diff --git a/internal/entity/models/common_test.go b/internal/entity/models/common_test.go index b9a572e5fe1..9c500e83923 100644 --- a/internal/entity/models/common_test.go +++ b/internal/entity/models/common_test.go @@ -1,6 +1,7 @@ package models import ( + "encoding/json" "fmt" "io" "net/http" @@ -64,3 +65,24 @@ func TestBaseModelDoStreamRequestAllowsMissingAPIKey(t *testing.T) { func modelFamilyTestString(value string) *string { return &value } + +// captureEmbedBodies serves an embedding endpoint that records every request +// body and replies with respBody. Drivers that read an OpenAI-shaped response +// can use `{"data":[{"embedding":[0.1],"index":0}]}`; Cohere needs its own +// `{"embeddings":{"float":[[0.1]]}}` shape. +func captureEmbedBodies(t *testing.T, respBody string) (baseURL string, bodies *[]map[string]interface{}) { + t.Helper() + captured := &[]map[string]interface{}{} + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + var body map[string]interface{} + _ = json.Unmarshal(raw, &body) + *captured = append(*captured, body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(respBody)) + })) + t.Cleanup(srv.Close) + return srv.URL, captured +} + +const openAIShapeEmbeddingBody = `{"data":[{"embedding":[0.1],"index":0}]}` diff --git a/internal/entity/models/jina.go b/internal/entity/models/jina.go index 4450111d902..f7a54a3dec7 100644 --- a/internal/entity/models/jina.go +++ b/internal/entity/models/jina.go @@ -450,6 +450,16 @@ func (j *JinaModel) Embed(ctx context.Context, modelName *string, request EmbedR "model": *modelName, "input": request.Texts, } + // Python JinaMultiVecEmbed sends task="retrieval.passage" in encode and + // "retrieval.query" in encode_queries, but only for the v3/v4 models + // ("if 'v3' in model_name or 'v4' in model_name"); earlier models take none. + if strings.Contains(*modelName, "v3") || strings.Contains(*modelName, "v4") { + if request.Query { + reqBody["task"] = "retrieval.query" + } else { + reqBody["task"] = "retrieval.passage" + } + } jsonData, err := json.Marshal(reqBody) if err != nil { diff --git a/internal/entity/models/jina_test.go b/internal/entity/models/jina_test.go index 0b15723099e..60df03e6af8 100644 --- a/internal/entity/models/jina_test.go +++ b/internal/entity/models/jina_test.go @@ -527,3 +527,37 @@ func TestJinaRerankDefaultsTopNToDocumentCount(t *testing.T) { t.Fatalf("Rerank: %v", err) } } + +func TestJinaEmbedTaskFollowsQueryForV3V4(t *testing.T) { + withSSRFBypass(t) + ctx := t.Context() + baseURL, bodies := captureEmbedBodies(t, openAIShapeEmbeddingBody) + m := NewJinaModel( + map[string]string{"default": baseURL}, + URLSuffix{Embedding: "embeddings", Rerank: "rerank"}, + ) + apiKey := "test-key" + + v4 := "jina-embeddings-v4" + if _, err := m.Embed(ctx, &v4, EmbedRequest{Texts: []string{"a"}}, &APIConfig{ApiKey: &apiKey}, nil, nil); err != nil { + t.Fatalf("Embed(v4): %v", err) + } + if _, err := m.Embed(ctx, &v4, EmbedRequest{Texts: []string{"a"}, Query: true}, &APIConfig{ApiKey: &apiKey}, nil, nil); err != nil { + t.Fatalf("Embed(v4 query): %v", err) + } + if got := (*bodies)[0]["task"]; got != "retrieval.passage" { + t.Errorf("v4 document task = %v, want retrieval.passage", got) + } + if got := (*bodies)[1]["task"]; got != "retrieval.query" { + t.Errorf("v4 query task = %v, want retrieval.query", got) + } + + // An older model must NOT carry a task at all (Python only sets it for v3/v4). + v2 := "jina-embeddings-v2-base-en" + if _, err := m.Embed(ctx, &v2, EmbedRequest{Texts: []string{"a"}, Query: true}, &APIConfig{ApiKey: &apiKey}, nil, nil); err != nil { + t.Fatalf("Embed(v2 query): %v", err) + } + if _, ok := (*bodies)[2]["task"]; ok { + t.Errorf("v2 must not send task, got %v", (*bodies)[2]["task"]) + } +} diff --git a/internal/entity/models/llm.go b/internal/entity/models/llm.go index b0617cdd354..16e3e50e33d 100644 --- a/internal/entity/models/llm.go +++ b/internal/entity/models/llm.go @@ -46,9 +46,10 @@ import ( // a new instance, never mutating in place — see eino's // components/model/interface.go:84-99 for the rationale). type EinoChatModel struct { - inner *ChatModel - chatCfg *ChatConfig - tools []*schema.ToolInfo + inner *ChatModel + chatCfg *ChatConfig + tools []*schema.ToolInfo + toolChoice *string } // NewEinoChatModel wraps an existing RAGFlow *ChatModel so it can be passed @@ -261,6 +262,8 @@ func (m *EinoChatModel) chatConfigForGenerate() (*ChatConfig, error) { choice = "required" break } + //if m.toolChoice != nil { + // choice = *m.toolChoice } cfg.ToolChoice = &choice for _, tool := range m.tools { @@ -459,6 +462,21 @@ func (m *EinoChatModel) WithTools(tools []*schema.ToolInfo) (model.ToolCallingCh return &cp, nil } +// WithToolChoice returns a NEW EinoChatModel instance constrained to the given +// tool_choice string ("auto", "none", "required", or a specific tool name). +// Empty string leaves the default ("auto"). Mirrors eino's WithToolChoice but +// operates on the RAGFlow wrapper so the choice reaches the driver's request +// body via chatConfigForGenerate. +func (m *EinoChatModel) WithToolChoice(choice string) *EinoChatModel { + cp := *m + if choice == "" { + cp.toolChoice = nil + return &cp + } + cp.toolChoice = &choice + return &cp +} + // Tools returns the tools currently bound to the wrapper (used by // introspection; not part of any eino interface). func (m *EinoChatModel) Tools() []*schema.ToolInfo { diff --git a/internal/entity/models/non_chat_usage_test.go b/internal/entity/models/non_chat_usage_test.go index 5cd0976fac3..a677af4f437 100644 --- a/internal/entity/models/non_chat_usage_test.go +++ b/internal/entity/models/non_chat_usage_test.go @@ -4,6 +4,7 @@ import ( "net/http" "net/http/httptest" "ragflow/internal/common" + "strings" "testing" ) @@ -36,11 +37,17 @@ func TestProviderEmbeddingAndRerankUsage(t *testing.T) { { name: "aliyun", newModel: func(baseURL string) ModelDriver { - return NewAliyunModel(map[string]string{"default": baseURL}, URLSuffix{Embedding: "embedding", Rerank: "rerank"}) + // Aliyun's native embedding API is the only transport carrying + // text_type, and the driver ignores a configured base URL that is + // neither a DashScope host nor already native (".../api/v1") — + // otherwise it falls back to the real DashScope endpoint. + return NewAliyunModel(map[string]string{"default": baseURL + "/api/v1"}, URLSuffix{Embedding: "embedding", Rerank: "rerank"}) }, - embeddingBody: `{"id":"embed-aliyun","data":[{"embedding":[0.1,0.2],"index":0}],"usage":{"prompt_tokens":7,"total_tokens":7}}`, + // Native response shapes: output.embeddings / request_id, and a usage + // block that reports total_tokens only (input/output stay 0). + embeddingBody: `{"request_id":"embed-aliyun","output":{"embeddings":[{"text_index":0,"embedding":[0.1,0.2]}]},"usage":{"total_tokens":7}}`, rerankBody: `{"id":"rerank-aliyun","results":[{"index":0,"relevance_score":0.9}],"usage":{"total_tokens":9}}`, - embedInput: 7, embedTotal: 7, rerankTotal: 9, + embedTotal: 7, rerankTotal: 9, supportsRerank: true, }, { @@ -132,8 +139,9 @@ func TestProviderEmbeddingAndRerankUsage(t *testing.T) { t.Run(tc.name, func(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") - switch r.URL.Path { - case "/embedding": + // The aliyun case is addressed through its native ".../api/v1" root. + switch path := strings.TrimPrefix(r.URL.Path, "/api/v1"); path { + case "/embedding", "/" + aliyunNativeEmbeddingPath: _, _ = w.Write([]byte(tc.embeddingBody)) case "/rerank": _, _ = w.Write([]byte(tc.rerankBody)) diff --git a/internal/entity/models/nvidia.go b/internal/entity/models/nvidia.go index 85c35af18b4..cefe2312c80 100644 --- a/internal/entity/models/nvidia.go +++ b/internal/entity/models/nvidia.go @@ -179,10 +179,16 @@ func (n *NvidiaModel) Embed(ctx context.Context, modelName *string, request Embe return nil, err } + // Python NvidiaEmbed.encode sends input_type="passage" for documents and + // encode_queries sends "query"; the NIM API embeds each side differently. + inputType := "passage" + if request.Query { + inputType = "query" + } reqBody := map[string]interface{}{ "model": *modelName, "input": request.Texts, - "input_type": "query", + "input_type": inputType, "encoding_format": "float", "truncate": "END", } diff --git a/internal/entity/models/nvidia_test.go b/internal/entity/models/nvidia_test.go index dbb851f00af..e3d1b7b5405 100644 --- a/internal/entity/models/nvidia_test.go +++ b/internal/entity/models/nvidia_test.go @@ -387,3 +387,32 @@ func TestNvidiaEmbedUsesModelSpecificURL(t *testing.T) { func ptr[T any](value T) *T { return &value } + +func TestNvidiaEmbedInputTypeFollowsQuery(t *testing.T) { + withSSRFBypass(t) + ctx := t.Context() + baseURL, bodies := captureEmbedBodies(t, openAIShapeEmbeddingBody) + m := NewNvidiaModel( + map[string]string{"default": baseURL}, + URLSuffix{Embedding: "embeddings"}, + ) + apiKey := "test-key" + model := "test-embed-model" + + if _, err := m.Embed(ctx, &model, EmbedRequest{Texts: []string{"a"}}, &APIConfig{ApiKey: &apiKey}, nil, nil); err != nil { + t.Fatalf("Embed: %v", err) + } + if _, err := m.Embed(ctx, &model, EmbedRequest{Texts: []string{"a"}, Query: true}, &APIConfig{ApiKey: &apiKey}, nil, nil); err != nil { + t.Fatalf("Embed(query): %v", err) + } + if got := (*bodies)[0]["input_type"]; got != "passage" { + t.Errorf("document input_type = %v, want passage", got) + } + if got := (*bodies)[1]["input_type"]; got != "query" { + t.Errorf("query input_type = %v, want query", got) + } +} + +// TestJinaEmbedTaskFollowsQueryForV3V4 pins Python JinaMultiVecEmbed: the task +// field is sent only for the v3/v4 models, as "retrieval.passage" in encode and +// "retrieval.query" in encode_queries. diff --git a/internal/entity/models/types.go b/internal/entity/models/types.go index a21c3d516ec..50da4a8331d 100644 --- a/internal/entity/models/types.go +++ b/internal/entity/models/types.go @@ -215,6 +215,12 @@ type EmbedRequest struct { Texts []string // for text Images [][]byte // for image Urls []string // for image + // Query selects the query-side encoding for providers that embed queries + // and documents differently (Python's LLMBundle.encode_queries vs encode): + // Cohere/Bedrock-Cohere input_type=search_query, Voyage input_type=query, + // Jina task=retrieval.query, NVIDIA input_type=query, DashScope + // text_type=query. Providers without an asymmetric mode ignore it. + Query bool } type EmbeddingConfig struct { @@ -349,6 +355,12 @@ type ToolConfig struct { MaxRounds int // max tool-calling rounds (default: 5) MaxRetries int // max retries on failure (default: 3) ToolCallSession ToolCallSession // session that executes tool calls + // TerminalTools names tools whose successful result is already the final + // answer. When a round executes one of them, the loop stops and returns + // that result instead of feeding it back for another model round. Mirrors + // Python's chat_mdl.terminal_tools short-circuit (chat_model.py:619-627). + // Empty disables the short-circuit (existing behaviour). + TerminalTools map[string]struct{} } // ChatModel wraps a ModelDriver with chat-specific configuration @@ -394,3 +406,18 @@ func (cm *ChatModel) BindTools(session ToolCallSession, tools interface{}) { ToolCallSession: session, } } + +// SetTerminalTools marks the named tools as terminal: once one executes +// successfully, the tool loop stops and returns its result as the final answer +// rather than re-invoking the model. Mirrors Python +// `chat_mdl.mdl.terminal_tools = {...}`. Call after BindTools. +func (cm *ChatModel) SetTerminalTools(names ...string) { + if cm.ToolConfig == nil { + return + } + term := make(map[string]struct{}, len(names)) + for _, n := range names { + term[n] = struct{}{} + } + cm.ToolConfig.TerminalTools = term +} diff --git a/internal/entity/models/voyage.go b/internal/entity/models/voyage.go index 51006a4b2df..0e524906ee9 100644 --- a/internal/entity/models/voyage.go +++ b/internal/entity/models/voyage.go @@ -83,9 +83,17 @@ func (v *VoyageModel) Embed(ctx context.Context, modelName *string, request Embe baseURL = strings.TrimSuffix(baseURL, "/") url := fmt.Sprintf("%s/%s", strings.TrimSuffix(baseURL, "/"), v.baseModel.URLSuffix.Embedding) + // Python VoyageEmbed.embed passes input_type="document"; encode_queries + // passes "query". The Voyage API applies a different (asymmetric) encoding + // per input_type, so the field must be sent on both paths. + inputType := "document" + if request.Query { + inputType = "query" + } reqBody := map[string]interface{}{ - "model": *modelName, - "input": request.Texts, + "model": *modelName, + "input": request.Texts, + "input_type": inputType, } if embeddingConfig != nil && embeddingConfig.Dimension > 0 { reqBody["output_dimension"] = embeddingConfig.Dimension diff --git a/internal/entity/models/voyage_test.go b/internal/entity/models/voyage_test.go index 206ee1d478e..8772b52c9e6 100644 --- a/internal/entity/models/voyage_test.go +++ b/internal/entity/models/voyage_test.go @@ -443,3 +443,29 @@ func TestVoyageEmbedTrimsTrailingSlashInBaseURL(t *testing.T) { t.Errorf("path=%q want %q (no double slash)", sawPath, "/v1/embeddings") } } + +func TestVoyageEmbedInputTypeFollowsQuery(t *testing.T) { + withSSRFBypass(t) + ctx := t.Context() + baseURL, bodies := captureEmbedBodies(t, openAIShapeEmbeddingBody) + m := newVoyageForTest(baseURL) + apiKey := "test-key" + model := "voyage-3.5" + + if _, err := m.Embed(ctx, &model, EmbedRequest{Texts: []string{"a"}}, &APIConfig{ApiKey: &apiKey}, nil, nil); err != nil { + t.Fatalf("Embed: %v", err) + } + if _, err := m.Embed(ctx, &model, EmbedRequest{Texts: []string{"a"}, Query: true}, &APIConfig{ApiKey: &apiKey}, nil, nil); err != nil { + t.Fatalf("Embed(query): %v", err) + } + if got := (*bodies)[0]["input_type"]; got != "document" { + t.Errorf("document input_type = %v, want document", got) + } + if got := (*bodies)[1]["input_type"]; got != "query" { + t.Errorf("query input_type = %v, want query", got) + } +} + +// TestNvidiaEmbedInputTypeFollowsQuery pins Python NvidiaEmbed: encode sends +// input_type="passage", encode_queries sends "query" (the Go port previously +// hardcoded "query" for BOTH, embedding indexed documents in the query space). diff --git a/internal/rag/advanced_rag/agentic_rag.go b/internal/rag/advanced_rag/agentic_rag.go new file mode 100644 index 00000000000..35c8673f31d --- /dev/null +++ b/internal/rag/advanced_rag/agentic_rag.go @@ -0,0 +1,1972 @@ +// +// 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. +// + +// Package advanced_rag is the outer agentic-search loop (medium / high / ultra). +// +// This file mirrors Python rag/advanced_rag/agentic_rag.py — the RAGTools +// methods: the run configuration (RAGTools), the rag entry point (Rag) +// and question formalization (Formalize). In Python, RAGTools is the shared +// capability carrier that the agentic graph (agentic_rag_graph.py) and the +// harness action session both read from and write to. In Go the equivalent +// carrier is harness.Toolset (see harness/action_session.go), while this file +// holds the RAGTools-side logic. +// +// The graph driver itself lives in agentic_rag_graph.go (mirroring +// agentic_rag_graph.py), so this package replicates the Python layout: +// - agentic_rag.go ↔ Python agentic_rag.py (RAGTools methods) +// - agentic_rag_graph.go ↔ Python agentic_rag_graph.py (the pipeline) +// - harness/ ↔ Python harness/ (primitives) +package advanced_rag + +import ( + "context" + "fmt" + "log" + "regexp" + "strings" + "sync" + + "github.com/cloudwego/eino/schema" + + "ragflow/internal/agent/chat" + "ragflow/internal/dao" + "ragflow/internal/entity" + "ragflow/internal/entity/models" + "ragflow/internal/rag/advanced_rag/harness" + "ragflow/internal/rag/prompts" + "ragflow/internal/service/nlp" +) + +// RAGTools method map — where each Python method lives in Go. +// +// Python's RAGTools is one object exposing every capability. Go keeps the same +// shape: the RAGTools methods live in this package (agentic_rag_graph.go and +// this file), while harness/ stays the +// leaf capability library they orchestrate (retrieval, sessions, tools). Nothing +// below is re-implemented as a forwarding shim — the Go column IS the +// implementation: +// +// __init__ 221 → RAGTools (below) +// has_* 340 → harness.Toolset (action_session.go) +// _fit_messages 360 → chat.FitMessages (chat/message_fit.go) +// get_citation_guidelines 367 → GetCitationGuidelines (below) +// sys_prompt 371 → SysPrompt (below) +// formalize 412 → Formalize (below) +// retrieve 593 → HybridSearch (harness/tools/search.go) +// _extract_keywords_weighted 571 → ExtractWeightedKeywords (harness/keywords.go) +// extract_keywords 581 → ExtractWeightedKeywords (harness/keywords.go) + CompactKeywords (harness/tool_text_processing.go) +// web_retrieve 676 → searchExecutor.webSearch (harness/tool_executor.go) +// _compose_answer_from_evidence 604 → ComposeAnswer (agentic_rag_graph.go) +// _naive_rag 1517 → ComposeNaiveAnswer (agentic_rag_graph.go) +// _fit_evidence 716 → FitEvidence (below) +// judge_sufficiency 734 → SCA review (harness/orchestrator/sufficient_context.go) +// gen_followups 750 → SCA gap rewrite (harness/orchestrator/sufficient_context.go) +// rag 817 → Rag (below) +// +// Also mirrored, outside this file: +// +// scoped_doc_ids 352 → toolDocScope (harness/tool_executor.go) +// _filter_known_doc_ids 981 → DocIDLookup (below) +// _resolve_doc_tenant 987 → docInDatasets (harness/search.go) +// fetch_full_document 761 → fetchFullDocument (harness/doc_fetch.go) +// summarize_document 934 → summarizeDocument (harness/doc_fetch.go) +// +// All live Python methods now have a Go counterpart, including +// harness.LLMUsageStats (Python harness/stats.py::LLMUsageStats) — Python counts +// usage through a ContextVar and a wrapper chat model, so Go instead passes an +// explicit *harness.LLMUsageStats collector (RAGTools.Stats) to the calls it +// makes; the per-round metrics Python derives from RAGTools.rounds are not +// tracked. +// +// Deliberately not ported — dead code in Python: pick_documents returns None on +// its first statement (agentic_rag.py:500) and is never called, so +// _select_by_titles, _filter_by_metadata, _get_cached_metas and +// _collect_doc_titles are unreachable too; structured_retrieve has neither a +// @tool decorator nor a caller. +// +// RAGTools configures one agentic-search run. It is the single Go mirror of +// Python RAGTools.__init__: every capability the run needs (retriever, model, +// prompts, embedder, kb accumulation, retrieval tuning, answer composition) is +// carried on this one object — there is no second dependency struct. The +// harness layer keeps narrow per-call views (harness.SearchDeps / +// harness.SessionDeps) that are projected from a RAGTools at call time, mirroring +// how Python methods receive self plus extra per-call arguments. Construct it directly +// (RAGTools{...}); its zero value is a valid starting point for the narrower call sites +// that only set a subset of fields. +type RAGTools struct { + // Tools is the shared capability carrier (Python RAGTools instance). The + // graph and the action session both reach retrieval through it. + Tools *harness.Toolset + // Search is the fully-projected retrieval configuration for this run. The + // graph's DUAL-CHANNEL fan-out needs it directly: unlike the action session + // (which goes through Tools.Exec's single "search_chunks" tool), fan-out + // issues a keyword BM25 leg and a dense semantic leg under different + // settings, which the tool interface cannot express. + Search harness.SearchDeps + // Retriever is the retrieval backend. When nil, the runtime singleton + // (runtime.GetRetrievalService) is used. + Retriever harness.Retriever + // Model drives the LLM turns. Required for agentic modes; low/naive never + // call it. + Model harness.SessionModel + // ModelName is the RESOLVED chat model identity (Python chat_mdl.llm_name, + // e.g. "gpt-4o"), one component of the gen_json reply-cache key. Empty + // disables that cache: keying on an empty name would collapse every model + // onto one bucket and serve a reply produced by another model. + ModelName string + // Embedder is the external embedding handle used by graph/structure seed + // encoding (Python tools.embed_mdl). Nil falls back to this package's + // internal tenant-default resolver, which additionally degrades to keyword + // matching when the DB is uninitialised or encoding panics. + Embedder nlp.NavEmbedder + // Keywords extracts the entity-weighted retrieval query. Optional. + Keywords KeywordExtractorFn + // Prompts are the report/SCA/rewrite prompt templates (user_defined_prompts). + Prompts harness.PromptLoader + // Expand runs compiled-structure expansion. Optional. + Expand harness.CompiledExpander + // SCAPrompts overrides Prompts for the sufficient-context review. + SCAPrompts harness.PromptLoader + // RewritePrompts overrides Prompts for the gap→query rewrite call. + RewritePrompts harness.PromptLoader + // KB is the in-flight retrieval accumulation (Python RAGTools.kbinfos). + KB *harness.Kbinfos + // Logger is optional; nil uses the default logger. + Logger *log.Logger + // Answer-composition configuration (see AnswerDeps). All optional; the + // defaults match Python's configured behaviour. + // CiteRules overrides the default citation rules. + CiteRules string + // SystemPrompt is the dialog-level UI configuration appended after the + // agentic contract (language/tone/style may override; evidence contract may not). + SystemPrompt string + // EmptyResponse is returned verbatim when no evidence was found, skipping + // the composition call entirely (Python tools.empty_response). + EmptyResponse string + // EvidenceMaxTokens caps the evidence block. <=0 uses evidenceBudgetTokens. + EvidenceMaxTokens int + // MaxLength is the chat model's context window (Python + // tools.chat_mdl.max_length). It bounds message_fit_in for prompt + // assembly; <=0 falls back to chat.EffectiveContextLength's 8192 default. + MaxLength int + // ComposeAnswer enables the terminal composition node. Defaults to true + // when a model is configured; set false to receive raw evidence only. + ComposeAnswer *bool + // Finalize runs the terminal composition (Python _compose_answer_from_evidence). + // It is wired by Rag so the graph can invoke it FROM INSIDE its last node — + // Python's agentic and low graphs both end in a formalize_answer node that + // composes and streams the answer. Nil means "the caller + // composes afterwards", which is only correct for the naive path. + Finalize func(ctx context.Context) + // Messages is the conversation history used by Formalize to resolve + // pronouns/ellipses into a standalone question. The agentic and low graphs + // formalize it as their first node (Python build_agentic_graph and + // build_low_graph); naive retrieval does not formalize. + Messages []schema.Message + // WebSearch is the optional open-web provider backing the `web_search` tool + // (Python RAGTools.web_search). Nil HIDES the tool from the mode's surface — + // sessionDeps sets HasWebSearch = mode.HasTool("web_search") && WebSearch != nil + // and ActiveToolSpecs drops the spec — so the model is never shown a dead tool. + // Should a call reach the executor anyway (stale spec, direct invocation), it + // answers StatusError/ReasonInfra with a do-not-retry note, NOT a query-level + // MISS: WebSearchTool returns the same infra error Python's _exec_web_search + // does for an absent provider (tool_search.go:826). + WebSearch harness.WebSearcher + // DocIDVerifier checks which requested document ids really belong to the + // datasets being searched (Python RAGTools._filter_known_doc_ids). Nil + // disables the check and leaves the requested scope untouched. + DocIDVerifier harness.DocIDVerifier + // DocChunks pages through a single document's chunks in reading order + // (Python settings.retriever.chunk_list, sort_by_position=True). It backs + // the whole-document-reading path (summarize_document / fetch_full_document) + // mirroring Python's chunk-list reads. Nil disables whole-document reading: + // the document-level tools report that it is unavailable. + DocChunks harness.DocChunkLister + // Outer is the outer-layer chat model that drives the Python-style + // rag_agent react loop (Python RAGTools.chat_mdl, used by + // dialog_service.rag_agent via chat_mdl.async_chat_with_tools with + // tools=[rag, summarize_document] and terminal_tools={"rag"}). When non-nil, + // Rag runs that outer loop: the model may call `rag` (terminal — runs the + // inner agentic graph and returns the cited answer) or `summarize_document` + // (non-terminal — reads a whole document into evidence and lets the model + // answer from it on the next round); with no tool call it answers directly. + // When nil, Rag falls back to the existing direct RunAgenticRAG path, so + // callers that don't wire an outer model see unchanged behaviour. + Outer *models.ChatModel + // OuterSupportsTools mirrors Python dialog_service.rag_agent's + // `if not getattr(chat_mdl, "is_tools", False)` gate: when the outer model + // exists but cannot emit tool calls, the outer react loop must be skipped + // (it would otherwise bind tools and, producing no tool_call, return a + // retrieval-less direct answer). Callers set it from + // ModelProviderService.ResolveModelToolSupport. + OuterSupportsTools bool + // Cache answers near-identical re-asks from an earlier answer (Python + // RAGTools._rag_cache). Rag builds a fresh per-turn RAGCache when this is + // nil, so caching is ON by default (matching Python's always-present + // _rag_cache). To share one cache across multiple Rag() calls within a + // single turn (Python's concurrent tool_call case), pass the same *RAGCache + // here instead of relying on the auto-built one. + Cache *RAGCache + // OriginalQuestion is the user's own, unrewritten question (Python + // tools.original_user_question). When the outer caller passes a compressed + // rewrite as Question, the original is preferred if both clearly describe + // the same turn. + OriginalQuestion string + // TextAttachments is appended to the question and bypasses the re-ask cache + // (Python tools.text_attachments_content). + TextAttachments string + // AnswerSink receives the answer as it is produced (Python + // tools.answer_sink). Nil disables streaming; the answer is still returned + // in full. Requires a model implementing harness.StreamingSessionModel, + // otherwise the run falls back to one-shot composition. + AnswerSink *AnswerSink + // ToolStarted is called once research begins, before any retrieval, so the + // caller can show progress (Python tools.tool_started_sink). + ToolStarted func() + // Progress receives engine-stage progress lines tagged like Python's + // think-log entries (e.g. "[Planner] Splitting the research question into + // tasks", "[Hybrid search] Searching for answers in the knowledge base") as + // the agentic loop runs. It is the Go counterpart of Python's + // rag/advanced_rag/think_log.py — those tagged lines used to be fished out of + // the log stream and forwarded into the block of the chat UI. Nil + // disables streaming progress; the pipeline still completes with the answer. + // A caller that also sets AnswerSink typically routes each line as a + // isThink=true delta so the reasoning block shows live research progress. + Progress func(line string) + // Retrieval tuning, mirroring Python RAGTools.retrieve: an explicit tool + // argument still wins over these, and zero selects the harness defaults. + TopN int + SimilarityThreshold float64 + // VectorSimilarityWeight is the vector leg's weight (Python + // tools.vector_similarity_weight). A pointer so an explicit 0 — keyword-only, + // which is what Python's agentic retrieve uses — is distinguishable from + // "not configured". Nil selects DefaultAgenticVectorWeight (0). + VectorSimilarityWeight *float64 + // UsingEmbedding is the Go spelling of Python RAGTools.retrieve's + // `using_embedding: bool = False` (agentic_rag.py:599). When false (the + // agentic default) retrieval is keyword-only (vector weight 0); when true + // the embedder is engaged and VectorSimilarityWeight (default 0.7) applies. + // + // SCOPE: only the RAGTools.retrieve channel honours it — Python's + // using_embedding lives on that function alone. + UsingEmbedding bool + // HasEmbedder is the Go spelling of Python `tools.embed_mdl` being set + // (dialog_service.py:2075). It gates hybrid_search's vector leg + // (search.py:143 `vector_weight = _setting(...) if embd_mdl else 0`), i.e. + // the semantic recall of the search_chunks tool. + HasEmbedder bool + RerankCandidatesCount int + TopK int + // DocScope is the session-wide document restriction (Python + // tools.doc_scope). Nil means "search everything". + DocScope []string + // MetaDataFilter restricts retrieval by chunk metadata (Python + // tools.meta_data_filter). + MetaDataFilter map[string]any + // KBs mirrors Python RAGTools' self.kbs (agentic_rag.py:283) — the full + // Knowledgebase objects (carrying parser_config / tenant_id) the agentic + // tools run over. Python loads these via + // KnowledgebaseService.get_by_ids(kb_ids) in __init__; Go receives the + // already-resolved objects from the caller (this package stays DB-free) and + // feeds them to the Tagger, mirroring retrieve's + // `rank_feature=label_question(question, self.kbs)`. + KBs []*entity.Knowledgebase + // Tagger mirrors Python RAGTools.retrieve's + // `rank_feature=label_question(question, self.kbs)` (agentic_rag.py:668): it + // classifies the query into question-type tags the retriever uses to boost + // matching chunks. It is the Go equivalent of rag.app.tag.label_question, + // implemented by internal/service.MetadataService.LabelQuestion. Nil means + // no tag boost (Python's label_question returning None). + Tagger harness.QuestionLabeler + // Stats receives per-phase LLM usage for this run (Python + // RAGTools.llm_stats, mirrored by harness.LLMUsageStats). Nil disables + // collection. + Stats *harness.LLMUsageStats +} + +// sessionDeps projects RAGTools onto the harness.SessionDeps the action session +// and slot-table builders consume. +// +// Every field is forwarded unconditionally. In particular a nil Prompts is NOT +// a reason to drop Tools/KB: the harness resolves a nil loader to its embedded +// canonical templates (harness.resolveLoader / prompts.EmbeddedPromptLoader), so +// the action session still runs with its toolset and the shared evidence pool. +// Returning a Model-only projection here silently turned the slot research pass +// into a tool-less question-answering turn. +func (d RAGTools) sessionDeps() harness.SessionDeps { + return harness.SessionDeps{ + Tools: d.Tools, + Model: d.Model, + Prompts: d.Prompts, + KB: d.KB, + } +} + +func (d RAGTools) logger() *log.Logger { + if d.Logger != nil { + return d.Logger + } + return _LOG +} + +// Question formalization (the graph's first node). +// +// Mirrors Python agentic_rag.RAGTools.formalize (line 412): rewrite the latest +// user message into a standalone question AND derive its search keywords, in one +// LLM call. +// +// Single-turn shortcut: when there is nothing to resolve, the question is kept +// VERBATIM (no rewrite) and only keywords are extracted. Rewriting a +// self-contained question risks silently changing its meaning — and the +// single-turn case is the overwhelming majority. +// +// The keyword/JSON extraction helpers (ExtractWeightedKeywords, ExtractJSON) +// stay in harness as the leaf capability library. + +const ( + // formalizeTimeoutS bounds the formalize call. + formalizeTimeoutS = 45.0 + // formalizeTemperature mirrors Python's chat conf at agentic_rag.py:471: + // formalization is a mechanical rewrite, so it must be stable. + formalizeTemperature = 0.1 +) + +var reFormalizeThink = regexp.MustCompile(`(?s)^.*`) + +var formalizePrompt = (`You are given a conversation. Do BOTH of the following and return JSON only: +1. Rewrite the LAST user message into a single, self-contained question that can be understood without the prior conversation — resolve pronouns, ellipses and follow-up shortcuts using the earlier turns. In most cases, it should be EXACTLY THE SAME as the last user query — only rewrite when there is something to resolve (a pronoun/ellipsis pointing back at an earlier turn). Preserve the original language. +2. Extract keywords for a keyword search: the salient content words and phrases that literally appear in the (standalone) question — key nouns, named entities, domain terms — PLUS 2-3 close synonyms/abbreviations/aliases/alternative spellings of each, in the SAME language as the question. Maximize recall. Do NOT include terms that would be part of the answer. + Example — "In which year did Apple acquire Beats?" -> keywords = "Apple, Apple Inc., AAPL, acquire, acquisition, acquired, Beats, Beats Electronics". + +Output ONLY JSON, no prose, no code fences: {"question": "", "keywords": ""}`) + +// Formalize mirrors Python RAGTools.formalize: return (question, keywords) for +// the given conversation. +// +// messages may be []schema.Message (preferred) or pre-formatted "Speaker: text" +// strings. On any failure it degrades to (last user message, "") — formalization +// is an optimization, never a precondition for answering. +// +// maxLength is the chat model's context window (Python tools.chat_mdl.max_length); +// it bounds the prompt fit. <=0 falls back to chat.EffectiveContextLength's 8192. +func Formalize(ctx context.Context, deps harness.SessionDeps, messages []schema.Message, maxLength int) (string, string) { + lastUser, transcript := transcriptOf(messages) + if lastUser == "" { + return "", "" + } + if deps.Model == nil { + // No model: keep the raw question and skip keyword extraction rather + // than failing the request. + return lastUser, "" + } + + // Single-turn: nothing to resolve — keep the question VERBATIM (rewriting a + // self-contained question risks silently changing its meaning), and extract + // only the search keywords (Python: tools.extract_keywords). + if !isMultiTurn(messages) { + _LOG.Printf("[Formalize] Single-turn self-contained question — kept verbatim (no rewrite): %s", trunc(lastUser, 120)) + _, kw := harness.ExtractWeightedKeywords(ctx, deps.Model, lastUser) + return lastUser, kw + } + + ctx, done := harness.Phase(ctx, harness.PhaseFormalize) + // Phase returns a child context carrying the phase label; the timeout is + // derived from it so the call is both attributed and bounded. + defer done() + + callCtx, cancel := context.WithTimeout(ctx, deadlineToDuration(formalizeTimeoutS)) + defer cancel() + + // Python 470: message_fit_in(form_message(system, user), chat_mdl.max_length). + fitted, fitErr := chat.FitMessages(formalizePrompt, []schema.Message{ + *schema.UserMessage("Conversation:\n" + transcript + "\n\nOutput JSON:"), + }, maxLength) + if fitErr != "" { + _LOG.Printf("[Formalize] prompt fitting failed: %s", fitErr) + return lastUser, "" + } + system := formalizePrompt + history := fitted + if len(fitted) > 0 && fitted[0].Role == schema.System { + system = fitted[0].Content + history = fitted[1:] + } + msgs := make([]schema.Message, 0, 1+len(history)) + msgs = append(msgs, *schema.SystemMessage(system)) + msgs = append(msgs, history...) + + // Python 471: async_chat(system, history, {"temperature": 0.1}). + reply, err := modelWithTemperature(deps.Model, formalizeTemperature).Complete(callCtx, msgs, nil) + if err != nil { + _LOG.Printf("[Formalize] failed; keeping the raw question: %v", err) + return lastUser, "" + } + + data, _ := harness.ExtractJSON(stripThinkAndFences(reply.Content)).(map[string]any) + question := "" + if data != nil { + if raw, ok := data["question"]; ok && raw != nil { + question = strings.Trim(strings.TrimSpace(fmt.Sprint(raw)), "\"'") + } + } + if question == "" { + // Fall back to the raw last user message rather than an empty question. + question = lastUser + } + keywords := "" + if data != nil { + switch v := data["keywords"].(type) { + case string: + keywords = v + case []any: + parts := make([]string, 0, len(v)) + for _, k := range v { + if s := strings.TrimSpace(fmt.Sprint(k)); s != "" { + parts = append(parts, s) + } + } + keywords = strings.Join(parts, ", ") + } + } + return question, harness.CompactKeywords(keywords) +} + +// transcriptOf renders the conversation and extracts the last user message. +func transcriptOf(messages []schema.Message) (lastUser, transcript string) { + var lines []string + for _, m := range messages { + content := m.Content + switch m.Role { + case schema.User: + lastUser = strings.TrimSpace(content) + lines = append(lines, "User: "+content) + case schema.Assistant: + lines = append(lines, "Assistant: "+content) + case schema.System: + lines = append(lines, "System: "+content) + default: + lines = append(lines, strings.TrimSpace(content)) + } + } + return strings.TrimSpace(lastUser), strings.Join(lines, "\n") +} + +// isMultiTurn reports whether the conversation has more than one user turn. +// Mirrors Python's `multi_turn = len(user_msgs) > 1`. +func isMultiTurn(messages []schema.Message) bool { + n := 0 + for _, m := range messages { + if m.Role == schema.User { + n++ + } + } + return n > 1 +} + +// stripThinkAndFences mirrors Python agentic_rag.py:474-475: drop a leading +// thinking preamble, then strip Markdown fences. Python's fence regex removes +// the delimiters wherever they appear, so a truncated or inline fence leaves no +// residue either. +func stripThinkAndFences(s string) string { + s = reFormalizeThink.ReplaceAllString(s, "") + s = reFenceDelimiters.ReplaceAllString(s, "") + return strings.TrimSpace(s) +} + +// reFenceDelimiters mirrors Python's `re.sub(r"```(?:json)?\s*|\s*```", "", s)`. +var reFenceDelimiters = regexp.MustCompile("```(?:json)?\\s*|\\s*```") + +// End-to-end entry point: one call that runs the harness and publishes the +// evidence it collected. +// +// Rag mirrors Python RAGTools.rag (agentic_rag.py:817) — the RAGTools method +// that drives the research pipeline. It owns the conversation-level concerns +// (re-ask cache, the effective question, attachments, composing the final +// answer) and delegates the mode dispatch to RunAgenticRAG, which mirrors +// run_agentic_rag and carries its dispatch: +// +// mode is NAIVE → _naive_rag (plain retrieval) +// mode.Agentic → build_agentic_graph (medium / high / ultra) +// else → build_low_graph (low: formalize → direct_search) +// +// SCOPE NOTE — read before relying on this for agentic modes: the outer +// orchestration that agentic_rag_graph.py owns — planner decomposition, prefetch +// fan-out, and the SCA↔rewriter iteration loop that drives medium/high/ultra — is +// the advanced_rag package's agentic planner (Rag's agentic-loop registration). +// So: +// +// - low / naive: fully wired here (direct search through HybridSearch). +// - medium/high/ultra: Rag delegates to the registered AgenticLoop, which the +// advanced_rag package registers (see SetAgenticLoop). Without it, Rag falls +// back to a single action session. +// +// The harness package keeps the low-level retrieval / session / tool machinery +// (RunActionSession, HybridSearch, Toolset, Kbinfos, searchExecutor, ...). + +// RunRequest lives in the harness package (see harness/tool_executor.go) because the +// harness engine's searchExecutor needs it to carry the per-run query, and the +// advanced_rag package must not be imported from harness (import-cycle rule). +// RunResponse is the agent-side result type returned by RAGTools.rag. + +// RunResponse is the outcome of one harness run. +type RunResponse struct { + // Answer is the session's terminal answer, when it produced one. + Answer string + // Slots are the filled slot-table values discovered by the session. + Slots []harness.Variable + // Chunks is the evidence accumulated in Kbinfos (narrowed, as the model saw + // it). Citations are built from this. + Chunks []map[string]any + // DocAggs is the per-document aggregation of Chunks. + DocAggs []map[string]any + // EmptyResult is true when nothing was retrieved, which the caller turns + // into an "I don't have enough information" answer (Python direct_search's + // empty_result). + EmptyResult bool + // Mode is the resolved spec, for logging. + Mode harness.ModeSpec + // Partial is true when research ended without a satisfying verdict, so the + // caller surfaces the residual findings honestly instead of refusing. + Partial bool + // SearchRounds is the number of completed SCA→rewrite iterations (0 for the + // non-agentic paths). + SearchRounds int + // GraphFailed is true when the research graph itself errored. Python pairs it + // with "produced nothing" before falling back to an internal-error message + // (run_agentic_rag); an empty result on its own is not a failure. + GraphFailed bool + // Verdict is the final sufficiency verdict ("SUFFICIENT"/"INSUFFICIENT"). + Verdict string + // SCAFeedback is the body of the SCA feedback note — agentic_rag.py:902-929's + // string, which is the sufficiency status hint alone (the verdict dict carries + // only "status"; see scaFeedback). Rag() appends it as the "[Research status]" + // note for every INSUFFICIENT verdict, adding the trailing "STOP" vs "call rag + // again" sentence based on the consecutive-unanswerable count. + SCAFeedback string + // CollectedAnswer is the research draft (SCA-reviewed) produced by the + // agentic loop. It feeds the final composition; prefer Answer for display. + CollectedAnswer string + // Kbinfos carries the full accumulated state (including the lossless + // memory store) for callers that need more than the summary above. + Kbinfos *harness.Kbinfos +} + +// AnswerSink forwards a partially produced answer while the model is still +// writing it (Python tools.answer_sink). Nil disables streaming; the answer is +// still returned in full. +// +// Requires a model implementing harness.StreamingSessionModel; otherwise the run +// falls back to a single completion. +type AnswerSink struct { + // OnDelta receives each successive piece of the answer. isThink marks pieces + // of a hidden reasoning block, which must not be shown as part of the answer + // (Python answer_sink(delta, kind == "think")). + OnDelta func(delta string, isThink bool) + // OnReset drops what has been forwarded so far. It is called before a + // fallback re-sends the answer from scratch, so a partially streamed answer + // is never shown twice. Nil means the sink cannot rewind, and the caller + // only sends the complete answer. + OnReset func() +} + +// deliver forwards one piece, if the sink has a handler. +func (s *AnswerSink) deliver(delta string, isThink bool) { + if s == nil || s.OnDelta == nil || delta == "" { + return + } + s.OnDelta(delta, isThink) +} + +// reset discards previously forwarded pieces, if the sink supports it. +func (s *AnswerSink) reset() { + if s == nil || s.OnReset == nil { + return + } + s.OnReset() +} + +// KeywordExtractorFn extracts the weighted retrieval query for a question. +type KeywordExtractorFn func(ctx context.Context, question string) (retrievalQuery string, err error) + +// Run executes one harness request end to end and publishes the evidence into +// the canvas state (when the context carries one) so citation grounding can +// read it. +// +// It never fails for a recoverable reason: a missing component degrades to +// "no evidence" rather than erroring, matching Python's behaviour of logging +// and returning an empty kbinfos. +// ragCacheMinOverlap is the word-overlap ratio at which a new question counts +// as a re-ask of a cached one (Python _RAG_CACHE_MIN_OVERLAP). +const ragCacheMinOverlap = 0.6 + +// ragCacheMinShared is the minimum number of shared significant words before a +// cached answer may be reused (Python _RAG_CACHE_MIN_SHARED). +const ragCacheMinShared = 2 + +// effectiveQuestionMinShared is the overlap _resolve_effective_question needs +// before trusting the original question over the outer rewrite. Python uses the +// literal 2 here, independent of _RAG_CACHE_MIN_SHARED. +const effectiveQuestionMinShared = 2 + +// ragCacheStopwords is Python _RAG_CACHE_STOPWORDS: for cross-`rag`-call dedup +// only, never for retrieval or answer quality. +var ragCacheStopwords = map[string]bool{ + "the": true, "a": true, "an": true, "is": true, "was": true, "were": true, + "what": true, "which": true, "when": true, "where": true, "who": true, + "how": true, "of": true, "in": true, "to": true, "for": true, "and": true, + "or": true, "but": true, "on": true, "at": true, "by": true, "be": true, + "as": true, "it": true, "that": true, "this": true, "about": true, + "with": true, "their": true, "its": true, "have": true, "has": true, + "had": true, "been": true, "being": true, "from": true, "over": true, + "under": true, "do": true, "does": true, "did": true, "not": true, + "no": true, "yes": true, "can": true, "could": true, "should": true, + "would": true, "also": true, "only": true, "very": true, "much": true, + "more": true, "most": true, "some": true, "any": true, +} + +// reQuestionTokens mirrors Python's `re.findall(r"[a-zA-Z0-9一-鿿]+", ...)`. +var reQuestionTokens = regexp.MustCompile(`[a-zA-Z0-9\x{4e00}-\x{9fff}]+`) + +// questionGram is Python _question_keywords' return value: the significant +// words plus the numeric tokens kept apart, so questions naming different +// numbers are never treated as the same question. +type questionGram struct { + words map[string]bool + numbers map[string]bool +} + +// questionKeywords mirrors Python _question_keywords. For English, plain +// tokenisation suffices; CJK tokens survive as whole significant units. +func questionKeywords(question string) questionGram { + gram := questionGram{words: map[string]bool{}, numbers: map[string]bool{}} + tokens := reQuestionTokens.FindAllString(strings.ToLower(question), -1) + for _, t := range tokens { + if isDigitToken(t) { + gram.numbers[t] = true + } + } + for _, t := range tokens { + if len([]rune(t)) > 1 && !isDigitToken(t) && !ragCacheStopwords[t] { + gram.words[t] = true + } + } + if len(gram.words) == 0 { + // Python falls back to every non-numeric token, so an all-stopword + // question still has something to compare. + for _, t := range tokens { + if len([]rune(t)) > 1 && !isDigitToken(t) { + gram.words[t] = true + } + } + } + return gram +} + +func isDigitToken(s string) bool { + if s == "" { + return false + } + for _, r := range s { + if r < '0' || r > '9' { + return false + } + } + return true +} + +// cacheSimilar mirrors Python _cache_similar: significant-word overlap +// (shared / min cardinality), and numbers must be both empty or identical. +func cacheSimilar(a, b questionGram) bool { + if len(a.words) == 0 || len(b.words) == 0 { + return false + } + if len(a.numbers) > 0 || len(b.numbers) > 0 { + if !sameTokens(a.numbers, b.numbers) { + return false + } + } + shared := 0 + for w := range a.words { + if b.words[w] { + shared++ + } + } + if shared < ragCacheMinShared { + return false + } + minLen := len(a.words) + if len(b.words) < minLen { + minLen = len(b.words) + } + return float64(shared)/float64(minLen) >= ragCacheMinOverlap +} + +func sameTokens(a, b map[string]bool) bool { + if len(a) != len(b) { + return false + } + for k := range a { + if !b[k] { + return false + } + } + return true +} + +// FitEvidence mirrors Python RAGTools._fit_evidence (agentic_rag.py:716): trim +// evidence so question + evidence + the template stay inside a FIXED budget. +// +// The budget is deliberately not the model's full context: a large retrieval +// pool must never fill the window with evidence, so each sufficiency/answer call +// stays cheap. message_fit_in keeps the small side (the question) whole and +// trims the large side (the evidence), which is what the two-message shape +// below asks for. +func FitEvidence(question, evidence string) string { + if evidence == "" { + return evidence + } + fitted, fitErr := chat.FitMessages("", []schema.Message{ + *schema.UserMessage(question), + *schema.UserMessage(evidence), + }, evidenceBudgetTokens) + if fitErr != "" || len(fitted) == 0 { + return evidence + } + return fitted[len(fitted)-1].Content +} + +// routerPromptBody is Python's router_prompt (agentic_rag.py:383-403) with the +// summarize_document line left as %s: that line is only included when +// unstructured retrieval is available (Python has_unstructured). +const routerPromptBody = "You are a smart agent. For any question that needs " + + "evidence from the knowledge bases or the web, call the `rag` tool " + + "with a self-contained question — it runs the full search-and-answer " + + "pipeline and returns a cited answer.\n" + + "After the `rag` tool returns, do not call `rag` again for the same " + + "user question. Use the returned cited answer as the final answer " + + "unless the user explicitly asks a new question.\n" + + "CRITICAL — preserve the full multi-hop structure when phrasing the " + + "`rag` question. A question that compares two or more DISTINCT " + + "targets or needs an arithmetic result across them (\"how much taller " + + "is X than Y\", \"how many days after A's death did B die\", \"which of " + + "these was discovered last\") MUST keep every target and relation in " + + "the question you pass to `rag`. Never rewrite a comparison into a " + + "single-entity question — dropping the second entity (e.g. the " + + "purchaser in \"how many days after his death did the man who " + + "purchased it in 1933 die\") makes the pipeline answer only the first " + + "part. Pass the complete comparison.\n" + + "%s" + + "Do not invent facts and do not fabricate document IDs." + +// routerSummarizeLine is the conditional summarize_document instruction +// (Python agentic_rag.py:378-381). +const routerSummarizeLine = "- Call `summarize_document` ONLY when the user explicitly asks to summarise a specific document ('summarise the security audit', 'tldr the onboarding guide'). It needs a document ID.\n" + +// SysPrompt mirrors Python RAGTools.sys_prompt (agentic_rag.py:371): the thin +// router prompt for callers that bind the tool set. The workflow itself lives in +// the rag graph; the outer model only chooses between retrieval and an explicit +// single-document summary. +// +// hasUnstructured mirrors Python has_unstructured(): when false the +// summarize_document instruction is omitted. systemPrompt is the dialog-level UI +// configuration, prepended when set (Python :404-405). +func SysPrompt(systemPrompt string, hasUnstructured bool) string { + summarizeLine := "" + if hasUnstructured { + summarizeLine = routerSummarizeLine + } + router := fmt.Sprintf(routerPromptBody, summarizeLine) + if strings.TrimSpace(systemPrompt) != "" { + return systemPrompt + "\n\n" + router + } + return router +} + +// GetCitationGuidelines mirrors Python RAGTools.get_citation_guidelines +// (agentic_rag.py:367): the citation rules the final answer must follow, with +// an optional user-defined override. +// +// Python renders `citation_prompt(self.user_defined_prompts)`; Go loads the same +// citation_prompt.md via prompts.CitationPrompt and takes a non-empty override +// verbatim — exactly as Python returns citation_prompt(self.user_defined_prompts). +func GetCitationGuidelines(userDefined string) string { + return prompts.CitationPrompt(userDefined) +} + +// resolveEffectiveQuestion mirrors Python _resolve_effective_question: prefer +// the user's ORIGINAL, complete question over the outer model's rewrite, but +// only when both clearly describe the same user turn. The outer rewrite often +// drops the final target of a multi-hop question, and no later stage can +// recover a deleted answer-attribute. +func resolveEffectiveQuestion(question, originalUserQuestion string) string { + if question == "" || originalUserQuestion == "" { + return question + } + original := strings.TrimSpace(originalUserQuestion) + if original == "" { + return question + } + qk := questionKeywords(question) + ok := questionKeywords(original) + if len(qk.words) == 0 || len(ok.words) == 0 { + return question + } + shared := 0 + for w := range qk.words { + if ok.words[w] { + shared++ + } + } + if shared >= effectiveQuestionMinShared { + return original + } + return question +} + +// RAGCache mirrors Python RAGTools._rag_cache (agentic_rag.py:837-889): it +// answers a near-identical re-ask from a previous answer instead of re-running +// the whole graph. +// +// Lifetime: Python keeps _rag_cache on the RAGTools instance, which is rebuilt +// for every dialog turn, so caching is per-turn by construction and is ON by +// default. Go mirrors that default-on, per-turn behavior: Rag builds a fresh +// RAGCache when deps.Cache is nil, so caching is never off, and the auto-built +// cache lives only for that call (the per-turn degenerate case under the +// current single-Rag()-per-turn path), so it can never serve a stale cross-turn +// hit. A caller that wants to share one cache across multiple Rag() calls within +// a single turn (Python's concurrent tool_call case) injects the same *RAGCache +// via RAGTools.Cache instead of relying on the auto-built one. This matches +// Python, where _rag_cache lives on the per-turn RAGTools instance. +type RAGCache struct { + mu sync.Mutex + entries map[string]ragCacheEntry + lastVerdict string + // ConsecutiveUnanswerable mirrors Python RAGTools._consecutive_unanswerable + // (agentic_rag.py:818): how many consecutive rag() calls ended without a + // satisfying verdict. After two in a row, RAGTools.rag appends a + // "[Research status] … STOP calling rag again" note to the answer so the + // outer agent stops re-asking. Python resets it on every RAGTools instance + // (rebuilt per turn), so it counts consecutive insufficient rounds within a + // single request; it is not persisted across turns unless a caller injects a + // long-lived *RAGCache via RAGTools.Cache. + ConsecutiveUnanswerable int +} + +type ragCacheEntry struct { + answer string + gram questionGram +} + +// NewRAGCache returns an empty per-request cache. +func NewRAGCache() *RAGCache { + return &RAGCache{entries: map[string]ragCacheEntry{}} +} + +// Lookup returns the cached answer for a question judged near-identical to an +// earlier one. Attachments bypass the cache (their content is not part of the +// key), and a previous round that was not SUFFICIENT invalidates reuse: the +// caller asked again precisely because it needs more evidence. +func (c *RAGCache) Lookup(question string) (string, bool) { + if c == nil || question == "" || !c.reuseAllowed() { + return "", false + } + gram := questionKeywords(question) + + c.mu.Lock() + defer c.mu.Unlock() + for _, e := range c.entries { + if cacheSimilar(gram, e.gram) { + return e.answer, true + } + } + return "", false +} + +// Store records answer for question. +func (c *RAGCache) Store(question, answer string) { + if c == nil || question == "" || answer == "" { + return + } + gram := questionKeywords(question) + c.mu.Lock() + defer c.mu.Unlock() + if c.entries == nil { + c.entries = map[string]ragCacheEntry{} + } + c.entries[question] = ragCacheEntry{answer: answer, gram: gram} +} + +// noteVerdict records the verdict of the last research round. +func (c *RAGCache) noteVerdict(verdict string) { + if c == nil { + return + } + c.mu.Lock() + defer c.mu.Unlock() + c.lastVerdict = verdict +} + +// researchStatusTrailer mirrors Python rag (:902-929): for every non-SUFFICIENT +// verdict it returns the trailing sentence folded into the "[Research status]" +// note. After two consecutive unsatisfying rag() calls (ConsecutiveUnanswerable +// >= 2 on the shared *RAGCache) it tells the outer agent to STOP calling rag +// again; otherwise it invites a focused re-ask. It returns "" when there is +// nothing to annotate — a SUFFICIENT verdict, an empty answer, or no SCA +// feedback. +func researchStatusTrailer(cache *RAGCache, resp *RunResponse) string { + if resp.Verdict != VerdictInsufficient || resp.SCAFeedback == "" || resp.Answer == "" { + return "" + } + if cache != nil && cache.ConsecutiveUnanswerable >= 2 { + return " STOP calling rag again: the same gaps remain." + } + return " If these gaps are material, call rag again with a question focused on them." +} + +// reuseAllowed mirrors Python's `_cache_ok = not last_status or last_status == +// "SUFFICIENT"`. +func (c *RAGCache) reuseAllowed() bool { + if c == nil { + return false + } + c.mu.Lock() + defer c.mu.Unlock() + return c.lastVerdict == "" || c.lastVerdict == "SUFFICIENT" +} + +// wrapModelForStats wraps the model's invoker so calls made through it are +// counted per phase. It reports false when the model carries no chat.Invoker, +// in which case the caller leaves it untouched. +// +// Python achieves the same by handing a CountingChatModel proxy to the tools +// (agentic_rag.py:267); Go's SessionModel does not expose its invoker in a +// uniform way, so only the known carrier is wrapped. Callers that go through +// other session models still get counted when they record via CurrentStats(ctx). +func wrapModelForStats(model harness.SessionModel, stats *harness.LLMUsageStats) (harness.SessionModel, bool) { + src, ok := model.(*harness.InvokerSessionModel) + if !ok || src == nil || src.Invoker == nil { + return model, false + } + // Copy before mutating: the caller may share this model across requests, and + // wrapping in place would attach another run's stats to it. + wrapped := *src + wrapped.Invoker = &harness.CountingInvoker{Inner: src.Invoker, Stats: stats} + return &wrapped, true +} + +// searchDepsFor projects a RAGTools' FULL retrieval configuration into the harness +// view for one request, including tenant/dataset resolution and the nil-backend +// fallback. Projecting here rather than at each call site keeps the retrieval paths +// (Rag's low/naive pass, the agentic fan-out and action session, the no-model +// fallback) from drifting — a partial copy silently drops tuning such as +// rank_feature (Python's `rank_feature=label_question(question, self.kbs)`, :668). +func searchDepsFor(ctx context.Context, deps RAGTools, req harness.RunRequest, datasetIDs []string, tenantID string, kb *harness.Kbinfos, logger *log.Logger) harness.SearchDeps { + if tenantID == "" { + tenantID = harness.TenantIDFromContext(ctx) + } + backend := deps.Retriever + if backend == nil { + backend = &harness.RuntimeRetriever{} + } + return harness.SearchDeps{ + Backend: backend, + KbIDs: datasetIDs, + TenantID: tenantID, + KB: kb, + Expand: deps.Expand, + Logger: logger, + DocIDVerifier: deps.DocIDVerifier, + DocChunks: deps.DocChunks, + DocTenantResolver: dbDocTenantResolver{}, + Model: deps.Model, // the calculate tool writes its expression via the model + DocScope: deps.DocScope, + // Python retrieve:614-646 — configuration is the middle precedence + // level, between an explicit tool argument and the module defaults. + TopN: deps.TopN, + SimilarityThreshold: deps.SimilarityThreshold, + VectorSimilarityWeight: deps.VectorSimilarityWeight, + UsingEmbedding: deps.UsingEmbedding, + HasEmbedder: deps.HasEmbedder, + RerankCandidatesCount: deps.RerankCandidatesCount, + TopK: deps.TopK, + MetaDataFilter: deps.MetaDataFilter, + // rank_feature (Python retrieve:668): RAGTools carries the KB objects + // and a tagger, mirroring rank_feature=label_question(question, self.kbs). + KBs: deps.KBs, + Tagger: deps.Tagger, + // External embedding handle (Python tools.embed_mdl). When the caller + // supplied one on RAGTools it is used directly; nil keeps the package's + // internal tenant-default resolver as a fallback (which itself degrades + // to keyword matching when the DB is uninitialised or encoding panics). + Embedder: deps.Embedder, + } +} + +// NewDocTenantResolver returns the DB-backed doc→(kb, tenant) resolver used to +// group a document scope by its real owner (Python tools._resolve_doc_tenant). +// It is the same resolver graph_explore uses; the compiled expander takes it too +// so a doc scope is scanned per owning dataset instead of being attached to +// every bound one. +func NewDocTenantResolver() harness.DocTenantResolver { return dbDocTenantResolver{} } + +// dbDocTenantResolver implements harness.DocTenantResolver against the database: it +// maps each document id to its real owning (kb, tenant) so graph_explore can group +// documents by owner and search knowledge bases outside the caller's datasetIDs. +// Mirrors Python tools._resolve_doc_tenant (exploration.py:_kg_scopes); the lookup is +// tenant-unscoped on purpose — DocScope is already constrained to the user's authorized +// documents — so a document may legitimately resolve to a KB not in the search set. +type dbDocTenantResolver struct{} + +func (dbDocTenantResolver) ResolveDocTenants(ctx context.Context, docIDs []string) (map[string]harness.DocTenant, error) { + if len(docIDs) == 0 || dao.DB == nil { + return nil, nil + } + var docs []struct { + ID string `gorm:"column:id"` + KbID string `gorm:"column:kb_id"` + } + if err := dao.DB.WithContext(ctx).Model(&entity.Document{}). + Where("id IN ?", docIDs).Select("id", "kb_id").Scan(&docs).Error; err != nil { + return nil, err + } + if len(docs) == 0 { + return nil, nil + } + kbIDs := make([]string, 0, len(docs)) + seen := make(map[string]bool, len(docs)) + for _, d := range docs { + if !seen[d.KbID] { + seen[d.KbID] = true + kbIDs = append(kbIDs, d.KbID) + } + } + var kbs []struct { + ID string `gorm:"column:id"` + TenantID string `gorm:"column:tenant_id"` + } + if err := dao.DB.WithContext(ctx).Model(&entity.Knowledgebase{}). + Where("id IN ?", kbIDs).Select("id", "tenant_id").Scan(&kbs).Error; err != nil { + return nil, err + } + tenantByKB := make(map[string]string, len(kbs)) + for _, k := range kbs { + tenantByKB[k.ID] = k.TenantID + } + out := make(map[string]harness.DocTenant, len(docs)) + for _, d := range docs { + out[d.ID] = harness.DocTenant{KBID: d.KbID, TenantID: tenantByKB[d.KbID]} + } + return out, nil +} + +func Rag(ctx context.Context, deps RAGTools, req harness.RunRequest) *RunResponse { + logger := deps.Logger + if logger == nil { + logger = _LOG + } + spec := harness.GetMode(req.ThinkingMode) + if !IsKnownMode(req.ThinkingMode) { + // An unrecognised label resolves to NAIVE; log it so a typo in the mode + // is visible instead of silently downgrading the request. + logger.Printf("[Agentic RAG] unrecognised thinking mode %q; falling back to naive (non-agentic) retrieval", req.ThinkingMode) + } + + // Python :266-267 — build the per-call usage counters and bind them to the + // context so every LLM call beneath is attributed to its phase. Without this + // the counting machinery is inert: CurrentStats(ctx) would stay nil and the + // phase markers already sprinkled through the graph would record nothing. + stats := deps.Stats + if stats == nil { + stats = harness.NewLLMUsageStats() + deps.Stats = stats + } + ctx = harness.WithStats(ctx, stats) + // Bind the caller's per-request progress sink (Python think_log counterpart) + // so engine stages and every search beneath can forward tagged lines to the + // live reasoning block. It flows through the whole RunAgenticRAG ctx lineage, + // which runSearch / CurrentProgress read. + if deps.Progress != nil { + ctx = harness.WithProgress(ctx, deps.Progress) + } + // Mirror Python think_log (rag/advanced_rag/think_log.py): rebuild the run's + // logger on top of the progress sink so every bracket-tagged stage line + // streams into the chat block. Python did this with a root + // logging.Handler; Go has no per-record hook on *log.Logger, so the same + // filtering happens at the writer instead. This logger is threaded into + // SearchDeps below and into every graph node by RunAgenticRAG, so one wrap + // here covers the whole pipeline without touching individual call sites. + if deps.Progress != nil { + logger = thinkLogger(logger, deps.Progress) + } + // Python :267 wraps the chat model in CountingChatModel(chat_mdl.clone(), + // self.llm_stats). Go wraps the session model's invoker the same way, so + // calls made through deps.Model are counted per phase too. + if wrapped, ok := wrapModelForStats(deps.Model, stats); ok { + deps.Model = wrapped + } + defer stats.Log(logger) + + // Python :831 — tell the caller research is starting, before any retrieval + // work, so it can show progress for the (potentially long) graph run. + if deps.ToolStarted != nil { + deps.ToolStarted() + } + + // Python dialog_service.rag_agent: when an outer chat model is wired + // (RAGTools.chat_mdl), the request is driven by the outer react loop that + // binds [rag, summarize_document] and treats `rag` as a terminal tool — + // mirroring chat_mdl.async_chat_with_tools(tools=rag_tools.tools, + // terminal_tools={"rag"}). The inner graph runs only when the model decides + // to call `rag`; otherwise the model answers directly (or calls + // summarize_document to read a whole document first). When no outer model is + // configured, or the outer model cannot emit tool calls (mirroring Python + // dialog_service.rag_agent's `if not chat_mdl.is_tools` fallback to + // async_chat), we fall through to the existing direct RunAgenticRAG path so + // behaviour is unchanged for every current caller. + // Mirror Python dialog_service.rag_agent: the last user message + // carries the question, text attachments, and — for vision models — image + // content blocks. In Go these reach the outer react loop's history + // (prepareOuterReact) so a vision model actually sees the images instead of + // silently dropping them. Assembled here (not in the caller) so the + // multimodal construction stays in the advanced_rag package beside the + // schema import. + if len(deps.Messages) == 0 { + deps.Messages = multimodalUserMessage(req.Question, req.TextAttachments, req.Images) + } + // Text attachments also feed the direct (non-outer) path, which appends them + // to the question (Python text_attachments_content handling); attachments + // bypass the near-duplicate cache (see cacheable above). + if deps.TextAttachments == "" { + deps.TextAttachments = req.TextAttachments + } + + // Build the per-request RAGCache up-front so the outer react loop (below) + // reuses the SAME cache across its multiple rag() calls within one turn. + // Keeping deps.Cache non-nil here is what makes the _consecutive_unanswerable + // guard (Python rag:921-924) live: ConsecutiveUnanswerable is incremented + // inside RunAgenticRAG and gated on deps.Cache != nil, so without a shared + // cache the outer loop would never reach the "STOP calling rag again" verdict. + // Python keeps the counter on the persistent RAGTools instance, which the + // outer loop naturally shares; Go mirrors that by setting deps.Cache before + // any branch rather than only on the direct path. + if deps.Cache == nil { + deps.Cache = NewRAGCache() + } + + if deps.Outer != nil && deps.OuterSupportsTools { + if deps.AnswerSink != nil { + return runOuterReactStream(ctx, deps, req, logger) + } + return runOuterReact(ctx, deps, req, logger) + } + + // Re-ask guard: reuse a near-identical question's cached answer instead of + // re-running the graph (Python rag:837-858). Attachments bypass it, since + // their content is appended to the question below and is not part of the key. + // Python keeps _rag_cache on the RAGTools instance, which is rebuilt for + // every turn, so the cache is per-turn by construction. Go mirrors that + // Go mirrors Python's default-on caching: deps.Cache is guaranteed non-nil + // here (built above, before the outer-react branch, so it is shared across + // the outer loop's multiple rag() calls). Python keeps _rag_cache on the + // RAGTools instance, which is rebuilt for every turn, so the cache is + // per-turn by construction. The auto-built cache lives only for this call + // (the per-turn degenerate case, since the current reasoning path issues a + // single Rag() per turn), so it can never serve a stale cross-turn hit. A + // caller that wants to share one cache across multiple Rag() calls within a + // single turn (Python's concurrent tool_call case) injects the same + // *RAGCache via deps.Cache instead of relying on the auto-built one. + cache := deps.Cache + cacheable := deps.TextAttachments == "" + if cacheable && cache != nil { + if cached, hit := cache.Lookup(req.Question); hit { + logger.Printf("[Agentic RAG] cache hit — reused prior answer for near-identical question %q; skipped research", trunc(req.Question, 80)) + return &RunResponse{Answer: cached, Mode: spec} + } + } + + // Prefer the user's ORIGINAL, complete question over the outer rewrite + // (Python rag:865). The outer rewrite often drops the final target of a + // multi-hop question, and no later stage can recover it. + if deps.OriginalQuestion != "" { + if effective := resolveEffectiveQuestion(req.Question, deps.OriginalQuestion); effective != req.Question { + logger.Printf("[Agentic RAG] using original user question over outer rewrite (original=%q → rewrite=%q)", + trunc(deps.OriginalQuestion, 80), trunc(req.Question, 80)) + req.Question = effective + } + } + if deps.TextAttachments != "" { + req.Question += deps.TextAttachments + } + + tenantID := req.TenantID + if tenantID == "" { + tenantID = harness.TenantIDFromContext(ctx) + } + datasetIDs := req.DatasetIDs + + kb := &harness.Kbinfos{} + searchDeps := searchDepsFor(ctx, deps, req, datasetIDs, tenantID, kb, logger) + + resp := &RunResponse{Mode: spec, Kbinfos: kb} + + // Python :877 — hand over to the graph driver, which owns the mode dispatch + // (agentic graph vs. direct/naive retrieval) and formalization. + // + // The terminal composition is handed to the graph instead of being run here: + // Python composes inside the last node of both graphs (agentic + // formalize_answer, low formalize_answer). The closure is + // idempotent so the post-graph call below is a no-op once the graph has + // composed — a graph that never reaches its last node (or the naive path, + // which Python composes under naiveAnswerSystem instead) still gets an + // answer here. + composed := false + compose := func(ctx context.Context) { + if composed { + return + } + composed = true + composeFinalAnswer(ctx, deps, req, kb, resp, logger) + } + deps.Finalize = compose + + RunAgenticRAG(ctx, deps, req, searchDeps, kb, resp, logger, spec) + + resp.Chunks = kb.Chunks + resp.DocAggs = kb.DocAggs + resp.EmptyResult = len(kb.Chunks) == 0 + + // Publish evidence for citation grounding. Best-effort: when no canvas + // state is attached (e.g. unit tests), skip silently — mirroring + // RetrievalTool's behaviour. + if len(kb.Chunks) > 0 { + harness.PublishReferences(ctx, kb) + } + + // The graph's last node composed already (see compose above); this only + // catches runs that never reached it. The naive path (_naive_rag) + // already composed under naiveAnswerSystem from flat "[i] content" + // evidence, so composing here would replace that with the + // FinalAnswerSystem / kb_prompt answer. + if spec.Label != "naive" { + compose(ctx) + } + + // Python rag (:902-929) appends a "[Research status]" note for EVERY + // non-SUFFICIENT verdict. When research has stayed unsatisfying for two + // consecutive turns it tells the outer agent to STOP calling rag again; + // otherwise it invites a focused re-ask. The counter lives on the + // conversation-scoped cache; it was incremented back in NewAgenticLoop once + // the SCA verdict was known. Skip the naive/sufficient paths: an empty + // answer or a SUFFICIENT verdict has nothing to annotate. + if t := researchStatusTrailer(deps.Cache, resp); t != "" { + resp.Answer += "\n\n[Research status] " + resp.SCAFeedback + t + } + + // Cache the freshly produced answer for later near-identical questions, and + // remember the verdict so a following re-ask is not answered from an + // admittedly incomplete one (Python rag:888-889 and :848-852). + if cacheable && cache != nil { + cache.Store(req.Question, resp.Answer) + cache.noteVerdict(resp.Verdict) + } + return resp +} + +// composeFinalAnswer runs the graph's terminal node and writes the result onto +// the response. +// +// When no model is configured this is a no-op: the caller still receives the +// evidence and can answer with it, matching Python's behaviour of returning an +// empty kbinfos rather than failing. +func composeFinalAnswer(ctx context.Context, deps RAGTools, req harness.RunRequest, kb *harness.Kbinfos, resp *RunResponse, logger *log.Logger) { + if deps.Model == nil { + return + } + // Python tags the terminal node @in_phase("finalize") + // (formalize_answer); without it every call made here is + // attributed to "unknown" in the usage table. + ctx, done := harness.Phase(ctx, harness.PhaseFinalize) + defer done() + if deps.ComposeAnswer != nil && !*deps.ComposeAnswer { + return + } + adeps := AnswerDeps{ + Model: deps.Model, + CiteRules: deps.CiteRules, + SystemPrompt: deps.SystemPrompt, + EmptyResponse: deps.EmptyResponse, + MaxTokens: deps.EvidenceMaxTokens, + MaxLength: deps.MaxLength, + Logger: logger, + // UserImages mirrors Python's direct async_chat fallback receiving the + // original multimodal messages: the non-outer compose model sees the + // vision-gated images too. The outer react path clears these in the rag + // terminal tool (Python inner _compose_answer_from_evidence is text-only). + UserImages: req.Images, + } + // Stream the answer when the model and the caller both support it, so the + // user sees text while it is produced instead of only at the end. + if deps.AnswerSink != nil { + if streamer, ok := deps.Model.(harness.StreamingSessionModel); ok { + deps.AnswerSink.reset() + streamed, err := ComposeAnswerStream(ctx, adeps, streamer, kb, req.Question, resp.Partial, func(delta string, isThink bool) error { + deps.AnswerSink.deliver(delta, isThink) + return nil + }) + if err == nil { + resp.Answer = streamed.Answer + if streamed.Partial { + resp.Partial = true + } + return + } + // A partially streamed answer must not be sent twice: tell the sink + // to drop what it already forwarded and fall back to one shot. + logger.Printf("[Agentic RAG] streaming compose failed (%v); falling back to a single call", err) + deps.AnswerSink.reset() + } + } + // No manual RecordCall here: the call is attributed to the "finalize" phase + // by the wrapped invoker above (Python relies on @in_phase alone). + // empty_result is Python's third no-evidence term (_compose_answer_from_evidence) — the loop's own + // "nothing was found" signal, distinct from abstain and from an empty pool. + res := ComposeAnswerWith(ctx, adeps, kb, req.Question, resp.Partial, false, resp.EmptyResult) + if deps.Stats != nil && res.Failed { + deps.Stats.RecordFailed(harness.PhaseFinalize) + } + resp.Answer = res.Answer + if res.Partial { + resp.Partial = true + } + if deps.AnswerSink != nil { + deps.AnswerSink.deliver(res.Answer, false) + } +} + +// outerReactParts holds the pieces shared by the streaming and non-streaming +// outer react loops (Python rag_agent's agent_messages + rag_tools.tools). +type outerReactParts struct { + kb *harness.Kbinfos + sd harness.SearchDeps + spec harness.ModeSpec + resp *RunResponse + tools []map[string]any + history []models.Message + system string +} + +// multimodalUserMessage mirrors Python dialog_service.rag_agent's assembly of +// agent_messages[-1]: a user turn whose text is the question plus any text +// attachments, augmented with image content blocks for vision-capable models. +// imageFiles are vision-gated base64 data URIs (data:...); textAttachments is +// joined file content. When there is nothing to carry (no question, no +// attachments, no images) it returns an empty slice so callers can skip it. +// +// The multimodal part list is used ONLY when images are attached, mirroring +// Python dialog_service.rag_agent: the text (question + +// attachments) stays a plain string, and the message is converted to content +// blocks just for image attachments. Sending a content-block array for a +// text-only question is not harmless — text-only providers silently drop it +// (Zhipu GLM answers an empty user turn with "Hello! How can I assist you +// today?" instead of calling the `rag` tool), and Python explicitly avoids it +// for that reason. +func multimodalUserMessage(question, textAttachments string, imageFiles []string) []schema.Message { + text := question + if textAttachments != "" { + if text != "" { + text = text + "\n\n" + textAttachments + } else { + text = textAttachments + } + } + if len(imageFiles) == 0 { + if text == "" { + return nil + } + return []schema.Message{{Role: schema.User, Content: text}} + } + parts := make([]schema.MessageInputPart, 0, 1+len(imageFiles)) + if text != "" { + parts = append(parts, schema.MessageInputPart{Type: schema.ChatMessagePartTypeText, Text: text}) + } + for i := range imageFiles { + uri := imageFiles[i] + parts = append(parts, schema.MessageInputPart{ + Type: schema.ChatMessagePartTypeImageURL, + Image: &schema.MessageInputImage{MessagePartCommon: schema.MessagePartCommon{URL: &uri}}, + }) + } + if len(parts) == 0 { + return nil + } + return []schema.Message{{Role: schema.User, UserInputMultiContent: parts}} +} + +// multimodalContentBlocks converts schema.MessageInputPart multimodal content +// into the OpenAI-style []interface{} block slice entity/models.Message.Content +// expects (mirroring entity/models toInternalMessages). Plain text Content is +// kept as a leading text block so the model sees both the original text and the +// multimodal parts. +func multimodalContentBlocks(m schema.Message) interface{} { + blocks := make([]interface{}, 0, 1+len(m.UserInputMultiContent)) + if m.Content != "" { + blocks = append(blocks, map[string]interface{}{"type": "text", "text": m.Content}) + } + for _, part := range m.UserInputMultiContent { + switch part.Type { + case schema.ChatMessagePartTypeText: + if part.Text != "" { + blocks = append(blocks, map[string]interface{}{"type": "text", "text": part.Text}) + } + case schema.ChatMessagePartTypeImageURL: + if part.Image != nil && part.Image.URL != nil { + blocks = append(blocks, map[string]interface{}{ + "type": "image_url", + "image_url": map[string]interface{}{"url": *part.Image.URL}, + }) + } + } + } + return blocks +} + +// prepareOuterReact builds the state both outer react loops need: the evidence set, +// the search deps, the two tool definitions and the outer conversation history +// rendered as models.Message. +func prepareOuterReact(ctx context.Context, deps RAGTools, req harness.RunRequest, logger *log.Logger) *outerReactParts { + tenantID := req.TenantID + if tenantID == "" { + tenantID = harness.TenantIDFromContext(ctx) + } + kb := &harness.Kbinfos{} + sd := searchDepsFor(ctx, deps, req, req.DatasetIDs, tenantID, kb, logger) + spec := harness.GetMode(req.ThinkingMode) + + tools := []map[string]any{ + { + "type": "function", + "function": map[string]any{ + "name": "rag", + "description": "Run the full agentic research graph over the configured datasets and return a cited answer.", + "parameters": map[string]any{ + "type": "object", + "properties": map[string]any{ + "question": map[string]any{ + "type": "string", + "description": "The research question to investigate.", + }, + }, + "required": []string{"question"}, + }, + }, + }, + { + "type": "function", + "function": map[string]any{ + "name": "summarize_document", + "description": "Read an entire document by id into the evidence set and return a short summary the model can answer from.", + "parameters": map[string]any{ + "type": "object", + "properties": map[string]any{ + "doc_id": map[string]any{ + "type": "string", + "description": "The document id to read.", + }, + }, + "required": []string{"doc_id"}, + }, + }, + }, + } + + history := make([]models.Message, 0, len(deps.Messages)) + for _, m := range deps.Messages { + msg := models.Message{Role: string(m.Role), Content: m.Content} + if len(m.UserInputMultiContent) > 0 { + msg.Content = multimodalContentBlocks(m) + } + history = append(history, msg) + } + system := deps.SystemPrompt + if strings.TrimSpace(system) == "" { + system = "You are a research assistant. Use the tools provided to gather evidence and answer the user's question with citations where possible." + } + + return &outerReactParts{ + kb: kb, + sd: sd, + spec: spec, + resp: &RunResponse{Mode: spec, Kbinfos: kb}, + tools: tools, + history: history, + system: system, + } +} + +// outerStreamMux merges the outer model's stream with the inner rag stream into +// one sink, mirroring Python rag_agent's event-queue state machine +// (dialog_service.py:2212-2274): the outer model's reasoning, the inner +// research log and the inner answer all share a single think/answer block. +// +// The models layer hands the outer stream down as (delta, reason) text that may +// carry literal / markers, while the sink takes an explicit +// isThink flag; the mux tracks the markers to keep the state and forwards plain +// text only. +type outerStreamMux struct { + mu sync.Mutex + sink *AnswerSink + inThink bool + terminalFired bool + // outerText accumulates the outer model's OWN non-think text. Python + // rag_agent treats a tool-less reply as the answer, so the streaming loop + // must be able to hand it back to the caller instead of dropping it (the + // inner `rag` stream arrives through deliver, never through here). + outerText strings.Builder +} + +// sender is the (delta, reason) callback handed to ChatStreamlyWithTools. +func (m *outerStreamMux) sender(delta, reason *string) error { + var text string + if delta != nil { + text = *delta + } + if reason != nil && *reason != "" { + text += *reason + } + if text == "" { + return nil + } + m.mu.Lock() + defer m.mu.Unlock() + for text != "" { + if strings.HasPrefix(text, "") { + m.inThink = true + text = text[len(""):] + continue + } + if strings.HasPrefix(text, "") { + m.inThink = false + text = text[len(""):] + continue + } + next := len(text) + if i := strings.Index(text, ""); i >= 0 && i < next { + next = i + } + if i := strings.Index(text, ""); i >= 0 && i < next { + next = i + } + chunk := text[:next] + text = text[next:] + if chunk == "" { + continue + } + // Python drops non-think outer text once the terminal tool has fired: + // what follows is the aggregate tool result, and the answer has already + // been streamed from inside the tool. + if m.terminalFired && !m.inThink { + continue + } + if !m.inThink { + m.outerText.WriteString(chunk) + } + m.emit(chunk, m.inThink) + } + return nil +} + +// deliver is the inner-stream entry point: research progress (isThink) and the +// composed answer (not think). +func (m *outerStreamMux) deliver(delta string, isThink bool) { + if delta == "" { + return + } + m.mu.Lock() + defer m.mu.Unlock() + m.inThink = isThink + m.emit(delta, isThink) +} + +// markTerminal records that the terminal `rag` tool ran, so later outer text is +// treated as the aggregate tool result and dropped (Python outer_tool_started). +func (m *outerStreamMux) markTerminal() { + m.mu.Lock() + defer m.mu.Unlock() + m.terminalFired = true +} + +// emit forwards one chunk. Caller must hold m.mu. +func (m *outerStreamMux) emit(chunk string, isThink bool) { + if m.sink == nil || m.sink.OnDelta == nil { + return + } + m.sink.OnDelta(chunk, isThink) +} + +// runOuterReact drives the Python-style rag_agent outer loop (Python +// dialog_service.rag_agent + RAGTools.tools=[rag, summarize_document] under +// chat_mdl.async_chat_with_tools with terminal_tools={"rag"}). The outer chat +// model decides whether to: +// - call `rag` (terminal): run the full inner agentic graph and return the +// cited answer, which the terminal short-circuit turns into the final answer; +// - call `summarize_document` (non-terminal): read a whole document into the +// evidence set and let the model answer from it on the next round; +// - answer directly with no tool call. +// +// deps.Outer must be non-nil; Rag() only delegates here when it is set, so +// existing callers that don't wire an outer model keep using the direct +// RunAgenticRAG path unchanged. +func runOuterReact(ctx context.Context, deps RAGTools, req harness.RunRequest, logger *log.Logger) *RunResponse { + p := prepareOuterReact(ctx, deps, req, logger) + + session := &outerReactSession{ + ctx: ctx, + deps: deps, + req: req, + sd: p.sd, + kb: p.kb, + resp: p.resp, + logger: logger, + spec: p.spec, + } + + outer := deps.Outer + outer.BindTools(session, p.tools) + outer.SetTerminalTools("rag") + + answer, _, err := outer.ChatWithTools(ctx, p.system, p.history, &models.ChatConfig{}) + if err != nil { + logger.Printf("[Agentic RAG] outer react failed: %v; falling back to direct graph", err) + // Fall back to the inner graph directly so the user still gets an answer. + RunAgenticRAG(ctx, deps, req, p.sd, p.kb, p.resp, logger, p.spec) + composeFinalAnswer(ctx, deps, req, p.kb, p.resp, logger) + return p.resp + } + p.resp.Answer = answer + p.resp.Chunks = p.kb.Chunks + p.resp.DocAggs = p.kb.DocAggs + p.resp.EmptyResult = len(p.kb.Chunks) == 0 + return p.resp +} + +// runOuterReactStream is the streaming counterpart of runOuterReact: it drives +// the same [rag, summarize_document] react loop but merges two live streams +// into the single sink the caller supplied, mirroring Python rag_agent's +// event-queue state machine (dialog_service.py:2212-2274): +// - the outer model's own reasoning/text, arriving through the models layer; +// - the inner rag run's research log (think) and composed answer (answer), +// produced while the terminal `rag` tool executes. +// +// `rag` streams its answer itself and returns "", so the terminal short-circuit +// stops the loop without re-streaming it (Python ignores the terminal result +// once the inner answer_sink has streamed). +func runOuterReactStream(ctx context.Context, deps RAGTools, req harness.RunRequest, logger *log.Logger) *RunResponse { + p := prepareOuterReact(ctx, deps, req, logger) + mux := &outerStreamMux{sink: deps.AnswerSink} + + // Route the inner run's progress and answer through the mux so they share + // one think/answer block with the outer model's stream. + inner := deps + // Same separator as thinkWriter: the block is HTML, so "\n" would collapse. + inner.Progress = func(line string) { mux.deliver(line+ThinkLineBreak, true) } + inner.AnswerSink = &AnswerSink{OnDelta: func(delta string, isThink bool) { mux.deliver(delta, isThink) }} + + session := &outerReactSession{ + ctx: ctx, + deps: inner, + req: req, + sd: p.sd, + kb: p.kb, + resp: p.resp, + logger: logger, + spec: p.spec, + mux: mux, + } + + outer := deps.Outer + outer.BindTools(session, p.tools) + outer.SetTerminalTools("rag") + + stream := true + _, err := outer.ChatStreamlyWithTools(ctx, p.system, p.history, &models.ChatConfig{Stream: &stream}, mux.sender) + if err != nil { + logger.Printf("[Agentic RAG] outer react stream failed: %v; falling back to direct graph", err) + // Fall back with the caller's own sink so the answer still streams out. + RunAgenticRAG(ctx, deps, req, p.sd, p.kb, p.resp, logger, p.spec) + composeFinalAnswer(ctx, deps, req, p.kb, p.resp, logger) + return p.resp + } + // A tool-less reply is the answer (Python rag_agent returns the model's + // text verbatim when it decides not to call a tool). The stream already + // delivered it to the caller's sink; recording it on the response is what + // lets the chat pipeline short-circuit instead of composing a second, + // contradicting answer from the (empty) evidence set. When the terminal + // `rag` tool fired, composeFinalAnswer already owns resp.Answer. + if p.resp.Answer == "" && !mux.terminalFired { + p.resp.Answer = strings.TrimSpace(mux.outerText.String()) + } + p.resp.Chunks = p.kb.Chunks + p.resp.DocAggs = p.kb.DocAggs + p.resp.EmptyResult = len(p.kb.Chunks) == 0 + return p.resp +} + +// outerReactSession implements models.ToolCallSession for the outer react loop. +type outerReactSession struct { + ctx context.Context + deps RAGTools + req harness.RunRequest + sd harness.SearchDeps + kb *harness.Kbinfos + resp *RunResponse + logger *log.Logger + spec harness.ModeSpec + // mux is set only on the streaming path; it merges the inner run's output + // into the caller's sink. + mux *outerStreamMux +} + +// ToolCall routes the two outer tools to their Go implementations. +func (s *outerReactSession) ToolCall(name string, arguments map[string]interface{}) (string, error) { + switch name { + case "rag": + if q, ok := arguments["question"].(string); ok && q != "" { + s.req.Question = q + } + // Python's inner _compose_answer_from_evidence is text-only: the outer + // model already saw the images via multimodal history, and the rephrased + // question carries no images. Drop the original images so the inner + // compose model (ComposeAnswerWith via composeFinalAnswer) does not + // receive them — matching Python's inner compose. + s.req.Images = nil + if s.mux != nil { + // Streaming: s.deps already routes the inner research log and the + // composed answer into the caller's sink, so return "" — the + // terminal short-circuit stops the loop and sendTerminal stays + // silent, so the answer is not streamed twice. + s.mux.markTerminal() + RunAgenticRAG(s.ctx, s.deps, s.req, s.sd, s.kb, s.resp, s.logger, s.spec) + composeFinalAnswer(s.ctx, s.deps, s.req, s.kb, s.resp, s.logger) + return "", nil + } + // Non-streaming: disable the sink so the answer is not emitted twice, + // and hand it back for the terminal short-circuit to return as final. + inner := s.deps + inner.AnswerSink = nil + RunAgenticRAG(s.ctx, inner, s.req, s.sd, s.kb, s.resp, s.logger, s.spec) + composeFinalAnswer(s.ctx, inner, s.req, s.kb, s.resp, s.logger) + return s.resp.Answer, nil + case "summarize_document": + docID, _ := arguments["doc_id"].(string) + if docID == "" { + return "Error: missing doc_id argument.", nil + } + blocks := harness.SummarizeDocument(s.ctx, s.sd, docID, s.deps.EvidenceMaxTokens) + if len(blocks) == 0 { + return "The document is unavailable or has no readable chunks.", nil + } + return strings.Join(blocks, "\n\n"), nil + } + return fmt.Sprintf("unknown tool %q", name), nil +} + +// runDirect is the low/naive path: one hybrid search, no tool loop. +// +// It is the ONE Go implementation of Python orchestrator/direct.py::direct_search +// (called from the low graph node) — there is deliberately no harness-level +// duplicate in harness/orchestrator. It lives here rather than there because the +// step reads the full RAGTools config; the graph node that calls it forces +// UseCompiled=true, which Python's direct_search hardcodes. +func runDirect(ctx context.Context, deps RAGTools, req harness.RunRequest, sd harness.SearchDeps, kb *harness.Kbinfos, resp *RunResponse, logger *log.Logger) { + ctx, done := harness.Phase(ctx, harness.PhaseDirect) + retrievalQuery := "" + if deps.Keywords != nil { + rq, err := deps.Keywords(ctx, req.Question) + if err != nil { + logger.Printf("[Agentic RAG] weighted keyword extraction failed: %v", err) + } else { + retrievalQuery = rq + } + } else if deps.Model != nil { + // Default: the four-aspect weighted extraction (Python + // tools.extract_keywords / harness/keywords.py). It gives BM25 both the + // discriminating entity and the surface variants the corpus may use. + rq, kw := harness.ExtractWeightedKeywords(ctx, deps.Model, req.Question) + retrievalQuery = rq + if req.Keywords == "" { + req.Keywords = kw + } + } + defer done() + + chunks, aggs := harness.HybridSearch(ctx, sd, harness.SearchParams{ + Question: req.Question, + Keywords: req.Keywords, + RetrievalQuery: retrievalQuery, + UseCompiled: req.UseCompiled, + TopN: req.TopN, + // Mirrors Python RAGTools.retrieve — the only function honouring + // using_embedding. + Channel: harness.ChannelRetrieve, + }) + kb.Merge(chunks, aggs) + if !kb.HasChunks() { + logger.Printf("[Agentic RAG] direct search found no matching passages") + } +} + +// AgenticLoop runs the full agentic search loop (planner / prefetch / SCA↔ +// rewriter iteration) for an agentic mode. +// +// It is registered by the advanced_rag package's init rather than called directly: the +// advanced_rag package owns RAGTools, so the harness cannot import it back. The +// indirection keeps the dependency graph acyclic. Registering is optional — see +// Run for the fallback when nothing is registered. +type AgenticLoop func(ctx context.Context, deps RAGTools, req harness.RunRequest, kb *harness.Kbinfos, resp *RunResponse, logger *log.Logger) + +var agenticLoop AgenticLoop + +// SetAgenticLoop registers the outer agentic loop. Called from the agent +// package's init(); importing that package (even blank) activates the full +// medium/high/ultra pipeline. Without it those modes degrade to a single action +// session. +func SetAgenticLoop(fn AgenticLoop) { agenticLoop = fn } + +// runAgentic drives medium/high/ultra. +// +// When an agentic loop is registered (see SetAgenticLoop) it runs the full +// five-phase pipeline: planner fan-out → slot table → slot research rounds → +// SCA review → gap rewrite → repeat until sufficient or the budget runs out. +// +// Fallback (no loop registered): ONE action session via RunActionSession. This +// keeps `Run` usable without the planner, at the cost of the +// planner/fan-out/SCA iteration. +func runAgentic(ctx context.Context, deps RAGTools, req harness.RunRequest, sd harness.SearchDeps, kb *harness.Kbinfos, resp *RunResponse, logger *log.Logger) { + // Formalization happens inside the graph: Python wires it as the + // build_agentic_graph entry node (add_edge(START, "formalize_question")). + if agenticLoop != nil { + agenticLoop(ctx, deps, req, kb, resp, logger) + return + } + if deps.Model == nil { + logger.Printf("[Agentic RAG] no model configured for mode %q; degrading to a direct search", resp.Mode.Label) + runDirect(ctx, deps, req, sd, kb, resp, logger) + return + } + runSingleSession(ctx, deps, req, sd, kb, resp, logger) +} + +// runSingleSession is the fallback agentic path: seed a slot table and run ONE +// bounded action session against it. +func runSingleSession(ctx context.Context, deps RAGTools, req harness.RunRequest, sd harness.SearchDeps, kb *harness.Kbinfos, resp *RunResponse, logger *log.Logger) { + // Seed the slot table and run one bounded session against it. A fresh tool + // cache and query history per run: they exist to dedupe WITHIN a session, + // not across requests. + sd.WebSearch = deps.WebSearch + sd.CiteRules = deps.CiteRules + sessionDeps := harness.SessionDeps{ + Tools: &harness.Toolset{ + ThinkingMode: resp.Mode.Label, + // Provider gate, mirroring Python action_session.py:463: without a + // wired provider the tool is hidden rather than advertised dead. + HasWebSearch: resp.Mode.HasTool("web_search") && deps.WebSearch != nil, + DisabledTools: map[string]bool{}, + Exec: harness.NewSearchExecutor(sd, req), + }, + Model: deps.Model, + Prompts: deps.Prompts, + // Surface already-retrieved evidence into the action session seed so the + // ReAct loop fills slots from what it has instead of re-searching. + KB: kb, + } + + // run_agentic_rag — there is no whole-graph wall clock: research stays + // bounded by per-node timeouts, the routing guards and the recursion limit. + // The only budget is the one AgenticState carries (formalize_question), and it is + // set when the state is created, so formalization is not charged to it. + init := harness.InitializeState(ctx, sessionDeps, req.Question, nil, req.DeadlineLeft) + root := init.Root + + result := harness.RunActionSession(ctx, sessionDeps, req.Question, root, req.DeadlineLeft, "", nil, nil) + // run_agentic_rag — failure to run research is recorded separately from + // "research found nothing": the session yielded neither messages nor states, + // so nothing was produced at all. + if len(result.Messages) == 0 && len(result.NewStates) == 0 && result.FoundAnswer == nil { + resp.GraphFailed = true + logger.Printf("[Agentic RAG] graph execution produced nothing (mode=%q)", resp.Mode.Label) + } + + if result.FoundAnswer != nil { + resp.Answer = *result.FoundAnswer + } + // Report the deepest slot table the session produced: later states carry + // strictly more filled slots than the root. + if len(result.NewStates) > 0 { + best := result.NewStates[len(result.NewStates)-1] + resp.Slots = append(resp.Slots, best.State...) + } else { + resp.Slots = append(resp.Slots, root.State...) + } +} + +// IsKnownMode reports whether label names a configured thinking mode. +func IsKnownMode(label string) bool { + _, ok := harness.THINKING_MODES[strings.ToLower(strings.TrimSpace(label))] + return ok +} + +// DocIDLookup mirrors Python RAGTools._filter_known_doc_ids (agentic_rag.py:981): +// it resolves which of a candidate document id set exist within the given +// datasets. +// +// Like Python, it reads the document table directly; the harness package takes +// it through the harness.DocIDVerifier interface so the retrieval path stays +// free of a database dependency. +type DocIDLookup struct { + docs *dao.DocumentDAO +} + +// NewDocIDLookup returns the document-ownership check backed by the document +// table. +func NewDocIDLookup() *DocIDLookup { + return &DocIDLookup{docs: &dao.DocumentDAO{}} +} + +// KnownDocIDs implements harness.DocIDVerifier: it returns the subset of +// candidates that belong to datasetIDs. +func (l *DocIDLookup) KnownDocIDs(ctx context.Context, datasetIDs, candidates []string) (map[string]bool, error) { + if l == nil || l.docs == nil || len(candidates) == 0 || len(datasetIDs) == 0 { + return nil, nil + } + docs, err := l.docs.GetByIDs(ctx, dao.DB, candidates) + if err != nil { + return nil, err + } + allowed := make(map[string]bool, len(datasetIDs)) + for _, id := range datasetIDs { + allowed[id] = true + } + known := make(map[string]bool, len(docs)) + for _, d := range docs { + if d != nil && allowed[d.KbID] { + known[d.ID] = true + } + } + return known, nil +} + +// compile-time check: the lookup satisfies the harness seam. +var _ harness.DocIDVerifier = (*DocIDLookup)(nil) diff --git a/internal/rag/advanced_rag/agentic_rag_graph.go b/internal/rag/advanced_rag/agentic_rag_graph.go new file mode 100644 index 00000000000..5f117ae66a7 --- /dev/null +++ b/internal/rag/advanced_rag/agentic_rag_graph.go @@ -0,0 +1,3697 @@ +// +// 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. +// + +// Package advanced_rag is the outer agentic-search loop (medium / high / ultra). +// +// This file mirrors Python rag/advanced_rag/agentic_rag_graph.py — the +// five-phase pipeline that sits ABOVE the action session: +// +// formalize_question → [planner → prefetch] → rag_agent → draft → sca +// ├─ sufficient ──────────────────────────→ formalize_answer +// └─ insufficient → query_rewrite ────────→ rag_agent (next round) +// +// Python uses LangGraph; this uses Eino's compose.NewGraph, compiled in Pregel +// mode (the research loop is a cycle: sca → query_rewrite → rag_agent). The +// node bodies, routing predicates, and their ordering are ported verbatim — +// only the driver differs. Node-visit accounting stays in this file rather than +// the framework's, because Python's recursion_limit counts NODE VISITS (a +// research round costs three) and Eino counts run steps. +// +// The RAGTools-configured dependencies live in agentic_rag.go, which +// mirrors Python rag/advanced_rag/agentic_rag.py. This split replicates the +// Python layout: agentic_rag.py (RAGTools) is a sibling of agentic_rag_graph.py, +// and both sit at the same level as harness/. +package advanced_rag + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "log" + "reflect" + "regexp" + "sort" + "strconv" + "strings" + "sync" + "time" + "unicode" + + "github.com/cespare/xxhash/v2" + "github.com/cloudwego/eino/compose" + "github.com/cloudwego/eino/schema" + + "ragflow/internal/agent/chat" + "ragflow/internal/common" + "ragflow/internal/engine/redis" + "ragflow/internal/rag/advanced_rag/harness" + "ragflow/internal/rag/advanced_rag/harness/orchestrator" + "ragflow/internal/rag/prompts" +) + +// --------------------------------------------------------------------------- +// Global research budget & per-call timeouts (Python lines 75-81). +// +// The benchmark client cuts a request at 300s (read timeout). These bounds keep +// one question's WHOLE pipeline comfortably under that line: when the budget +// runs out the routing guards steer to synthesis with whatever evidence is on +// hand instead of starting another research round. +// --------------------------------------------------------------------------- + +var _LOG = common.StdLogger() + +const ( + TotalBudgetS = 180.0 // whole-graph wall-clock ceiling per question + MinRoundHeadroomS = 50.0 // need at least this much left to start a new round + PassTimeoutS = 120.0 // slot research pass wall-clock + PrefetchTimeoutS = 90.0 // programmatic fan-out fetch + DraftTimeoutS = 60.0 // fallback draft synthesis + SCATimeoutS = 60.0 // sufficient-context review call + RewriteTimeoutS = 45.0 // gap → query rewrite call + // SCAViewCap: 24 of 225 hid the answer-bearing table chunk from the SCA. + SCAViewCap = 60 + // MaxSnippetPool is the storage ceiling of the snippet pool across ALL + // rounds. Storage and REVIEW are decoupled: the SCA only reads a ranked + // view, so the pool may accumulate freely while prompts stay bounded. + MaxSnippetPool = 60 + // DrillReserve: slots kept free after the FIRST prefetch so the research + // executor can top up evidence. + DrillReserve = 12 + // FanoutTopN is the per-query result count for the programmatic fetch. + FanoutTopN = 8 + // FanoutTopNRewrite is the reduced count used after a rewrite round. + FanoutTopNRewrite = 6 + // MaxFanouts caps planner fan-outs (Python: [:5]). + MaxFanouts = 5 + // MaxSCAGaps caps gaps handed to the rewriter (Python: gaps[:8]). + MaxSCAGaps = 8 + // PoolHeadLines caps the evidence-pool summary shown to the rewriter + // (Python: chunks[:12]). + PoolHeadLines = 12 + + // Slot-table research constants (Python: asyncio.Semaphore(2), [:3], etc.). + slotSessionConcurrency = 2 + slotSessionsPerRound = 3 + slotFallbackClueChars = 160 + // draftCandidateChars caps a claim's draft text handed to the SCA + // (Python sca node: `(meta.get("candidate") or "")[:400]`). + draftCandidateChars = 400 + // draftClueTailChars / draftUnresolvedClueChars are the per-clue caps in the + // rendered draft (Python _render_slot_draft: 240 for a resolved slot's + // discovered-clue tail, 80 for an unresolved slot's question clues). + draftClueTailChars = 240 + draftUnresolvedClueChars = 80 +) + +// Verdict statuses. +const ( + VerdictSufficient = "SUFFICIENT" + VerdictInsufficient = "INSUFFICIENT" +) + +// --------------------------------------------------------------------------- +// Local text helpers (mirror the helpers Python defines in agentic_rag_graph.py +// before AgenticState: _snip / _safe_list / _is_poisoned / _view_terms / ...). +// --------------------------------------------------------------------------- + +var tokenPattern = regexp.MustCompile(`[A-Za-z0-9_]+`) + +// queryToTerms mirrors the harness keywords helper used by Python _view_terms: +// lowercase word tokens of length >= 3, de-duplicated, order preserved. +func queryToTerms(q string) []string { + if q == "" { + return nil + } + found := tokenPattern.FindAllString(strings.ToLower(q), -1) + out := make([]string, 0, len(found)) + seen := make(map[string]bool, len(found)) + for _, t := range found { + if len(t) < 3 || seen[t] { + continue + } + seen[t] = true + out = append(out, t) + } + return out +} + +// truncateRunes caps a string to n runes without breaking multi-byte chars. +func truncateRunes(s string, n int) string { + if n <= 0 { + return "" + } + r := []rune(s) + if len(r) <= n { + return s + } + return string(r[:n]) +} + +// dedupe preserves order and drops empty / repeated entries. +func dedupe(in []string) []string { + if len(in) == 0 { + return nil + } + seen := make(map[string]bool, len(in)) + out := make([]string, 0, len(in)) + for _, s := range in { + if s == "" || seen[s] { + continue + } + seen[s] = true + out = append(out, s) + } + return out +} + +// stringOf coerces an arbitrary JSON value to a string (Python str()). +func stringOf(v any) string { + switch x := v.(type) { + case nil: + return "" + case string: + return x + case fmt.Stringer: + return x.String() + default: + return fmt.Sprint(x) + } +} + +// asSliceOfAny coerces a JSON array value to []any (Python _safe_list, line 95). +// +// Python also guards against a coroutine reaching a state field under async +// concurrency; Go cannot hit that case, but isPoisoned covers the equivalents +// that equally must never reach a prompt (see its doc comment). +func asSliceOfAny(v any) []any { + if isPoisoned(v) { + _LOG.Printf("[StateGuard] dropping poisoned value of kind %s; treating as empty", + reflect.ValueOf(v).Kind()) + return nil + } + switch x := v.(type) { + case nil: + return nil + case []any: + return x + case []string: + out := make([]any, len(x)) + for i, s := range x { + out[i] = s + } + return out + case map[string]any: + out := make([]any, 0, len(x)) + for _, vv := range x { + out = append(out, vv) + } + return out + default: + return []any{v} + } +} + +// toIntStrict parses an int-like value (JSON numbers arrive as float64). +func toIntStrict(v any) (int, bool) { + switch x := v.(type) { + case int: + return x, true + case int64: + return int(x), true + case float64: + return int(x), true + case string: + var n int + if _, err := fmt.Sscanf(x, "%d", &n); err == nil { + return n, true + } + } + return 0, false +} + +// toFloat parses a numeric value. +func toFloat(v any) (float64, bool) { + switch x := v.(type) { + case float64: + return x, true + case int: + return float64(x), true + case int64: + return float64(x), true + case string: + var f float64 + if _, err := fmt.Sscanf(x, "%f", &f); err == nil { + return f, true + } + } + return 0, false +} + +// anyString reads a string field from a chunk-like map. +func anyString(v any) string { + switch x := v.(type) { + case nil: + return "" + case string: + return x + default: + return fmt.Sprint(x) + } +} + +// truncateEach caps every entry of a string slice. +func truncateEach(in []string, n int) []string { + if len(in) == 0 { + return nil + } + out := make([]string, len(in)) + for i, s := range in { + out[i] = truncateRunes(s, n) + } + return out +} + +// equalStringPtr reports whether two optional strings are equal. +func equalStringPtr(a, b *string) bool { + if a == nil || b == nil { + return a == b + } + return *a == *b +} + +// equalStrings reports set-equality (order-independent) of two string slices. +func equalStrings(a, b []string) bool { + if len(a) != len(b) { + return false + } + seen := make(map[string]int, len(a)) + for _, s := range a { + seen[s]++ + } + for _, s := range b { + if seen[s] == 0 { + return false + } + seen[s]-- + } + return true +} + +// isPoisoned mirrors Python _is_poisoned: true when a state value +// must be discarded before it poisons an LLM prompt. +// +// Python guards against coroutine objects leaking into graph-state fields under +// async concurrency. Go's type system makes that specific leak impossible, so +// this checks the Go equivalents that must never reach a prompt: channels and +// function values, neither of which renders as anything a model can read. +func isPoisoned(v any) bool { + if v == nil { + return false + } + switch reflect.ValueOf(v).Kind() { + case reflect.Chan, reflect.Func, reflect.UnsafePointer: + return true + } + return false +} + +// SelectSCAView mirrors Python _select_sca_view: rank the stored pool +// down to the SCA review view (storage ≠ review). +// +// Score = retrieval relevance + surface-term coverage + freshness bonus for +// chunks admitted in later rounds. Returns (view, identity) where identity is a +// stable hash of the selected chunk ids — the caller uses it to detect an +// unproductive round (same view twice despite new storage ⇒ nothing new). +func SelectSCAView(chunks []map[string]any, focusTerms []string) ([]map[string]any, string) { + terms := dedupe(focusTerms) + lowered := make([]string, 0, len(terms)) + for _, t := range terms { + if len(t) >= 3 { + lowered = append(lowered, strings.ToLower(t)) + } + } + type scored struct { + idx int + chunk map[string]any + score float64 + } + ranked := make([]scored, 0, len(chunks)) + for i, c := range chunks { + text := strings.ToLower(strings.Join([]string{ + anyString(c["content"]), anyString(c["content_with_weight"]), + anyString(c["title"]), anyString(c["question_toks"]), + }, " ")) + cov := 0 + for _, t := range lowered { + if strings.Contains(text, t) { + cov++ + } + } + covRatio := 0.5 + if len(lowered) > 0 { + covRatio = float64(cov) / float64(len(lowered)) + } + // _select_sca_view — `float(c.get("similarity") or c.get("score") or 0.0)`: + // a FALSY similarity (0.0 or missing) falls through to score, so this is + // not "first key present wins". + rel := 0.0 + if v, ok := toFloat(c["similarity"]); ok && v != 0 { + rel = v + } else if v, ok := toFloat(c["score"]); ok && v != 0 { + rel = v + } + fresh := min(float64(i)/20.0, 0.2) // late arrivals (gap-pursuit evidence) get seen + ranked = append(ranked, scored{i, c, rel*0.45 + min(covRatio, 1.0)*0.45 + fresh}) + } + sort.SliceStable(ranked, func(i, j int) bool { return ranked[i].score > ranked[j].score }) + limit := min(len(ranked), SCAViewCap) + view := make([]map[string]any, 0, limit) + ids := make([]string, 0, limit) + for _, r := range ranked[:limit] { + view = append(view, r.chunk) + ids = append(ids, harness.ChunkIDOf(r.chunk)) + } + sort.Strings(ids) + return view, joinHash(ids) +} + +// joinHash builds a stable identity from the selected chunk ids. Mirrors +// Python's `str(hash("|".join(sorted(ids))))` in spirit (a deterministic digest +// rather than Python's randomised-per-process hash). +func joinHash(ids []string) string { + return fmt.Sprintf("%x", strings.Join(ids, "|")) +} + +// ViewTerms mirrors Python _view_terms: terms describing what the SCA +// should look FOR this round. +func ViewTerms(st *AgenticState) []string { + if st == nil { + return nil + } + terms := queryToTerms(st.Question) + for _, q := range st.CurrentQueries { + terms = append(terms, queryToTerms(q)...) + } + return dedupe(terms) +} + +// RemainingS mirrors Python _remaining_s: seconds left in the global budget. +// Never negative. +func (s *AgenticState) RemainingS() float64 { + if s.Deadline.IsZero() { + return TotalBudgetS + } + d := time.Until(s.Deadline).Seconds() + if d < 0 { + return 0 + } + return d +} + +// bounded mirrors Python _bounded: run fn under a wall-clock bound. +// On expiry it logs and returns the zero value, so one slow step never stalls +// the whole question. A non-positive bound means "no bound". +// +// The pipeline nodes (prefetch / research pass / draft / SCA / rewrite) wrap +// their calls by hand instead of routing through this helper, because each +// needs to record per-node state on expiry (partial flags, round counters) — +// not merely fall back to a zero value. This helper covers the plain case and +// is the shape those hand-written guards shrink to once they stop needing the +// extra bookkeeping. +func bounded[T any](ctx context.Context, timeoutS float64, what string, fn func(context.Context) (T, error)) (T, error) { + var zero T + if timeoutS <= 0 { + return fn(ctx) + } + runCtx, cancel := context.WithTimeout(ctx, time.Duration(timeoutS*float64(time.Second))) + defer cancel() + out, err := fn(runCtx) + if errors.Is(err, context.DeadlineExceeded) { + _LOG.Printf("[Budget] %s exceeded %.0fs — moving on without it", what, timeoutS) + return zero, nil + } + return out, err +} + +// --------------------------------------------------------------------------- +// AgenticState — the outer loop's mutable state (Python AgenticState, line 177). +// +// Deliberately NOT mirrored: Python declares `fills_found` and `research_feedback` +// but never wires them — neither is appended to anywhere, so the "focus" injected +// from them is always empty. Carrying them here would add dead state for no +// behaviour. +// +// They are part of a wider upstream layer that was declared but never connected +// (`research_feedback`, `fills_found`, and the `verdict` dict's +// `missing_claims` / `hard_violations` / `agent_confidence` / `feedback` keys, +// which `agentic_rag.py:906-909` reads but nothing ever writes). Verify against +// the WRITE site, not the declaration, before re-adding any of them. +// --------------------------------------------------------------------------- + +type AgenticState struct { + // ── conversation input ── + // Messages is the conversation history the formalize_question node reads to + // resolve pronouns and ellipses (Python: messages). + Messages []schema.Message + Question string + Keywords string + + // ── evolving research state ── + Plan []string // planner fan-outs (Phase 1) + CurrentQueries []string // active research targets + SlotTable harness.State + SlotDraft string // slot-rendered fact draft fed to the SCA + CollectedAnswer string // non-terminal candidate for SCA validation + UnresolvedSlots []map[string]any + SlotEvidence map[string]SlotEvidence + KB *harness.Kbinfos + Draft string // intermediate fact-preserving draft (Phase 3 reviewee) + RagAnswer string + PartialAnswer bool + Abstain bool + EmptyResult bool + Verdict string // VerdictSufficient / VerdictInsufficient + SCA map[string]any + + // ── budgets & counters ── + MaxLoops int + Deadline time.Time // wall-clock expiry of the research budget + SearchRounds int // completed SCA→query_rewrite iterations + SCAViewID string // identity of the last SCA review view + Attempted []map[string]any + NoProgress bool +} + +// NewAgenticState builds the initial state. It does NOT arm the global budget: +// Python sets `deadline` inside the formalize_question node's return, so +// formalization is not charged to it. Mirroring that keeps the deadline's owner +// identical to Python's. +// +// maxLoops mirrors Python's max_loops. +func NewAgenticState(question, keywords string, maxLoops int, messages []schema.Message) *AgenticState { + if maxLoops <= 0 { + maxLoops = 3 + } + return &AgenticState{ + Question: question, + Keywords: keywords, + MaxLoops: maxLoops, + Messages: messages, + KB: &harness.Kbinfos{}, + EmptyResult: true, + } +} + +// --------------------------------------------------------------------------- +// Thinking-tag stream splitting (Python lines 223-292). +// --------------------------------------------------------------------------- + +// Thinking-tag delimiters (Python _THINK_OPEN / _THINK_CLOSE, lines 223-224). +const ( + thinkOpen = "" + thinkClose = "" +) + +// partialTagTail mirrors Python _partial_tag_tail: the length of the +// longest proper prefix of tag that s ends with — how much of a tag may still +// be arriving on the next stream delta. +func partialTagTail(s, tag string) int { + limit := len(s) + if max := len(tag) - 1; max < limit { + limit = max + } + for k := limit; k > 0; k-- { + if strings.HasSuffix(s, tag[:k]) { + return k + } + } + return 0 +} + +// ThinkChunk is one split-out piece of a model stream: either reasoning +// ("think") or user-visible text ("answer"). +type ThinkChunk struct { + Kind string // "think" | "answer" + Text string +} + +// SplitThinkStream mirrors Python _split_think_stream: split model +// deltas into "think" and "answer" text. +// +// Besides ordinary ... streams, some providers emit the opening +// tag only on the first reasoning delta and append to every +// subsequent delta, so an unmatched closing tag still marks the text before it +// as reasoning. +// +// Python is an async generator; Go returns a channel that is closed once deltas +// are drained or ctx is cancelled. +func SplitThinkStream(ctx context.Context, deltas <-chan string) <-chan ThinkChunk { + out := make(chan ThinkChunk) + go func() { + defer close(out) + var buf strings.Builder + inThink := false + + emit := func(kind, text string) bool { + if text == "" { + return true + } + select { + case out <- ThinkChunk{Kind: kind, Text: text}: + return true + case <-ctx.Done(): + return false + } + } + + for { + var token string + var ok bool + select { + case token, ok = <-deltas: + if !ok { + // Flush the tail, stripping any residual tag. + if rest := buf.String(); rest != "" { + rest = strings.ReplaceAll(rest, thinkOpen, "") + rest = strings.ReplaceAll(rest, thinkClose, "") + kind := "answer" + if inThink { + kind = "think" + } + emit(kind, rest) + } + return + } + case <-ctx.Done(): + return + } + + buf.WriteString(token) + s := buf.String() + + for s != "" { + if inThink { + closeIdx := strings.Index(s, thinkClose) + if closeIdx >= 0 { + if !emit("think", s[:closeIdx]) { + return + } + s = s[closeIdx+len(thinkClose):] + inThink = false + continue + } + if hold := partialTagTail(s, thinkClose); hold > 0 { + if !emit("think", s[:len(s)-hold]) { + return + } + s = s[len(s)-hold:] + } else { + if !emit("think", s) { + return + } + s = "" + } + break + } + + openIdx := strings.Index(s, thinkOpen) + closeIdx := strings.Index(s, thinkClose) + + if closeIdx >= 0 && (openIdx < 0 || closeIdx < openIdx) { + if !emit("think", s[:closeIdx]) { + return + } + s = s[closeIdx+len(thinkClose):] + continue + } + if openIdx >= 0 { + if !emit("answer", s[:openIdx]) { + return + } + s = s[openIdx+len(thinkOpen):] + inThink = true + continue + } + + hold := partialTagTail(s, thinkOpen) + if h := partialTagTail(s, thinkClose); h > hold { + hold = h + } + if hold > 0 { + if !emit("answer", s[:len(s)-hold]) { + return + } + s = s[len(s)-hold:] + } else { + if !emit("answer", s) { + return + } + s = "" + } + break + } + + buf.Reset() + buf.WriteString(s) + } + }() + return out +} + +// SCAGapsToRewrite mirrors Python _sca_gaps_to_rewrite. +// +// Preference order: +// 1. Unsatisfied sub_queries (the precise "what is missing / where to search +// next" signal from Q-CARE) — (missing_fact, search_hint). +// 2. Per-claim missing_information items — (what, search_hint). +// +// Returns [(what, search_hint), ...] (deduped, non-empty). +func SCAGapsToRewrite(sca map[string]any) []orchestrator.MissingPiece { + var gaps []orchestrator.MissingPiece + seen := map[string]bool{} + add := func(what, hint string) { + what = strings.TrimSpace(what) + hint = strings.TrimSpace(hint) + if what == "" && hint == "" { + return + } + key := what + "|" + hint + if seen[key] { + return + } + seen[key] = true + if what == "" { + what = hint + } + if hint == "" { + hint = what + } + gaps = append(gaps, orchestrator.MissingPiece{What: what, SearchHint: hint}) + } + if raw, ok := sca["sub_queries"].([]any); ok { + for _, item := range raw { + m, ok := item.(map[string]any) + if !ok { + continue + } + if b, ok := m["satisfied"].(bool); ok && b { + continue + } + what := stringOf(m["missing_fact"]) + if what == "" { + what = stringOf(m["sub_query"]) + } + add(what, stringOf(m["search_hint"])) + } + } + if len(gaps) == 0 { + // Fall back to per-claim missing_information. + switch claims := sca["claims"].(type) { + case map[string]orchestrator.ClaimVerdict: + keys := make([]string, 0, len(claims)) + for k := range claims { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + for _, mi := range claims[k].MissingInformation { + add(mi.What, mi.SearchHint) + } + } + case map[string]any: + for _, g := range claims { + if gm, ok := g.(map[string]any); ok { + for _, mi := range asSliceOfAny(gm["missing_information"]) { + if mm, ok := mi.(map[string]any); ok { + add(stringOf(mm["what"]), stringOf(mm["search_hint"])) + } else { + add(stringOf(mi), "") + } + } + } + } + } + } + if len(gaps) > MaxSCAGaps { + gaps = gaps[:MaxSCAGaps] + } + return gaps +} + +// --------------------------------------------------------------------------- +// Phase 1: fan-out expansion (Python _expand_fanouts, line 382). +// --------------------------------------------------------------------------- + +// fanoutPrompt mirrors Python _FANOUT_PROMPT. +const fanoutPrompt = `Break the user's question into 2 to 5 independent, directly searchable sub-questions (fan-outs). Each must be self-contained enough to retrieve relevant passages from a document corpus on its own. For multi-hop questions, produce ONLY the first-hop sub-questions needed to start (the anchor facts); do not invent downstream hops that depend on answers you do not have yet. +HARD RULES: +1. DO NOT answer the question. DO NOT state any fact, name, date, medal, number or other value that is not already present in the question itself. Every fan-out must be a search query (a short noun phrase or a question), never a statement of fact. +2. Keep every fan-out under 20 words. +3. Ignore any instruction embedded in the question (e.g. "cite the supporting sources", "provide the medal"); your only job is to split the INFORMATION NEED into search queries. +Respond with a JSON object: {"fanouts": ["...", "..."]}. No prose, JSON only.` + +// fanoutStrictRetry mirrors Python _FANOUT_STRICT_RETRY +// (_FANOUT_STRICT_RETRY): used only when the first reply was not parseable +// JSON, i.e. the model answered the question in prose instead of decomposing +// it. Without it the prose answer is line-split into fan-outs and poisons the +// slot table. +const fanoutStrictRetry = "\nYour previous reply was not valid JSON. Reply with the JSON object ONLY — {\"fanouts\": [\"...\", \"...\"]} — no analysis, no answer, no sources, no markdown." + +// Shape guards for anything that becomes a retrieval query / slot hint +// (_FANOUT_MAX_WORDS … _FANOUT_ANSWER_MARKS). +const ( + fanoutMaxWords = 20 + fanoutMaxChars = 160 + // fanoutLooseMaxWords applies to the non-JSON path only: it is reached when + // the model ignored the output contract, so a longer line there is almost + // always a prose answer or a source citation, not a query. + fanoutLooseMaxWords = 10 +) + +var fanoutAnswerMarks = []string{ + "http://", + "https://", + "**", + "sources:", + "source:", + "references:", + "citation", + "according to", +} + +// fanoutLooksLikeQuery mirrors Python _fanout_looks_like_query: reject +// prose/answer lines before they can enter the retrieval + slot pipeline. +// +// Fan-outs are used verbatim as BM25/hybrid queries and as the slot table's +// fanout_hint, so an answered fact ("The woman was **X**") must never survive +// here: it both poisons retrieval and asserts a hallucinated entity as a known +// aspect. +func fanoutLooksLikeQuery(line string, loose bool) bool { + s := strings.TrimSpace(line) + if s == "" { + return false + } + low := strings.ToLower(s) + for _, mark := range fanoutAnswerMarks { + if strings.Contains(low, mark) { + return false + } + } + if len(s) > fanoutMaxChars { + return false + } + words := len(strings.Fields(s)) + if loose && !strings.HasSuffix(s, "?") && words > fanoutLooseMaxWords { + return false + } + return words <= fanoutMaxWords +} + +// parseFanouts mirrors Python _parse_fanouts: extract fan-outs from a +// model reply, validating every entry's shape. +func parseFanouts(text string) []string { + var raw []string + loose := false + if data, ok := extractJSONObject(text).(map[string]any); ok { + for _, f := range asSliceOfAny(data["fanouts"]) { + if s := strings.TrimSpace(fmt.Sprint(f)); s != "" { + raw = append(raw, s) + } + } + } else { + // Loose fallback: the model answered in prose. Only lines that still + // look like a search query are kept — answer sentences and source + // lists are dropped. + loose = true + for _, ln := range strings.Split(text, "\n") { + ln = strings.TrimSpace(strings.TrimLeft(ln, "-•0123456789. ")) + if ln != "" { + raw = append(raw, ln) + } + } + } + kept := make([]string, 0, len(raw)) + for _, q := range raw { + if fanoutLooksLikeQuery(q, loose) { + kept = append(kept, q) + } + } + if len(raw) > 0 && len(kept) == 0 { + _LOG.Printf("[Planner] discarding %d fan-out candidate(s): none look like search queries", len(raw)) + } + kept = dedupe(kept) + if len(kept) > MaxFanouts { + kept = kept[:MaxFanouts] + } + return kept +} + +// extractJSONObject mirrors Python _extract_json_object: return the +// first parseable JSON object in text, or nil when none parses. +// +// The fan-out model sometimes emits prose around the object, and a greedy +// brace-match would capture several objects and fail with "extra data"; each +// candidate is therefore validated before it is accepted, and an invalid one +// resumes the scan at its next "{". +func extractJSONObject(text string) any { + for i := 0; i < len(text); { + rel := strings.IndexByte(text[i:], '{') + if rel < 0 { + return nil + } + start := i + rel + depth := 0 + scan: + for j := start; j < len(text); j++ { + switch text[j] { + case '{': + depth++ + case '}': + depth-- + if depth == 0 { + var out map[string]any + if json.Unmarshal([]byte(text[start:j+1]), &out) == nil { + return out + } + break scan // not a valid object; try the next "{" + } + } + } + i = start + 1 + } + return nil +} + +// ExpandFanouts mirrors Python _expand_fanouts: ONE chat call (no +// tools) producing 2-5 first-hop fan-outs, plus one strict retry when the +// reply was not parseable JSON (_expand_fanouts). +// +// Falls back to the raw question alone on any failure — a fan-out failure never +// blocks the pipeline. +func ExpandFanouts(ctx context.Context, deps RAGTools, question string) []string { + if question == "" { + return nil + } + if deps.Model == nil { + return []string{question} + } + reply, err := deps.Model.Complete(ctx, []schema.Message{ + *schema.SystemMessage(fanoutPrompt), + *schema.UserMessage("Question: " + question), + }, nil) + if err != nil { + _LOG.Printf("[Planner] fan-out expansion failed; falling back to raw question: %v", err) + return []string{question} + } + fanouts := parseFanouts(reply.Content) + if len(fanouts) == 0 { + // The model answered the question instead of decomposing it (no JSON, + // or JSON that failed the shape guard). One strict retry, then give up. + _LOG.Printf("[Planner] fan-out expansion produced no usable sub-question; retrying with a strict JSON instruction") + if retry, rerr := deps.Model.Complete(ctx, []schema.Message{ + *schema.SystemMessage(fanoutPrompt + fanoutStrictRetry), + *schema.UserMessage("Question: " + question), + }, nil); rerr != nil { + _LOG.Printf("[Planner] strict fan-out retry failed: %v", rerr) + } else { + fanouts = parseFanouts(retry.Content) + } + } + if len(fanouts) == 0 { + fanouts = []string{question} + } + _LOG.Printf("[Planner] fan-out expansion: %d sub-question(s): %v", len(fanouts), fanouts) + return fanouts +} + +// --------------------------------------------------------------------------- +// Phase 2: programmatic fan-out search (Python _fanout_search, line 432). +// --------------------------------------------------------------------------- + +// Fanout search tuning . +const ( + // fanoutBM25TopN is the keyword-leg candidate pool (Python: [:60]). + fanoutBM25TopN = 60 + // fanoutHybridTopN is the semantic-leg candidate pool. + fanoutHybridTopN = 30 + // fanoutSemanticQuota caps narrow-BYPASS hits admitted per fan-out. + fanoutSemanticQuota = 4 + // Narrowing budget for the exact leg (Python narrow_by_terms kwargs). + fanoutNarrowMaxOutPerChunk = 1200 + fanoutNarrowMaxOutTotal = 16000 +) + +// FanoutSearch mirrors Python _fanout_search: the +// programmatic multi-query prefetch that seeds the snippet pool. +// +// It is a DUAL-CHANNEL search, and the two channels are deliberately different: +// +// - channel A (exact): a keyword BM25 round over a wide pool (top_n=60) whose +// hits are then narrowed by the query's own terms — the precision path. A +// chunk only survives if it literally contains a query term. +// - channel B (semantic bypass): a dense hybrid round (top_n=30) that +// deliberately SKIPS narrowing, so a paraphrase-only hit can still enter the +// pool. These are quarantined to a small per-fan-out quota +// (fanoutSemanticQuota) because bypassing narrowing is what makes them +// low-precision. +// +// Collapsing them into one call loses the split, and with it the ability to +// admit a paraphrase-only match without letting it displace an exact one. +// +// Admission order is the point: every fan-out's channel A is admitted before any +// fan-out's channel B, so an exact hit from a later fan-out outranks a semantic +// hit from an earlier one. +// +// Returns the number of NEW snippets admitted to the pool. +func FanoutSearch(ctx context.Context, deps RAGTools, st *AgenticState, queries []string, topN, capacity int) int { + if len(queries) == 0 || st.KB == nil { + return 0 + } + sd := deps.Search + if sd.Backend == nil { + return 0 + } + + // Python dedups against what kbinfos ALREADY holds, then caps admissions at + // the remaining room — the pool is a shared, cross-round ceiling. + seen := make(map[string]bool, len(st.KB.Chunks)) + for _, c := range st.KB.Chunks { + seen[harness.ChunkIDOf(c)] = true + } + maxTotal := capacity + if maxTotal <= 0 { + maxTotal = MaxSnippetPool + } + room := maxTotal - len(seen) + if room <= 0 { + return 0 + } + + // Python coerces the planner's output with _as_text_list; Go's []string is + // already that shape, but blank entries still have to be dropped. + qs := make([]string, 0, len(queries)) + for _, q := range queries { + if q = strings.TrimSpace(q); q != "" { + qs = append(qs, q) + } + } + if len(qs) == 0 { + return 0 + } + capPerQuery := topN + if capPerQuery < 1 { + capPerQuery = 1 + } + + // Python runs the fan-outs as parallel asyncio tasks, but each coroutine + // only RETRIEVES — kbinfos is mutated once, back in the caller. Go keeps + // that same "retrieve, then mutate once" structure, hence sequential: the + // per-request search cache and Kbinfos are shared mutable state that the + // Python coroutines never touch concurrently either. + type fanoutPair struct { + exact []map[string]any + semantic []map[string]any + } + pairs := make([]fanoutPair, 0, len(qs)) + for _, q := range qs { + select { + case <-ctx.Done(): + return 0 + default: + } + exact, semantic := fanoutSearchQuery(ctx, sd, q, capPerQuery) + pairs = append(pairs, fanoutPair{exact: exact, semantic: semantic}) + } + + added := 0 + admit := func(batch []map[string]any) bool { + for _, c := range batch { + if added >= room { + return true + } + id := harness.ChunkIDOf(c) + if id != "" { + if seen[id] { + continue + } + seen[id] = true + } + st.KB.Chunks = append(st.KB.Chunks, c) + added++ + } + return added >= room + } + // Channel A across every fan-out first, then channel B. + for _, p := range pairs { + if admit(p.exact) { + return added + } + } + for _, p := range pairs { + if admit(p.semantic) { + return added + } + } + return added +} + +// fanoutSearchQuery runs one fan-out's two channels. It only retrieves; the +// caller admits the results (Python's coroutine contract). +func fanoutSearchQuery(ctx context.Context, sd harness.SearchDeps, fq string, capPerQuery int) (exact, semantic []map[string]any) { + terms := harness.QueryToTerms(fq) + keyed := harness.FanoutKeyedTerms(terms) + termList := keyed + if len(termList) == 0 { + termList = terms + } + + // Channel A — exact: Python calls bm25_search, which is keyword-only + // (vector_similarity_weight=0). Go's BM25Search is the dedicated entry point. + candidates, _ := harness.BM25Search(ctx, sd, harness.SearchParams{ + Question: fq, + Keywords: strings.Join(termList, " "), + TopN: fanoutBM25TopN, + }) + if len(candidates) > 0 { + res := harness.NarrowByTerms(candidates, termList, nil, fq, + harness.NarrowContext{Before: 0, After: 1}, + fanoutNarrowMaxOutPerChunk, fanoutNarrowMaxOutTotal) + exact = res.Kept + if len(exact) > capPerQuery { + exact = exact[:capPerQuery] + } + } + + // Channel B — semantic bypass: Python calls hybrid_search, which gives the + // vector leg weight 0.3 whenever an embedder is configured. NO narrowing + // (a paraphrase-only hit has no query term to match, so narrowing would + // erase it). Go's HybridSearch is the dedicated entry point. + hits, _ := harness.HybridSearch(ctx, sd, harness.SearchParams{ + Question: fq, + TopN: fanoutHybridTopN, + }) + exactIDs := make(map[string]bool, len(exact)) + for _, c := range exact { + exactIDs[harness.ChunkIDOf(c)] = true + } + for _, c := range hits { + if exactIDs[harness.ChunkIDOf(c)] { + continue + } + semantic = append(semantic, c) + if len(semantic) >= fanoutSemanticQuota { + break + } + } + return exact, semantic +} + +// BuildLowGraph mirrors Python build_low_graph: the lightweight +// low-mode path — formalize → direct_search → answer — with no planner, no +// fan-out, and no SCA loop. +// +// Python compiles a LangGraph and run_agentic_rag invokes it. Go +// declares the same two nodes on Eino's compose.NewGraph and invokes the +// compiled runnable. The name follows Python's build_low_graph for traceability. +// +// The returned error mirrors Python's holder["error"]: run_agentic_rag +// wraps BOTH graphs in the same try/except, so a low-graph failure is reported +// the same way as an agentic one. +func BuildLowGraph(ctx context.Context, deps RAGTools, req harness.RunRequest, sd harness.SearchDeps, kb *harness.Kbinfos, resp *RunResponse, logger *log.Logger) error { + // The graph is declared per run: deps / sd / resp are request-scoped and Eino + // captures them in closures. Python does the same — run_agentic_rag calls + // build_low_graph per request — so this is parity, not an oversight. + g := compose.NewGraph[*harness.RunRequest, *harness.RunRequest]() + + var buildErr error + addNode := func(name string, fn func(context.Context, *harness.RunRequest) (*harness.RunRequest, error)) { + if buildErr != nil { + return + } + buildErr = g.AddLambdaNode(name, compose.InvokableLambda(fn)) + } + addEdge := func(from, to string) { + if buildErr != nil { + return + } + buildErr = g.AddEdge(from, to) + } + + // Node 1: formalize_question — rewrites req.Question/Keywords in place. + addNode("formalize_question", func(c context.Context, r *harness.RunRequest) (*harness.RunRequest, error) { + formalizeQuestion(c, deps, r, logger) + return r, nil + }) + // Node 2: direct_search (direct_search_node). + addNode("direct_search", func(c context.Context, r *harness.RunRequest) (*harness.RunRequest, error) { + // Python low mode's direct_search is orchestrator/direct.py, which calls + // hybrid_search(..., use_compiled=True) unconditionally. The RunRequest + // field only gates the L1 direct retrieve elsewhere, so it must not be + // able to turn expansion off here. + low := *r + low.UseCompiled = true + runDirect(c, deps, low, sd, kb, resp, logger) + return r, nil + }) + // Node 3: formalize_answer — Python's low graph ends with the + // composition node, so the answer is produced inside the graph. + addNode("formalize_answer", func(c context.Context, r *harness.RunRequest) (*harness.RunRequest, error) { + if deps.Finalize != nil { + deps.Finalize(c) + } + return r, nil + }) + + addEdge(compose.START, "formalize_question") + addEdge("formalize_question", "direct_search") + addEdge("direct_search", "formalize_answer") + addEdge("formalize_answer", compose.END) + + if buildErr != nil { + logger.Printf("[Low RAG] graph build failed: %v", buildErr) + return buildErr + } + + runnable, err := g.Compile(ctx, compose.WithGraphName("low_graph")) + if err != nil { + logger.Printf("[Low RAG] graph compile failed: %v", err) + return err + } + if _, err := runnable.Invoke(ctx, &req); err != nil { + logger.Printf("[Low RAG] graph run failed: %v", err) + return err + } + return nil +} + +// --------------------------------------------------------------------------- +// Routing +// --------------------------------------------------------------------------- + +type agenticNode int + +const ( + // nodeFormalizeQuestion is the graph's entry node (Python + // build_agentic_graph: `add_edge(START, "formalize_question")`). + nodeFormalizeQuestion agenticNode = iota + nodeFormalizeAnswer + nodeQueryRewrite + nodeRagAgentLoop + nodePlanner + nodePrefetch + nodeRagAgentFirst +) + +// plannerNode mirrors the `planner` node: decompose into fan-outs, +// then build the slot table from them. +func plannerNode(ctx context.Context, deps RAGTools, st *AgenticState, logger *log.Logger) { + ctx, done := harness.Phase(ctx, "planner") + defer done() + + logger.Printf("[Planner] Decomposing the question into first-hop fan-outs...") + fanouts := ExpandFanouts(ctx, deps, st.Question) + st.Plan = fanouts + st.CurrentQueries = append([]string(nil), fanouts...) + + // Build the slot table right after fan-out decomposition so the research + // pass is slot-directed (each slot = one unknown to resolve). + // + // planner — `lambda: _remaining_s(state) - 15.0`, NOT floored: once the + // budget is spent the value goes negative and initialize_state times out + // immediately, so the table falls back to the fan-outs instead of spending + // another 15s on a decomposition the round cannot afford. + sd := deps.sessionDeps() + root, firstQueries := BuildSlotTable(ctx, sd, st.Question, fanouts, st.RemainingS()-15.0) + st.SlotTable = root + if len(firstQueries) > 0 { + st.CurrentQueries = firstQueries + } +} + +// prefetchNode mirrors the `prefetch` node: programmatic fan-out +// retrieval into the snippet pool. +func prefetchNode(ctx context.Context, deps RAGTools, st *AgenticState, logger *log.Logger, firstRound bool) { + ctx, done := harness.Phase(ctx, "orchestrator") + defer done() + + queries := st.CurrentQueries + if len(queries) == 0 { + if st.Question == "" { + return + } + queries = []string{st.Question} + } + timeout := min(PrefetchTimeoutS, max(10.0, st.RemainingS()-MinRoundHeadroomS)) + callCtx, cancel := context.WithTimeout(ctx, time.Duration(timeout*float64(time.Second))) + defer cancel() + + capacity := MaxSnippetPool + if firstRound { + // First-round prefetch leaves drill slots free. + capacity = MaxSnippetPool - DrillReserve + } + added := FanoutSearch(callCtx, deps, st, queries, FanoutTopN, capacity) + for _, q := range queries { + st.Attempted = append(st.Attempted, map[string]any{"q": q, "r": 0, "new": added}) + } +} + +// ragAgentNode mirrors the `rag_agent` node: one slot research pass. +func ragAgentNode(ctx context.Context, deps RAGTools, st *AgenticState, logger *log.Logger) { + ctx, done := harness.Phase(ctx, "dynamic") + defer done() + + timeLeft := st.RemainingS() + if timeLeft < MinRoundHeadroomS { + logger.Printf("[RAGAgent] only %.0fs left of the research budget; skipping further passes.", timeLeft) + return + } + roundNo := st.SearchRounds + 1 + poolBefore := len(st.KB.Chunks) + logger.Printf("[RAGAgent] ROUND %d start (search_rounds=%d, time_left=%.0fs, pool=%d chunks)", + roundNo, st.SearchRounds, timeLeft, poolBefore) + + t := max(20.0, min(PassTimeoutS, timeLeft-25.0)) + callCtx, cancel := context.WithTimeout(ctx, time.Duration(t*float64(time.Second))) + defer cancel() + + res := RunSlotResearchPass(callCtx, deps.sessionDeps(), st.Question, st, t) + if res == nil { + return + } + st.SlotTable = res.SlotTable + st.CollectedAnswer = res.CollectedAnswer + st.UnresolvedSlots = res.UnresolvedSlots + st.SlotEvidence = res.SlotEvidence + st.SlotDraft = res.SlotDraft + // Python _run_slot_research_pass — `rag_answer = draft or + // (state.rag_answer or "")`: an empty draft keeps the PREVIOUS round's + // answer. Overwriting unconditionally (and the old self-assignment that + // followed it) cleared it instead, so the draft node fell back to + // synthesizing from snippets on the next round. + if res.SlotDraft != "" { + st.RagAnswer = res.SlotDraft + } + st.Attempted = res.Attempted + + logger.Printf("[RAGAgent] ROUND %d end (+%d new chunks, pool=%d, unresolved=%d)", + roundNo, len(st.KB.Chunks)-poolBefore, len(st.KB.Chunks), len(res.UnresolvedSlots)) +} + +// draftNode mirrors the `draft` node: the intermediate draft that the +// SCA reviews. +func draftNode(ctx context.Context, deps RAGTools, st *AgenticState, logger *log.Logger) { + ctx, done := harness.Phase(ctx, "draft") + defer done() + + draftText := strings.TrimSpace(st.RagAnswer) + if draftText == "" { + // Budget exhaustion without a report: synthesize one from snippets. + t := min(DraftTimeoutS, max(15.0, st.RemainingS()-10.0)) + callCtx, cancel := context.WithTimeout(ctx, time.Duration(t*float64(time.Second))) + draftText = ComposeFallbackDraft(callCtx, deps, st) + cancel() + } + if draftText != "" { + st.KB.PreSummary = draftText + } + st.Draft = draftText + logger.Printf("[Draft] intermediate draft %d chars (evidence=%d chunks)", len(draftText), len(st.KB.Chunks)) +} + +// scaNode mirrors the `sca` node: the Phase-3 quality-control review. +func scaNode(ctx context.Context, deps RAGTools, st *AgenticState, logger *log.Logger) { + ctx, done := harness.Phase(ctx, "sca") + defer done() + + chunks := st.KB.Chunks + view, viewID := SelectSCAView(chunks, ViewTerms(st)) + if st.SCAViewID != "" && viewID == st.SCAViewID { + // Same evidence review twice despite new storage — further rounds cannot + // change the verdict; stop instead of looping. + logger.Printf("[SCA] review view UNCHANGED since last round (%d stored / %d viewed); closing out.", len(chunks), len(view)) + st.Verdict = VerdictInsufficient + st.NoProgress = true + st.SCA = map[string]any{} + return + } + + draftText := strings.TrimSpace(st.Draft) + claims, grownView := buildSCAClaims(draftText, view, chunks, st.SlotEvidence) + // Review against the GROWN view (sca appends to the same list). + view = grownView + // sca — the only case that skips the review outright is + // "nothing retrieved AND nothing drafted". A non-empty view always reaches + // the SCA (its default claim indexes the whole view, see buildSCAClaims). + if draftText == "" && len(view) == 0 { + logger.Printf("[SCA] nothing retrieved nor drafted; marking INSUFFICIENT to trigger a targeted re-search.") + st.Verdict = VerdictInsufficient + st.SCA = map[string]any{} + st.SCAViewID = viewID + return + } + + // The SCA renders claim evidence from kbinfos BY INDEX, so review against a + // view-only copy — the indexed ids then point at exactly the selected + // chunks. The full pool is restored afterwards. + orig := st.KB.Chunks + st.KB.Chunks = view + defer func() { st.KB.Chunks = orig }() + + t := min(SCATimeoutS, max(15.0, st.RemainingS()-10.0)) + callCtx, cancel := context.WithTimeout(ctx, time.Duration(t*float64(time.Second))) + defer cancel() + + res := orchestrator.SufficientContextAgent(callCtx, orchestrator.SCADeps{ + KB: st.KB, + Model: &jsonModelAdapter{inner: deps.Model, maxLength: deps.MaxLength, modelName: deps.ModelName, cache: redisGenJSONCache{}}, + Prompts: deps.SCAPrompts, + }, st.Question, claims) + + st.SCAViewID = viewID + st.SCA = scaResultToMap(res) + if len(st.SCA) == 0 { + // sca — an unavailable SCA (timeout, unparsable reply, no + // model) is INSUFFICIENT, so the unresolved slots can drive another + // research round. Accepting the draft here would ship an unverified + // answer as if the review had passed it. + logger.Printf("[SCA] unavailable; marking INSUFFICIENT so unresolved slots can drive another research round.") + st.SCA = map[string]any{} + st.Verdict = VerdictInsufficient + return + } + if res.IsSufficient { + st.Verdict = VerdictSufficient + } else { + st.Verdict = VerdictInsufficient + } + logger.Printf("[SCA] verdict=%s (confidence=%.2f; view=%d/%d)", st.Verdict, res.Confidence, len(view), len(chunks)) +} + +// unresolvedClueGaps mirrors Python's gap fallback (action_session...:1114-1128, +// agentic_rag_graph.py query_rewrite): the first two question_clues of every +// unresolved slot become (what, hint) gaps, so a rewrite can still be issued +// when the SCA produced no structured gaps. +func unresolvedClueGaps(st *AgenticState) []orchestrator.MissingPiece { + var gaps []orchestrator.MissingPiece + seen := map[string]bool{} + for _, us := range st.UnresolvedSlots { + clues, ok := us["question_clues"].([]string) + if !ok { + continue + } + for i, qc := range clues { + if i >= 2 { + break + } + qc = strings.TrimSpace(qc) + if qc == "" || seen[qc] { + continue + } + seen[qc] = true + gaps = append(gaps, orchestrator.MissingPiece{What: qc, SearchHint: qc}) + } + } + return gaps +} + +// queryRewriteNode mirrors the `query_rewrite` node: Phase-4 +// targeted gap pursuit. +func queryRewriteNode(ctx context.Context, deps RAGTools, st *AgenticState, logger *log.Logger) { + ctx, done := harness.Phase(ctx, "rewrite") + defer done() + + gaps := SCAGapsToRewrite(st.SCA) + if len(gaps) == 0 { + // query_rewrite — a timed-out or unavailable SCA leaves no + // structured gap payload, but an unresolved slot table still gives + // precise retrieval directions. Fold those in BEFORE giving up, so the + // research loop stays alive instead of an unresolved draft being + // accepted as if it were sufficient. + gaps = unresolvedClueGaps(st) + } + if len(gaps) == 0 { + logger.Printf("[QueryRewriter] SCA insufficient but no concrete gap; accepting the draft.") + st.NoProgress = true + return + } + + // Information-augmented rewriting: give the rewriter FULL VISIBILITY — what + // was tried (with outcomes), what the evidence pool holds — so it aims at + // uncovered angles itself, instead of rule-based dedupe. + researchContext := renderResearchContext(st) + + t := min(RewriteTimeoutS, max(10.0, st.RemainingS()-10.0)) + callCtx, cancel := context.WithTimeout(ctx, time.Duration(t*float64(time.Second))) + defer cancel() + + rewritten := orchestrator.RewriteGapToQuery(callCtx, orchestrator.RewriteDeps{ + Model: &jsonModelAdapter{inner: deps.Model, maxLength: deps.MaxLength, modelName: deps.ModelName, cache: redisGenJSONCache{}}, + Prompts: deps.RewritePrompts, + ResearchContext: researchContext, + }, st.Question, gaps) + + var queries []string + for _, q := range rewritten { + if s := strings.TrimSpace(q["query"]); s != "" { + queries = append(queries, s) + } + } + // Fold the still-unresolved slots into the rewrite queries so the next slot + // research pass targets exactly those unknowns. This makes an insufficient + // verdict drive slot completion, not a blind re-search. + for _, us := range st.UnresolvedSlots { + if clues, ok := us["question_clues"].([]string); ok { + for i, qc := range clues { + if i >= 2 { + break + } + if s := strings.TrimSpace(qc); s != "" { + queries = append(queries, s) + } + } + } + } + queries = dedupe(queries) + if len(queries) == 0 { + logger.Printf("[QueryRewriter] no actionable query produced; accepting the draft.") + st.NoProgress = true + return + } + + // Dual-track pursuit of the gap: (a) programmatically pre-fetch new snippets + // into the SCA pool; (b) the next slot research pass picks these up via the + // persisted slot_table + unresolved_slots. + added := FanoutSearch(callCtx, deps, st, queries, FanoutTopNRewrite, MaxSnippetPool) + // Retrieval saturation early-exit: a rewrite round that produced ZERO new + // snippets means further full research passes just burn latency. + if added == 0 && st.SearchRounds >= 1 { + logger.Printf("[QueryRewriter] retrieval saturated (0 new chunks after another insufficient round); stopping iteration.") + st.NoProgress = true + st.CurrentQueries = queries + return + } + + logger.Printf("[QueryRewriter] insufficient round %d → %d targeted query(s): %v", + st.SearchRounds+1, len(queries), queries) + st.NoProgress = false + st.CurrentQueries = queries + st.SearchRounds++ + for _, q := range queries { + st.Attempted = append(st.Attempted, map[string]any{"q": q, "r": st.SearchRounds, "new": added}) + } +} + +// formalizeAnswerNode mirrors the `formalize_answer` node's state mutation +// (query_rewrite). The answer composition itself (Phase 5 synthesis) is out of +// scope here — it needs the report prompt templates; the caller reads the +// approved draft from st.KB.PreSummary. +func formalizeAnswerNode(ctx context.Context, deps RAGTools, st *AgenticState, logger *log.Logger) { + if st.NoProgress || st.Verdict == VerdictInsufficient { + // All research attempts exhausted without a satisfying context — surface + // the residual findings honestly instead of refusing. + st.PartialAnswer = true + } + st.EmptyResult = len(st.KB.Chunks) == 0 + logger.Printf("[Finalize] partial=%v empty=%v chunks=%d", st.PartialAnswer, st.EmptyResult, len(st.KB.Chunks)) + // formalize_answer — the node itself composes and streams the answer + // (_compose_answer_from_evidence); it does not just flag the state. + if deps.Finalize != nil { + deps.Finalize(ctx) + } +} + +// --------------------------------------------------------------------------- +// SCA helpers (Python agentic_rag_graph.py: _select_sca_view, _view_terms, +// _sca_gaps_to_rewrite, and the sca node's claim construction). +// --------------------------------------------------------------------------- + +// buildSCAClaims mirrors the sca node's claim construction (lines 971-997): the +// draft as claim "c0", plus one claim per slot carrying its evidence positions. +// +// It returns the (possibly grown) view alongside the claims: Python appends the +// slot-evidence chunks that the view missed to the SAME list +// (sca) and then reviews against it, so the caller must +// review against the returned slice, not the one it passed in. +func buildSCAClaims(draftText string, view, chunks []map[string]any, slotEvidence map[string]SlotEvidence) ([]orchestrator.ClaimDraft, []map[string]any) { + var claims []orchestrator.ClaimDraft + if draftText != "" { + claims = append(claims, orchestrator.ClaimDraft{ID: "c0", Draft: draftText}) + } + viewIndexByID := map[string]int{} + for i, c := range view { + if id := harness.ChunkIDOf(c); id != "" { + viewIndexByID[id] = i + } + } + sids := make([]string, 0, len(slotEvidence)) + for sid := range slotEvidence { + sids = append(sids, sid) + } + sort.Strings(sids) + for _, sid := range sids { + meta := slotEvidence[sid] + if len(meta.EvidenceIDs) == 0 { + continue + } + // Resolve every evidence id to a POSITION in the view, appending chunks + // that are missing so the SCA sees the passages that actually produced + // the candidate (sca). + positions := make([]string, 0, len(meta.EvidenceIDs)) + for _, eid := range meta.EvidenceIDs { + pos := -1 + if p, ok := viewIndexByID[eid]; ok { + pos = p + } else if c := resolveEvidenceChunk(eid, chunks); c != nil { + if p, ok := viewIndexByID[harness.ChunkIDOf(c)]; ok { + pos = p + } else { + view = append(view, c) + pos = len(view) - 1 + if id := harness.ChunkIDOf(c); id != "" { + viewIndexByID[id] = pos + } + } + } + if pos >= 0 { + positions = append(positions, strconv.Itoa(pos)) + } + } + draft := truncateRunes(meta.Candidate, draftCandidateChars) + if draft == "" { + draft = fmt.Sprintf("(slot %s evidence)", sid) + } + claims = append(claims, orchestrator.ClaimDraft{ID: sid, Draft: draft, EvidenceIDs: positions}) + } + if len(claims) == 0 { + // sca — an empty draft still gets ONE claim, carrying every + // position in the view, so the SCA judges the evidence itself instead of + // the node short-circuiting on "no draft". + draft := draftText + if strings.TrimSpace(draft) == "" { + draft = "(no draft)" + } + claims = []orchestrator.ClaimDraft{{ID: "c0", Draft: draft, EvidenceIDs: allViewPositions(view)}} + } + return claims, view +} + +// resolveEvidenceChunk maps one slot-evidence id back to a chunk. The ids are +// heterogeneous by construction: +// +// - the retrieval tools emit the chunk id (Python _admit_evidence's +// `ids.append(cid)`); +// - the navigation tools emit document ids (tool_executor.go:455); +// - the SCA view itself is keyed by POSITION (renderClaimContext / +// sufficient_context.go:305-309), which the numeric branch below covers. +// +// Python's slot_evidence holds chunk ids throughout (sca), +// so both spellings are resolved here before giving up. +func resolveEvidenceChunk(eid string, chunks []map[string]any) map[string]any { + eid = strings.TrimSpace(eid) + if eid == "" { + return nil + } + if n, err := strconv.Atoi(eid); err == nil && n >= 0 && n < len(chunks) { + return chunks[n] + } + for _, c := range chunks { + if harness.ChunkIDOf(c) == eid { + return c + } + if id := harness.DocIDOf(c); id != "" && id == eid { + return c + } + } + return nil +} + +// allViewPositions is "every position in the view" — the Go counterpart of +// Python's list(range(len(view))) (renderClaimContext keys evidence by index). +func allViewPositions(view []map[string]any) []string { + positions := make([]string, 0, len(view)) + for i := range view { + positions = append(positions, strconv.Itoa(i)) + } + return positions +} + +// viewChunkIDs collects the chunk ids of a view — the Go counterpart of +// Python's "all view positions", since the SCA indexes evidence by chunk id. +func viewChunkIDs(view []map[string]any) []string { + ids := make([]string, 0, len(view)) + for _, c := range view { + if id := harness.ChunkIDOf(c); id != "" { + ids = append(ids, id) + } + } + return ids +} + +// genJSONMaxRetry mirrors Python gen_json's default max_retry=2: the first +// call, plus one corrective round that feeds the malformed answer and the parse +// error back to the model. +const genJSONMaxRetry = 2 + +// LLMCache is the gen_json reply-cache seam (Python +// rag.graphrag.utils.get_llm_cache / set_llm_cache). A nil seam disables +// caching, which is also what a Redis-less deployment gets. +type LLMCache interface { + Get(ctx context.Context, key string) (string, bool) + Set(ctx context.Context, key, value string) +} + +// genJSONCacheTTL mirrors Python set_llm_cache's `24 * 3600` second expiry. +const genJSONCacheTTL = 24 * time.Hour + +// genJSONCacheKey mirrors gen_json's cache key byte for byte: +// +// xxhash.xxh64(str(llm_name) + str(system_prompt) + str(user_prompt) + str(gen_conf)).hexdigest() +// +// `str(gen_conf)` of the default {} is "{}" — the two agentic callers (SCA +// review, gap→query rewrite) pass no gen_conf, so the literal is exact. Go's +// zero-padded %016x over xxhash.Sum64String prints the same 16 lowercase hex +// digits Python's hexdigest() does (plain %x drops leading zeros), so a Go and +// a Python process sharing one Redis share one cache. An empty modelName yields +// "" and the caller must then SKIP the cache: keying on an empty name would +// collapse every model onto one bucket. +func genJSONCacheKey(modelName, systemPrompt, userPrompt string) string { + if modelName == "" { + return "" + } + return fmt.Sprintf("%016x", xxhash.Sum64String(modelName+systemPrompt+userPrompt+"{}")) +} + +// redisGenJSONCache is the production LLMCache: the process-wide Redis client. +// With no Redis configured redis.Get() is nil and every call degrades to a miss +// — the same "no cache" behaviour Python has when REDIS_CONN is absent. +type redisGenJSONCache struct{} + +func (redisGenJSONCache) Get(ctx context.Context, key string) (string, bool) { + client := redis.Get() + if client == nil || key == "" { + return "", false + } + v, err := client.Get(ctx, key) + if err != nil || v == "" { + return "", false + } + return v, true +} + +func (redisGenJSONCache) Set(ctx context.Context, key, value string) { + client := redis.Get() + if client == nil || key == "" || value == "" { + return + } + client.Set(ctx, key, value, genJSONCacheTTL) +} + +// jsonModelAdapter adapts harness.SessionModel to orchestrator.JSONModel. +// +// Mirrors Python's gen_json(prompt, "Output:\n", chat_mdl): a 24h reply cache is +// consulted first, the rendered prompt is the system turn and "Output:\n" the +// user turn (fitted ONCE to the model's context window), then the first JSON +// value is parsed out of the reply. Malformed JSON is retried (up to +// genJSONMaxRetry calls) with the model's own bad answer and the parse error +// appended to the user turn, so a single formatting hiccup does not abort the +// SCA review or the query rewrite. +type jsonModelAdapter struct { + inner harness.SessionModel + // maxLength is the chat model's context window (Python + // chat_mdl.max_length). It bounds gen_json's message_fit_in so an oversized + // prompt is trimmed instead of rejected by the provider. <=0 falls back to + // chat.EffectiveContextLength's 8192 default. + maxLength int + // modelName is the resolved chat model identity (Python chat_mdl.llm_name). + // Empty disables the reply cache (see genJSONCacheKey). + modelName string + // cache is the gen_json reply cache; nil disables caching. + cache LLMCache +} + +// parseGenJSONReply parses a cleaned model reply with gen_json's tolerance: a +// strict decode of ANY top-level JSON value first (json_repair accepts objects, +// arrays and scalars alike), then the brace-matched object extractor for fenced +// or damaged objects — the JSON-shaped gate, NOT the prose-salvaging ExtractJSON, +// so a non-JSON reply stays a parse failure and triggers the corrective retry. +// The boolean distinguishes a successful decode from a failure, because a +// legitimate `null` reply decodes to a nil value. +func parseGenJSONReply(cleaned string) (any, bool) { + var val any + if err := json.Unmarshal([]byte(strings.TrimSpace(cleaned)), &val); err == nil { + return val, true + } + if v := harness.ExtractJSONObject(cleaned); v != nil { + return v, true + } + return nil, false +} + +// genJSONTailFenceRE matches a trailing ``` fence followed by any newlines, the +// "```\n*$" alternative of gen_json's cleanup regex. +var genJSONTailFenceRE = regexp.MustCompile("```\\n*$") + +// stripGenJSONWrappers mirrors gen_json's answer cleanup: +// +// ans = re.sub(r"(^.*|```json\n|```\n*$)", "", ans, flags=re.DOTALL) +// +// The think term (greedy up to the LAST ) is common.StripThinkTrailing; +// a "```json\n" fence may occur anywhere and is removed wholesale; a trailing +// "```" (plus newlines) is cut from the end. +func stripGenJSONWrappers(s string) string { + s = common.StripThinkTrailing(s) + s = strings.ReplaceAll(s, "```json\n", "") + return genJSONTailFenceRE.ReplaceAllString(s, "") +} + +// GenJSON implements orchestrator.JSONModel. +func (a *jsonModelAdapter) GenJSON(ctx context.Context, prompt string) (any, error) { + if a.inner == nil { + return nil, fmt.Errorf("agentic: no model configured") + } + // Python gen_json consults the 24h reply cache FIRST, keyed on the ORIGINAL + // system/user prompts (not the fitted ones), and returns without any model + // call on a hit: + // cached = get_llm_cache(chat_mdl.llm_name, system_prompt, user_prompt, gen_conf) + // if cached: return json_repair.loads(cached) + const userPrompt = "Output:\n" + cacheKey := "" + if a.cache != nil { + cacheKey = genJSONCacheKey(a.modelName, prompt, userPrompt) + if cached, hit := a.cache.Get(ctx, cacheKey); hit { + if v, ok := parseGenJSONReply(cached); ok { + return v, nil + } + } + } + // Python gen_json then fits ONCE, before the retry loop: + // _, msg = message_fit_in(form_message(system_prompt, user_prompt), max_length) + // and sends msg[0] as the system turn and msg[1:] as history, appending the + // corrective text to the LAST user turn WITHOUT re-fitting. A zero/negative + // max_length is normalised to 8192 by chat.EffectiveContextLength. + baseUser := userPrompt + systemTurn := prompt + if fitted, _ := chat.FitMessages("", []schema.Message{ + *schema.SystemMessage(prompt), + *schema.UserMessage(baseUser), + }, a.maxLength); len(fitted) > 0 { + if fitted[0].Role == schema.System { + systemTurn = fitted[0].Content + } + if last := fitted[len(fitted)-1]; last.Role == schema.User { + baseUser = last.Content + } + } + var lastAns, errText string + for attempt := 0; attempt < genJSONMaxRetry; attempt++ { + userTurn := baseUser + if attempt > 0 && lastAns != "" && errText != "" { + // gen_json appends the corrective prompt to the user turn only once + // the previous round produced both an answer and a parse error. + userTurn = baseUser + fmt.Sprintf("\nGenerated JSON is as following:\n%s\nBut exception while loading:\n%s\nPlease reconsider and correct it.", lastAns, errText) + } + reply, err := a.inner.Complete(ctx, []schema.Message{ + *schema.SystemMessage(systemTurn), + *schema.UserMessage(userTurn), + }, nil) + if err != nil { + // gen_json propagates chat/transport errors immediately; only JSON + // parsing failures are retried. Mirror that. + return nil, err + } + cleaned := stripGenJSONWrappers(reply.Content) + // The corrective prompt re-sends the CLEANED answer: Python's gen_json + // rebinds `ans` to the post-regex value, so the next round's + // "Generated JSON is as following:" carries the stripped text, not the + // raw reply with its fences / think block. + lastAns = cleaned + if v, ok := parseGenJSONReply(cleaned); ok { + // Python caches the CLEANED answer on the first successful parse + // (set_llm_cache(..., ans, ...)), and only there. + if a.cache != nil && cacheKey != "" { + a.cache.Set(ctx, cacheKey, cleaned) + } + return v, nil + } + // Deliberately log length, not content: the reply may embed retrieved + // material (PII), so the raw body is excluded, as in jsonchat.GenJSON. + errText = fmt.Sprintf("model reply (%d bytes) is not parseable JSON", len(cleaned)) + } + return nil, fmt.Errorf("agentic: no parseable JSON in the model output after %d attempts", genJSONMaxRetry) +} + +// scaResultToMap flattens an SCAResult back into the map shape the loop keeps in +// AgenticState.SCA (SCAGapsToRewrite reads both shapes). +func scaResultToMap(res orchestrator.SCAResult) map[string]any { + if len(res.Claims) == 0 && res.Reasoning == "" && !res.IsSufficient { + return nil + } + out := map[string]any{ + "is_sufficient": res.IsSufficient, + "confidence": res.Confidence, + "contradictions": toAnySlice(res.Contradictions), + "reasoning": res.Reasoning, + "claims": res.Claims, + } + if len(res.SubQueries) > 0 { + sqs := make([]any, 0, len(res.SubQueries)) + for _, sq := range res.SubQueries { + sqs = append(sqs, map[string]any{ + "sub_query": sq.SubQuery, + "satisfied": sq.Satisfied, + "missing_fact": sq.MissingFact, + "search_hint": sq.SearchHint, + }) + } + out["sub_queries"] = sqs + } + return out +} + +func toAnySlice(ss []string) []any { + out := make([]any, 0, len(ss)) + for _, s := range ss { + out = append(out, s) + } + return out +} + +// verdictStatusHint mirrors agentic_rag.py:911-915 — the human phrase folded +// into rag()'s "[Research status]" note for each sufficiency status. +// +// Only INSUFFICIENT is reachable: Python's verdict dict carries a single +// "status" key (sca) whose value is either +// "SUFFICIENT" or "INSUFFICIENT" (sca), and skips SUFFICIENT outright. +// The upstream dict's USEFUL_BUT_INCOMPLETE and CONFLICTING entries are +// therefore unreachable, so Go does not carry cases for them. +func verdictStatusHint(verdict string) string { + switch verdict { + case VerdictInsufficient: + return "evidence is not yet sufficient" + default: + return "sufficiency status: " + verdict + } +} + +// scaFeedback mirrors agentic_rag.py:902-929 — the body rag() folds into the answer as +// the "[Research status]" note whenever research stays unsatisfying. +// +// Python composes it as `status_hint + missing_txt + hard_txt + conf_txt + fb_txt`, but +// every term after the first is empty in practice: `verdict` is `{"status": ...}` and +// carries no missing_claims / hard_violations / agent_confidence / feedback keys anywhere +// in the Python tree, so the note is the status hint alone. +// +// The SCA's rich payload is not lost — it stays in AgenticState.SCA and still drives +// SCAGapsToRewrite (which reads the separate `sca` state key). Non-empty for +// ANY non-SUFFICIENT verdict (not only after two consecutive misses), so the caller can +// append the appropriate trailing sentence ("STOP" vs "call rag again"). +func scaFeedback(_ map[string]any, verdict string) string { + if verdict == VerdictSufficient { + return "" + } + return verdictStatusHint(verdict) +} + +// renderResearchContext mirrors the query_rewrite node's context build +// (lines 1047-1066): the attempted-query ledger with outcomes, plus the first +// lines of the evidence pool. +func renderResearchContext(st *AgenticState) string { + var historyLines []string + for _, e := range st.Attempted { + if e == nil { + continue + } + q := truncateRunes(stringOf(e["q"]), 120) + r := stringOf(e["r"]) + if r == "" { + r = "?" + } + outcome := "no new passages" + if n, ok := toIntStrict(e["new"]); ok && n != 0 { + outcome = fmt.Sprintf("%d new passage(s)", n) + } + historyLines = append(historyLines, fmt.Sprintf("- %s (round %s: %s)", q, r, outcome)) + } + var poolLines []string + if st.KB != nil { + for i, c := range st.KB.Chunks { + if i >= PoolHeadLines { + break + } + first := harness.ChunkTextOf(c) + if idx := strings.IndexByte(first, '\n'); idx >= 0 { + first = first[:idx] + } + if first = strings.TrimSpace(first); first != "" { + poolLines = append(poolLines, "- "+truncateRunes(first, 140)) + } + } + } + var parts []string + if len(historyLines) > 0 { + parts = append(parts, "Previously searched queries and their outcomes:\n"+strings.Join(historyLines, "\n")) + } + if len(poolLines) > 0 { + parts = append(parts, "Evidence currently at hand (first lines of top stored snippets):\n"+strings.Join(poolLines, "\n")) + } + return strings.Join(parts, "\n\n") +} + +// routeSCA mirrors Python _route_sca. +func routeSCA(st *AgenticState, enableSCA bool, scaMaxRounds int) agenticNode { + if st.NoProgress { + return nodeFormalizeAnswer + } + if !enableSCA { + // medium: single research pass — the SCA verdict is informational only. + return nodeFormalizeAnswer + } + if st.Verdict == VerdictInsufficient && + st.SearchRounds < scaMaxRounds && + // Budget guard: only start another rewrite+research round when enough + // headroom remains for the whole round. + st.RemainingS() > MinRoundHeadroomS { + return nodeQueryRewrite + } + return nodeFormalizeAnswer +} + +// routeRewrite mirrors Python _route_rewrite. +func routeRewrite(st *AgenticState, scaMaxRounds int, logger *log.Logger) agenticNode { + if st.NoProgress { + return nodeFormalizeAnswer + } + if st.SearchRounds >= scaMaxRounds { + return nodeFormalizeAnswer + } + if st.RemainingS() <= MinRoundHeadroomS { + if logger != nil { + logger.Printf("[Routing] research budget nearly exhausted (%.0fs left); closing out with current evidence.", st.RemainingS()) + } + return nodeFormalizeAnswer + } + return nodeRagAgentLoop +} + +// RenderSlotDraft mirrors Python _render_slot_draft: +// render the slot table into a fact-preserving draft for the SCA. +// +// A resolved slot carries the model's own candidate strength, the evidence ids / +// terminal type of the passages that produced it (from slotEvidence), and the +// tail of its discovered clues, so the SCA can verify the candidate against the +// passages that actually produced it. Unresolved slots are listed explicitly +// with their question clues so the SCA can call them out as gaps. A collected +// answer leads the draft — it is the strongest candidate — with the same +// evidence metadata under the "_answer" key. +func RenderSlotDraft(slotTable harness.State, collectedAnswer string, slotEvidence map[string]SlotEvidence) string { + var lines []string + if collectedAnswer != "" { + // Python leads with the collected answer (the strongest candidate) and + // carries the same evidence metadata, read from the "_answer" key. + lines = append(lines, "Candidate answer: "+collectedAnswer+draftEvidenceSuffix(slotEvidence["_answer"])) + lines = append(lines, "") + } + if len(slotTable.State) == 0 { + return strings.Join(lines, "\n") + } + for _, v := range slotTable.State { + vtype := v.Type + if vtype == "" { + vtype = "entity" + } + cand := "" + if v.Candidate != nil { + cand = *v.Candidate + } + if cand == "" { + clues := v.QuestionClues + if len(clues) > 2 { + clues = clues[:2] + } + lines = append(lines, fmt.Sprintf("- slot %d [%s]: NOT RESOLVED (%s)", + v.ID, vtype, strings.Join(truncateEach(clues, draftUnresolvedClueChars), "; "))) + continue + } + strength := "?" + if v.CandidateStrength != nil { + strength = fmt.Sprintf("%.2f", *v.CandidateStrength) + } + line := fmt.Sprintf("- slot %d [%s]: %s (strength=%s)%s", + v.ID, vtype, cand, strength, draftEvidenceSuffix(slotEvidence[fmt.Sprint(v.ID)])) + if tail := draftClueTail(v.DiscoveredClues); tail != "" { + line += " — " + tail + } + lines = append(lines, line) + } + return strings.Join(lines, "\n") +} + +// draftEvidenceSuffix renders Python's " [terminal=..., evidence_ids=['a', 'b']]" +// suffix; empty when the session recorded neither. +func draftEvidenceSuffix(ev SlotEvidence) string { + var parts []string + if ev.TerminalType != "" { + parts = append(parts, "terminal="+ev.TerminalType) + } + if len(ev.EvidenceIDs) > 0 { + parts = append(parts, "evidence_ids="+pyListRepr(ev.EvidenceIDs)) + } + if len(parts) == 0 { + return "" + } + return " [" + strings.Join(parts, ", ") + "]" +} + +// draftClueTail joins a resolved slot's last four discovered clues the way +// Python does: each capped at draftClueTailChars, separated by "; ". Empty clues +// are KEPT — Python joins them too, so `["", "x"]` renders as "; x". +func draftClueTail(clues []string) string { + if len(clues) > 4 { + clues = clues[len(clues)-4:] + } + capped := make([]string, 0, len(clues)) + for _, c := range clues { + capped = append(capped, truncateRunes(c, draftClueTailChars)) + } + return strings.Join(capped, "; ") +} + +// pyListRepr renders a string slice the way Python's str(list) does +// (['a', 'b']): the draft text is prompt content the SCA reads, so it must match +// the Python run rather than Go's fmt.Sprint form ([a b]). +func pyListRepr(in []string) string { + quoted := make([]string, 0, len(in)) + for _, s := range in { + quoted = append(quoted, "'"+s+"'") + } + return "[" + strings.Join(quoted, ", ") + "]" +} + +// --------------------------------------------------------------------------- +// Slot-table research: the executor behind the outer loop's `rag_agent` node. +// +// Mirrors Python agentic_rag_graph.py: +// - _build_slot_table +// - _run_slot_research_pass +// - _merge_slot_patch +// - _render_slot_draft +// +// One research round = one action session per unresolved slot, run concurrently +// under a semaphore, with the resulting branches folded back into the shared +// table. +// --------------------------------------------------------------------------- + +// SlotEvidence records which passages produced a slot's candidate, so the SCA +// can verify the candidate against the passages that actually produced it. +type SlotEvidence struct { + EvidenceIDs []string + TerminalType string + Candidate string + Strength *float64 +} + +// SlotResearchResult is one research round's output. +type SlotResearchResult struct { + SlotTable harness.State + CollectedAnswer string + UnresolvedSlots []map[string]any + SlotEvidence map[string]SlotEvidence + SlotDraft string + Attempted []map[string]any +} + +// BuildSlotTable mirrors Python _build_slot_table: decompose the question into +// a slot table, seeding it with the planner's fan-outs. +// +// Returns (root, firstQueries) — never an empty root: on failure it degrades to +// one "aspect" slot per fan-out (or a single "answer" slot for the raw +// question), so the research pass always has something to work on. +func BuildSlotTable(ctx context.Context, deps harness.SessionDeps, question string, fanouts []string, deadlineLeft float64) (harness.State, []string) { + root, firstQueries, err := buildSlotTableFrom(ctx, deps, question, fanouts, deadlineLeft) + if err != nil { + _LOG.Printf("[SlotTable] initialize_state failed; building from fanouts: %v", err) + // _build_slot_table — the exception path keeps the FULL fan-out list as + // first_queries; the [:3] cap below belongs to the empty-root path only. + if len(fanouts) > 0 { + firstQueries = fanouts + } else { + firstQueries = []string{question} + } + } + if len(root.State) == 0 { + queries := fanouts + if len(queries) == 0 { + queries = []string{question} + } + vars := make([]harness.Variable, 0, 4) + for i, q := range queries { + if i >= 4 { + break + } + vars = append(vars, harness.Variable{ + ID: i, + Type: "aspect", + QuestionClues: []string{truncateRunes(q, slotFallbackClueChars)}, + }) + } + root = harness.NewState(vars, 0, nil) + if len(firstQueries) == 0 { + firstQueries = queries + if len(firstQueries) > 3 { + firstQueries = firstQueries[:3] + } + } + } + _LOG.Printf("[SlotTable] built %d slot(s): %s", len(root.State), root.Brief()) + if len(firstQueries) == 0 { + firstQueries = []string{question} + } + return root, firstQueries +} + +// buildSlotTableFrom wraps InitializeState, converting its non-error result into +// an error so BuildSlotTable can apply the single fallback path. +func buildSlotTableFrom(ctx context.Context, deps harness.SessionDeps, question string, fanouts []string, deadlineLeft float64) (harness.State, []string, error) { + if deps.Model == nil { + return harness.State{}, nil, fmt.Errorf("no model configured") + } + init := harness.InitializeState(ctx, deps, question, fanouts, deadlineLeft) + if len(init.Root.State) == 0 { + // Covers both an empty reply and a reply the strict Python parser + // rejected (non-integer id / non-iterable clues); Python's exception path + // in _build_slot_table lands here too. + return harness.State{}, nil, fmt.Errorf("decomposition failed") + } + return init.Root, init.FirstQueries, nil +} + +// RunSlotResearchPass mirrors Python _run_slot_research_pass: drive ONE +// research round with slot-aware action sessions. +// +// Unresolved slots are worked concurrently under a semaphore; each session's +// branches are folded back into the shared table. A nil result means "nothing to +// do" (all slots already filled). +func RunSlotResearchPass(ctx context.Context, deps harness.SessionDeps, question string, st *AgenticState, deadlineLeft float64) *SlotResearchResult { + slotTable := st.SlotTable + if len(slotTable.State) == 0 { + // No planner ran (medium single-pass, or the planner failed): build the + // table from the raw question so the research still executes. + root, _ := BuildSlotTable(ctx, deps, question, nil, max(15.0, deadlineLeft-10.0)) + slotTable = root + } + if question == "" { + question = st.Question + } + unresolved := slotTable.Unresolved() + if len(unresolved) == 0 { + _LOG.Printf("[SlotResearch] all slots filled; no session to run.") + return nil + } + + // Shared across sessions so duplicate retrievals are served from cache. + sharedToolCache := map[string]harness.ToolOutcome{} + var sharedSearchQueries []string + + sem := make(chan struct{}, slotSessionConcurrency) + var wg sync.WaitGroup + var mu sync.Mutex + + type outcome struct { + slotID int + result harness.Result + } + results := make([]outcome, 0, slotSessionsPerRound) + limit := min(len(unresolved), slotSessionsPerRound) + sessionBudget := max(20.0, deadlineLeft-10.0) + + for i := 0; i < limit; i++ { + v := unresolved[i] + wg.Add(1) + go func(v harness.Variable) { + defer wg.Done() + sem <- struct{}{} + defer func() { <-sem }() + + direction := question + if len(v.QuestionClues) > 0 { + direction = v.QuestionClues[0] + } + // Sessions share ONE Toolset; DisableTool mutates it, so the call is + // guarded here. The Kbinfos merge happens inside the executor. + res := harness.RunActionSession(ctx, deps, direction, slotTable, sessionBudget, "", sharedToolCache, sharedSearchQueries) + mu.Lock() + results = append(results, outcome{slotID: v.ID, result: res}) + mu.Unlock() + }(v) + } + wg.Wait() + + // Fold in slot-id order so the merge is deterministic regardless of which + // session finished first. + sort.Slice(results, func(i, j int) bool { return results[i].slotID < results[j].slotID }) + + collected := st.CollectedAnswer + sessionEvidence := map[string]SlotEvidence{} + ledger := append([]map[string]any(nil), st.Attempted...) + + for _, item := range results { + r := item.result + if r.FoundAnswer != nil && collected == "" { + collected = *r.FoundAnswer + } + if len(r.RetrievedEvidenceIDs) > 0 { + terminalType := "" + if r.TerminalType != nil { + terminalType = *r.TerminalType + } + var candidate string + if r.FoundAnswer != nil { + candidate = *r.FoundAnswer + } + sessionEvidence[fmt.Sprint(item.slotID)] = SlotEvidence{ + EvidenceIDs: dedupe(r.RetrievedEvidenceIDs), + TerminalType: terminalType, + Candidate: candidate, + } + } + for _, ns := range r.NewStates { + if merged := MergeSlotPatch(slotTable, ns); merged != nil { + slotTable = *merged + } + } + // _run_slot_research_pass — a session without a found answer still logs a hint, taken + // from its message history (`(r.found_answer or str(r.messages))[:80]`). + // Without the fallback the rewriter's research context shows a bare + // "- (round N: …)" row for those sessions. + q := "" + if r.FoundAnswer != nil { + q = truncateRunes(*r.FoundAnswer, 80) + } else { + q = pythonMessageListPrefix(r.Messages, 80) + } + ledger = append(ledger, map[string]any{"q": q, "new": 1}) + } + + // _run_slot_research_pass — report how many passages each slot's session bound, so + // a round that retrieved nothing for a slot is visible in the run log. + if len(sessionEvidence) > 0 { + bounds := make(map[string]int, len(sessionEvidence)) + for sid, ev := range sessionEvidence { + bounds[sid] = len(ev.EvidenceIDs) + } + _LOG.Printf("[SlotResearch] slot evidence bound: %v", bounds) + } + + unresolvedOut := make([]map[string]any, 0, len(unresolved)) + for _, v := range slotTable.Unresolved() { + clues := v.DiscoveredClues + if len(clues) > 4 { + clues = clues[len(clues)-4:] + } + unresolvedOut = append(unresolvedOut, map[string]any{ + "id": v.ID, + "type": v.Type, + "question_clues": append([]string(nil), v.QuestionClues...), + "discovered_clues": append([]string(nil), clues...), + }) + } + + draft := RenderSlotDraft(slotTable, collected, sessionEvidence) + _LOG.Printf("[SlotResearch] round done — %d slot(s) filled, unresolved=%d, collected_answer=%v", + countFilled(slotTable), len(unresolvedOut), collected != "") + _LOG.Printf("[SlotResearch] slot table after round:\n%s", draft) + + return &SlotResearchResult{ + SlotTable: slotTable, + CollectedAnswer: collected, + UnresolvedSlots: unresolvedOut, + SlotEvidence: sessionEvidence, + SlotDraft: draft, + Attempted: ledger, + } +} + +// MergeSlotPatch mirrors Python _merge_slot_patch: fold a session's new-state +// branch into the shared slot table, adopting the STRONGER candidate. +// +// Returns nil when nothing changed (mirrors Python's `if not changed: return +// None`), so callers can skip no-op merges. +func MergeSlotPatch(base, branch harness.State) *harness.State { + if len(branch.State) == 0 { + return nil + } + branchByID := map[int]harness.Variable{} + for _, v := range branch.State { + branchByID[v.ID] = v + } + merged := make([]harness.Variable, 0, len(base.State)) + changed := false + for _, v := range base.State { + bv, ok := branchByID[v.ID] + if !ok { + merged = append(merged, v) + continue + } + // Adopt the branch candidate only when STRONGER. Sessions run + // concurrently and their branches fold in completion order, so an + // unconditional "branch wins" made the result both order-dependent and + // destructive: a weak session (0.3, tentative) could downgrade a slot + // another session had already proven (0.95). + cand, strength := v.Candidate, v.CandidateStrength + switch { + case bv.Candidate == nil: + // branch has no candidate: keep base + case v.Candidate == nil: + cand, strength = bv.Candidate, bv.CandidateStrength + case strengthOf(bv) > strengthOf(v): + cand, strength = bv.Candidate, bv.CandidateStrength + } + clues := dedupe(append(append([]string(nil), v.DiscoveredClues...), bv.DiscoveredClues...)) + if !equalStringPtr(cand, v.Candidate) || !equalStrings(clues, v.DiscoveredClues) { + changed = true + } + merged = append(merged, harness.Variable{ + ID: v.ID, + Type: v.Type, + QuestionClues: append([]string(nil), v.QuestionClues...), + DiscoveredClues: clues, + Candidate: cand, + CandidateStrength: strength, + }) + } + if !changed { + return nil + } + out := harness.NewState(merged, base.Depth+1, append([]string(nil), base.RetrievedEvidenceIDs...)) + return &out +} + +// pythonMessageListPrefix reproduces Python's `str(messages)[:n]` for a langchain +// message list — the ledger hint _run_slot_research_pass builds with +// `(r.found_answer or str(r.messages))[:80]`. +// +// It is an emulation, not an approximation of intent: the value is prompt-visible +// (it lands in the rewriter's "Previously searched queries and their outcomes" +// block), so the port keeps Python's exact text even though that text is a +// truncated system-prompt fragment. The reprs mirror langchain_core's +// pydantic-generated ones, verified against the installed version: +// +// SystemMessage(content='…', additional_kwargs={}, response_metadata={}) +// HumanMessage(content='…', additional_kwargs={}, response_metadata={}) +// AIMessage(content='…', additional_kwargs={}, response_metadata={}, tool_calls=[…], invalid_tool_calls=[]) +// ToolMessage(content='…', tool_call_id='…') +// +// Known limits (both unreachable at the 80-rune window this is used with, which +// never gets past the session's system message): tool-call args come from a Go +// map, so their key order is the sorted one rather than langchain's insertion +// order; and message `id`/`usage_metadata` fields, which langchain fills with +// per-run uuids, are not reproduced. +func pythonMessageListPrefix(msgs []schema.Message, n int) string { + var b strings.Builder + b.WriteByte('[') + for i, m := range msgs { + if i > 0 { + b.WriteString(", ") + } + b.WriteString(langchainMessageRepr(m)) + if len([]rune(b.String())) >= n { + break + } + } + b.WriteByte(']') + return truncateRunes(b.String(), n) +} + +// langchainMessageRepr renders one message the way langchain_core does. +func langchainMessageRepr(m schema.Message) string { + switch m.Role { + case schema.System: + return "SystemMessage(content=" + harness.PyStringRepr(m.Content) + ", additional_kwargs={}, response_metadata={})" + case schema.User: + return "HumanMessage(content=" + harness.PyStringRepr(m.Content) + ", additional_kwargs={}, response_metadata={})" + case schema.Assistant: + return "AIMessage(content=" + harness.PyStringRepr(m.Content) + + ", additional_kwargs={}, response_metadata={}, tool_calls=" + pyToolCallsRepr(m.ToolCalls) + + ", invalid_tool_calls=[])" + case schema.Tool: + return "ToolMessage(content=" + harness.PyStringRepr(m.Content) + ", tool_call_id=" + harness.PyStringRepr(m.ToolCallID) + ")" + default: + // Roles the session never produces (function/…): keep the shape close to + // langchain's without inventing fields. + return "BaseMessage(content=" + harness.PyStringRepr(m.Content) + ", additional_kwargs={}, response_metadata={})" + } +} + +// pyToolCallsRepr renders AIMessage.tool_calls the way langchain normalizes them: +// [{'name': …, 'args': {…}, 'id': …, 'type': 'tool_call'}, …]. eino stores the +// arguments as the raw JSON string, so they are decoded back into a value before +// rendering — langchain's repr shows the dict, not its JSON text. +func pyToolCallsRepr(calls []schema.ToolCall) string { + if len(calls) == 0 { + return "[]" + } + parts := make([]string, 0, len(calls)) + for _, c := range calls { + var args any = map[string]any{} + if raw := strings.TrimSpace(c.Function.Arguments); raw != "" { + if err := json.Unmarshal([]byte(raw), &args); err != nil { + args = raw + } + } + parts = append(parts, fmt.Sprintf("{'name': %s, 'args': %s, 'id': %s, 'type': 'tool_call'}", + harness.PyStringRepr(c.Function.Name), harness.PyValueRepr(args), harness.PyStringRepr(c.ID))) + } + return "[" + strings.Join(parts, ", ") + "]" +} + +// The Python repr helpers (harness.PyValueRepr / harness.PyStringRepr) live in +// the harness package: initialize_state needs the same semantics to parse the +// slot table, so there is one implementation. + +func strengthOf(v harness.Variable) float64 { + if v.CandidateStrength == nil { + return 0.0 + } + return *v.CandidateStrength +} + +// Fallback-draft synthesis tuning (Python _compose_fallback_draft). +const ( + // draftChunkCap / draftChunkChars: the evidence budget (Python: [:16], 1200). + draftChunkCap = 16 + draftChunkChars = 1200 + // draftFallbackChars: raw-evidence fallback when no model is available or the + // call fails (Python: evidence[:4000]). + draftFallbackChars = 4000 + // draftMaxChars caps the composed draft (Python: (ans or evidence)[:6000]). + draftMaxChars = 6000 +) + +// ComposeFallbackDraft mirrors Python _compose_fallback_draft: an +// intermediate draft synthesized from the snippet pool when a research pass +// produced no report (budget exhaustion). +// +// This is an LLM call, not a concatenation. The draft is what the +// sufficient-context agent reviews and what later lands in PreSummary as +// "Research findings (authoritative — use these facts verbatim)", so Python +// asks the model for a specific shape: +// +// - the FOUND facts, stated plainly; +// - a final "MISSING:" line naming what is still unknown. +// +// The MISSING line is load-bearing: it is what tells the next round (and the +// final answer) which unknowns remain. A plain list of truncated snippets +// cannot express it. +func ComposeFallbackDraft(ctx context.Context, deps RAGTools, st *AgenticState) string { + // Nil-safe: the draft node runs on every round, including a state whose KB + // was never populated (Python reaches the same fields through getattr, which + // tolerates a missing pool). + if st == nil || st.KB == nil || len(st.KB.Chunks) == 0 { + return "" + } + + // Python 1478: strongest evidence first — the pool is in insertion order, so + // sort by similarity/score before spending the 16-slot budget on it. + chunks := chunksByRelevance(st.KB.Chunks) + + // Python 1566-1568: "[i] text" joined by "\n", 1-indexed, 16 chunks x 1200 + // chars. Empty chunk text still produces its "[i] " line — Python does not + // skip or trim. + var ev strings.Builder + n := min(len(chunks), draftChunkCap) + for i := 0; i < n; i++ { + if ctx.Err() != nil { + break + } + if i > 0 { + ev.WriteString("\n") + } + fmt.Fprintf(&ev, "[%d] %s", i+1, truncateRunes(harness.ChunkTextOf(chunks[i]), draftChunkChars)) + } + evidence := ev.String() + if evidence == "" { + return "" + } + + // Python 1571-1573: no model -> the raw evidence, capped at 4000. + mdl := deps.Model // Python _base_chat_mdl(tools): the innermost chat model. + if mdl == nil { + return truncateRunes(evidence, draftFallbackChars) + } + + // _compose_fallback_draft injects the latest research_feedback as a "focus", and + // that state field is vestigial upstream: it is declared and initialised to + // [] but never appended anywhere in the Python tree, so the + // focus is always empty. The Go port therefore carries no feedback field — + // populating one would invent behaviour Python does not have. + // + // The prompt is Python's, verbatim (_compose_fallback_draft): the FOUND list plus a final + // "MISSING:" line is what gives the SCA precise gaps. + system := "You are a research assistant writing an INTERMEDIATE DRAFT toward answering the user's " + + "question, using ONLY the retrieved evidence snippets below.\n" + + "Requirements:\n" + + "1. First list concrete FACTS FOUND in the snippets (exact numbers, dates, names preserved).\n" + + "2. Then output a line starting with 'MISSING:' naming precisely which part(s) of the " + + "question the snippets do NOT answer yet.\n" + + "3. No conclusions beyond the evidence; no general knowledge.\n" + + "Keep it under 250 words." + if containsNonASCII(st.Question) { + // _compose_fallback_draft — appended directly, with no separator. + system += "Write your draft in the same language as the question." + } + + user := "Question: " + st.Question + "\n\nRetrieved evidence:\n" + evidence + + reply, err := mdl.Complete(ctx, []schema.Message{ + *schema.SystemMessage(system), + *schema.UserMessage(user), + }, nil) + if err != nil { + // Python 1599-1601: a failed composition degrades to the raw evidence + // (capped at 4000, unlike the composed draft's 6000). + _LOG.Printf("[Draft] fallback composition failed; using snippet text: %v", err) + return truncateRunes(evidence, draftFallbackChars) + } + answer := "" + if reply != nil { + answer = strings.TrimSpace(reply.Content) + } + if answer == "" { + answer = evidence + } + // Python 1598: (ans or evidence)[:6000]. + return truncateRunes(answer, draftMaxChars) +} + +// chunksByRelevance mirrors Python's draft ordering: strongest evidence +// first, so the fixed 16-slot budget is spent on the best snippets rather than +// on whatever happened to be inserted first. +func chunksByRelevance(chunks []map[string]any) []map[string]any { + out := make([]map[string]any, len(chunks)) + copy(out, chunks) + sort.SliceStable(out, func(i, j int) bool { + return chunkScore(out[i]) > chunkScore(out[j]) + }) + return out +} + +func chunkScore(c map[string]any) float64 { + // _compose_fallback_draft — `float(c.get("similarity") or c.get("score") or 0.0)`: a + // falsy similarity (0.0 or missing) falls through to score. + for _, k := range []string{"similarity", "score"} { + if v, ok := toFloat(c[k]); ok && v != 0 { + return v + } + } + return 0.0 +} + +// containsNonASCII mirrors Python's language check: a question carrying +// non-ASCII characters is answered in its own language. +func containsNonASCII(s string) bool { + for _, r := range s { + if r > unicode.MaxASCII { + return true + } + } + return false +} + +// NaiveRAG mirrors Python _naive_rag: answer with one retrieve pass +// and no agentic graph at all. +// +// Used when the thinking mode is unrecognised — instead of failing the request +// (the label comes from user input) this degrades to plain retrieval plus one +// composed answer. +// +// Python is an async generator that yields the answer; Go returns it whole, so +// this mirrors the contract, not the streaming shape. +// +// The composition itself lives in ComposeNaiveAnswer, which mirrors +// Python lines 1555-1568 (fixed short prompt, flat "[i] content" evidence over +// the first 8 chunks at 1500 chars, message_fit_in, temperature 0.3, and the +// raw evidence as the failure fallback). +func NaiveRAG(ctx context.Context, deps RAGTools, req harness.RunRequest, kb *harness.Kbinfos, resp *RunResponse, logger *log.Logger) { + if logger == nil { + logger = _LOG + } + question := strings.TrimSpace(req.Question) + + logger.Printf("[Naive RAG] single-pass retrieval for question_len=%d", len(question)) + + // Python 1533: tools.retrieve(question) — one PLAIN pass. Unlike runDirect + // (low mode) this extracts no weighted keywords and expands no compiled + // structure: naive is deliberately plain retrieval, and a failure degrades + // to "no evidence" rather than erroring. + var chunks []map[string]any + if question != "" { + // Python calls tools.retrieve(question), which reads its full config off + // the tools instance — including rank_feature. Projecting only a subset + // here would silently drop that tuning for the naive path. + var aggs []map[string]any + chunks, aggs = harness.RetrieveSearch(ctx, + searchDepsFor(ctx, deps, req, req.DatasetIDs, req.TenantID, kb, logger), + harness.SearchParams{ + Question: question, + TopN: req.TopN, + }) + // Python 1543-1553: accumulate onto the shared pool so the composed + // answer can be cited and callers see the same shape as the agentic path. + kb.Merge(chunks, aggs) + } + + // Python 1539-1541: no evidence -> yield the configured empty response. + if len(chunks) == 0 { + resp.Answer = deps.EmptyResponse + return + } + + // Python 1555-1568: compose from the flat "[i] content" evidence under the + // fixed short naiveAnswerSystem — NOT FinalAnswerSystem / kb_prompt. This is + // why the naive path must not fall through to composeFinalAnswer. + out := ComposeNaiveAnswer(ctx, AnswerDeps{ + Model: deps.Model, + EmptyResponse: deps.EmptyResponse, + MaxLength: deps.MaxLength, + Logger: logger, + }, chunks, question) + + resp.Answer = out.Answer +} + +// countFilled counts slots holding a candidate. +func countFilled(slotTable harness.State) int { + n := 0 + for _, v := range slotTable.State { + if v.Filled() { + n++ + } + } + return n +} + +// --------------------------------------------------------------------------- +// Graph driver — mirrors Python build_agentic_graph. +// --------------------------------------------------------------------------- + +// BuildAgenticGraph drives the agentic-search loop and returns the terminal state. +// Mirrors Python build_agentic_graph: declare and compile the graph, then invoke +// the runnable; the name follows Python for traceability. +// +// The caller reads the answer from st.KB.PreSummary / st.CollectedAnswer and composes it +// (see Run for the single-shot entry point). +// +// The returned error mirrors run_agentic_rag's holder["error"] — the graph itself +// failed. The state is still returned so the caller can surface whatever the run +// produced; an empty result alone is not a failure. +// +// Activation is EXPLICIT: call this directly, with no init()-based auto-registration. +// This is the agentic planner (medium/high/ultra); the mode dispatch lives in +// RAGTools.Run, and agentic modes register this as the AgenticLoop. +func BuildAgenticGraph(ctx context.Context, deps RAGTools, question, keywords string, maxLoops int, messages []schema.Message) (*AgenticState, error) { + logger := deps.logger() + // formalize_question — the graph starts at formalize_question, which both + // initializes the state and arms the budget, so the budget is NOT set here. + st := NewAgenticState(question, keywords, maxLoops, messages) + if deps.KB != nil { + st.KB = deps.KB + } + spec := harness.ResolveMode(deps.Tools) + enableSCA := spec.EnableSCA + useFanout := spec.UseFanout + scaMaxRounds := spec.SCAMaxRounds + + logger.Printf("[Agentic RAG] Starting research — mode=%s sca=%v fanouts=%v", + spec.Label, enableSCA, useFanout) + + // run_agentic_rag — there is NO whole-graph wall clock. Research stays + // bounded by the per-node timeouts (bounded / PassTimeoutS / SCATimeoutS…), + // the routing guards (MinRoundHeadroomS) and the visit limit; and because + // formalize_answer now composes inside the graph, the answer stream must be + // allowed to run until the model finishes. Go previously capped the whole + // graph at TotalBudgetS+30s, which cut the composition short — that ceiling + // was a Go-only deviation from Python. + + // Prefetch is gated on fan-out, mirroring Python's `use_prefetch = + // use_fanout`. NOTE: the Python comment there claims prefetch is DISABLED, + // but the code still wires it for fan-out modes — behaviour here matches the + // CODE, not the stale comment. + usePrefetch := useFanout + + // run_agentic_rag — LangGraph counts NODE VISITS, not loop iterations: one + // research round is rag_agent → draft → sca = three visits. Counting run + // steps instead would let Go do roughly 3x the work before the guard trips, + // so the counter is kept here and each node adds the visits it costs. + limit := graphRecursionLimit(true, maxLoops) + visits := 0 + + // The graph is declared per run: deps / logger / spec are request-scoped and + // Eino captures them in closures, so a compiled graph cannot be shared + // across requests. The graph is 7 nodes; compilation is validation plus + // channel wiring. + g := compose.NewGraph[*AgenticState, *AgenticState]() + var buildErr error + visit := func(n int) { visits += n } + + addNode := func(name string, fn func(context.Context, *AgenticState) (*AgenticState, error)) { + if buildErr != nil { + return + } + buildErr = g.AddLambdaNode(name, compose.InvokableLambda(fn)) + } + addEdge := func(from, to string) { + if buildErr != nil { + return + } + buildErr = g.AddEdge(from, to) + } + addBranch := func(from string, cond func(context.Context, *AgenticState) (string, error), ends map[string]bool) { + if buildErr != nil { + return + } + buildErr = g.AddBranch(from, compose.NewGraphBranch(cond, ends)) + } + // guard routes to "stop" once the visit budget is spent. Python's guard + // ABORTS the run (LangGraph raises GraphRecursionError) rather than running + // formalize_answer, so the stop node reports the failure instead of composing + // an answer from whatever partial research the round had gathered. + guard := func(next string) string { + if visits >= limit { + return "stop" + } + return next + } + + addNode("formalize_question", func(ctx context.Context, s *AgenticState) (*AgenticState, error) { + visit(1) + formalizeQuestionNode(ctx, deps, s, logger) + return s, nil + }) + addNode("planner", func(ctx context.Context, s *AgenticState) (*AgenticState, error) { + visit(1) + plannerNode(ctx, deps, s, logger) + return s, nil + }) + addNode("prefetch", func(ctx context.Context, s *AgenticState) (*AgenticState, error) { + visit(1) + // firstRound is always true here: prefetch is only reachable from the + // planner, which itself only runs on the first pass. + prefetchNode(ctx, deps, s, logger, true) + return s, nil + }) + // rag_agent is one research round: rag_agent → draft → sca (build_agentic_graph). + // Both the first pass and the rewrite-driven passes enter this node. + addNode("rag_agent", func(ctx context.Context, s *AgenticState) (*AgenticState, error) { + visit(agenticRoundVisits) + ragAgentNode(ctx, deps, s, logger) + draftNode(ctx, deps, s, logger) + scaNode(ctx, deps, s, logger) + return s, nil + }) + addNode("query_rewrite", func(ctx context.Context, s *AgenticState) (*AgenticState, error) { + visit(1) + queryRewriteNode(ctx, deps, s, logger) + return s, nil + }) + addNode("formalize_answer", func(c context.Context, s *AgenticState) (*AgenticState, error) { + visit(1) + formalizeAnswerNode(c, deps, s, logger) + return s, nil + }) + // stop is the visit-budget backstop. Python has no graceful stop: LangGraph + // raises GraphRecursionError, which run_agentic_rag records as a graph failure + // (run_agentic_rag) and only then, when the run also produced nothing, surfaces as + // graphFailureFallback. Returning the state as-is instead let Go + // compose a partial answer where Python reports the internal error, so the + // error is raised here and the caller drops the state (see below). + addNode("stop", func(_ context.Context, s *AgenticState) (*AgenticState, error) { + logger.Printf("[Agentic RAG] stopping after %d node visits (Python recursion_limit=%d)", visits, limit) + return s, fmt.Errorf("graph recursion limit reached after %d node visits", visits) + }) + + // START → formalize_question. + addEdge(compose.START, "formalize_question") + addEdge("prefetch", "rag_agent") + addEdge("formalize_answer", compose.END) + addEdge("stop", compose.END) + + // build_agentic_graph — onward to the planner, or straight to rag_agent when + // fan-out is off (medium). + addBranch("formalize_question", func(_ context.Context, _ *AgenticState) (string, error) { + if useFanout { + return guard("planner"), nil + } + return guard("rag_agent"), nil + }, map[string]bool{"stop": true, "planner": true, "rag_agent": true}) + + addBranch("planner", func(_ context.Context, _ *AgenticState) (string, error) { + if usePrefetch { + return guard("prefetch"), nil + } + return guard("rag_agent"), nil + }, map[string]bool{"stop": true, "prefetch": true, "rag_agent": true}) + + addBranch("prefetch", func(_ context.Context, _ *AgenticState) (string, error) { + return guard("rag_agent"), nil + }, map[string]bool{"stop": true, "rag_agent": true}) + + addBranch("rag_agent", func(_ context.Context, s *AgenticState) (string, error) { + return guard(agenticNodeName(routeSCA(s, enableSCA, scaMaxRounds))), nil + }, map[string]bool{"stop": true, "query_rewrite": true, "formalize_answer": true}) + + addBranch("query_rewrite", func(_ context.Context, s *AgenticState) (string, error) { + return guard(agenticNodeName(routeRewrite(s, scaMaxRounds, logger))), nil + }, map[string]bool{"stop": true, "rag_agent": true, "formalize_answer": true}) + + if buildErr != nil { + logger.Printf("[Agentic RAG] graph build failed: %v", buildErr) + return st, buildErr + } + + runnable, err := g.Compile(ctx, + compose.WithGraphName("agentic_rag"), + // The visit counter above is the authoritative guard (Python counts node + // visits); this is only a backstop so a mis-wired cycle cannot spin. + compose.WithMaxRunSteps(limit*2+16), + ) + if err != nil { + logger.Printf("[Agentic RAG] graph compile failed: %v", err) + return st, err + } + out, err := runnable.Invoke(ctx, st) + if err != nil { + logger.Printf("[Agentic RAG] graph run failed: %v", err) + // run_agentic_rag — a failed run keeps NO state: holder["state"] is only + // assigned on success, so everything downstream sees an empty state + // (`state = holder.get("state") or {}`, run_agentic_rag). Handing back the mutated + // state would surface slots/draft Python discards. + return &AgenticState{}, err + } + if out != nil { + return out, nil + } + return st, nil +} + +// agenticNodeName maps the routing predicates' node ids onto the Eino graph's +// node keys. +func agenticNodeName(n agenticNode) string { + switch n { + case nodeQueryRewrite: + return "query_rewrite" + case nodeRagAgentFirst, nodeRagAgentLoop: + return "rag_agent" + default: + return "formalize_answer" + } +} + +// --------------------------------------------------------------------------- +// Explicit wiring into the RAGTools.Run loop registration (mirrors Python +// dialog_service.py instantiating RAGTools and driving the agentic graph). +// +// The Python module has NO init()/auto-registration: the caller constructs the +// object and invokes it. Go mirrors that — callers activate the full +// medium/high/ultra pipeline by explicitly registering this loop: +// +// advanced_rag.SetAgenticLoop(advanced_rag.NewAgenticLoop()) +// +// Without registration, RAGTools.Run falls back to a single action session for +// agentic modes (see Run). +// --------------------------------------------------------------------------- + +// NewAgenticLoop returns the outer agentic loop adapter for RAGTools.Run. It +// converts the RAGTools run config into the planner's state and maps the result +// back onto the +// RunResponse. +func NewAgenticLoop() AgenticLoop { + return func(ctx context.Context, deps RAGTools, req harness.RunRequest, kb *harness.Kbinfos, resp *RunResponse, logger *log.Logger) { + if logger == nil { + logger = _LOG + } + if deps.Model == nil { + logger.Printf("[Agentic RAG] no model configured for mode %q; degrading to a direct search", resp.Mode.Label) + runDirectFallback(ctx, deps, req, kb, logger) + return + } + + // The loop needs an executor for its programmatic fan-out fetches, built + // from the same retrieval backend the single-session path uses. It must + // project the FULL RAGTools config (Python reads it all off the tools + // instance), otherwise fan-out and action-session retrieval silently + // lose tuning — notably rank_feature (Tagger/KBs). + sd := searchDepsFor(ctx, deps, req, req.DatasetIDs, req.TenantID, kb, logger) + sd.WebSearch = deps.WebSearch + sd.CiteRules = deps.CiteRules + + toolset := &harness.Toolset{ + ThinkingMode: resp.Mode.Label, + // web_search is visible only when the mode exposes it AND a provider + // is actually wired (Python action_session.py:463 discards the tool + // when tools.web_search is None). Advertising it without a provider + // left the model calling a tool that can only return an infra error. + HasWebSearch: resp.Mode.HasTool("web_search") && deps.WebSearch != nil, + DisabledTools: map[string]bool{}, + Exec: harness.NewSearchExecutor(sd, req), + } + + st, runErr := BuildAgenticGraph(ctx, RAGTools{ + Tools: toolset, + Search: sd, // dual-channel fan-out retrieves directly + Model: deps.Model, + ModelName: deps.ModelName, + Prompts: deps.Prompts, + KB: kb, + SCAPrompts: deps.Prompts, + RewritePrompts: deps.Prompts, + MaxLength: deps.MaxLength, + Logger: logger, + // The terminal composition is Python's formalize_answer node body; it + // must reach the graph even though this deps copy is rebuilt here. + Finalize: deps.Finalize, + // Progress is the caller's per-request sink for engine-stage lines + // (Python think_log). Rag already wraps `logger` with thinkLogger so + // tagged logger lines reach the think block; the sink itself is only + // threaded here for callers that re-wrap or inspect it. + Progress: deps.Progress, + }, req.Question, req.Keywords, 3, deps.Messages) + + // run_agentic_rag — a graph exception is recorded separately from + // "research found nothing". The state is still surfaced below: Python only + // swaps in its internal-error message when the failed run ALSO produced + // nothing (run_agentic_rag). + if runErr != nil { + resp.GraphFailed = true + } + + // Surface the loop's outcome on the RunResponse. + resp.Slots = append(resp.Slots, st.SlotTable.State...) + // Research findings: the SCA-reviewed draft. NOTE: this is the research + // draft, NOT the final answer — RAGTools.Run composes the final cited + // answer afterwards from KB.PreSummary (see composeFinalAnswer), exactly + // as Python's formalize_answer node does. + if st.CollectedAnswer != "" { + resp.CollectedAnswer = st.CollectedAnswer + } + resp.Partial = st.PartialAnswer + resp.SearchRounds = st.SearchRounds + resp.Verdict = st.Verdict + // SCAFeedback mirrors agentic_rag.py:902-929 — the body of the + // "[Research status]" note (status hint + hard violations + missing + // claims + confidence) that rag() folds into the answer for EVERY + // non-SUFFICIENT verdict. Rag() appends the trailing "STOP" vs + // "call rag again" sentence based on the consecutive-unanswerable count. + resp.SCAFeedback = scaFeedback(st.SCA, st.Verdict) + // Update the consecutive-unanswerable guardrail (Python + // RAGTools._consecutive_unanswerable, :818) on the shared per-turn + // *RAGCache. Rag() builds deps.Cache before the outer react branch, so + // this counter accumulates across the outer loop's multiple rag() calls + // within a single turn. + recordConsecutiveUnanswerable(deps.Cache, st.Verdict) + } +} + +// recordConsecutiveUnanswerable mirrors Python RAGTools._consecutive_unanswerable +// (agentic_rag.py:818, :921-924): a SUFFICIENT verdict resets the counter, any +// other verdict bumps it. The counter lives on the shared *RAGCache so it +// accumulates across the outer react loop's multiple rag() calls within a single +// turn — which is exactly why Rag() must build deps.Cache before branching into +// the outer loop (otherwise the "STOP calling rag again" guard would never fire). +func recordConsecutiveUnanswerable(cache *RAGCache, verdict string) { + if cache == nil { + return + } + if verdict == VerdictSufficient { + cache.ConsecutiveUnanswerable = 0 + } else { + cache.ConsecutiveUnanswerable++ + } +} + +// graphRecursionLimit mirrors Python run_agentic_rag — the graph aborts +// after this many node visits: 60 for the agentic graph, else +// max(25, max_loops*8). Eino counts run steps, not Python's node visits, so the +// graph keeps its own visit counter and checks it in every branch. +func graphRecursionLimit(agentic bool, maxLoops int) int { + if agentic { + return AgenticRecursionLimit + } + if n := maxLoops * 8; n > lowRecursionLimitBase { + return n + } + return lowRecursionLimitBase +} + +// formalizeQuestionNode is Python's formalize_question node of +// build_agentic_graph. It resolves pronouns and ellipses from the +// conversation into a standalone question plus search keywords, and arms the +// global budget in its return (formalize_question) — so the formalization work itself is NOT +// charged to that budget. +// +// Single-turn input costs no LLM call (Formalize returns early), mirroring +// Python's non-LLM fast path. +func formalizeQuestionNode(ctx context.Context, deps RAGTools, st *AgenticState, logger *log.Logger) { + // formalize_question — the budget is armed as the node returns, i.e. after any + // formalization work has already happened. + st.Deadline = time.Now().Add(time.Duration(TotalBudgetS * float64(time.Second))) + + if len(st.Messages) == 0 || deps.Model == nil { + return + } + fdeps := harness.SessionDeps{Model: deps.Model, Prompts: deps.Prompts} + q, kw := Formalize(ctx, fdeps, st.Messages, deps.MaxLength) + if q != "" { + st.Question = q + } + if kw != "" && st.Keywords == "" { + st.Keywords = kw + } + if logger != nil && q != "" { + logger.Printf("[Agentic RAG] formalized the question into %q", trunc(q, 80)) + } +} + +// formalizeQuestion is Python's formalize_question node of build_agentic_graph. +// and build_low_graph: resolve pronouns and ellipses from the conversation into +// a standalone question plus search keywords. Single-turn input costs no LLM call +// (Formalize returns early), and the graph budget is NOT started here — Python sets +// that deadline in the node's return (formalize_question), so this cost is not charged to it. The +// low graph has no scheduler in Go, so it runs as a plain step of BuildLowGraph rather +// than as a scheduled node. _naive_rag has no such node. +func formalizeQuestion(ctx context.Context, deps RAGTools, req *harness.RunRequest, logger *log.Logger) { + if len(deps.Messages) == 0 || deps.Model == nil { + return + } + fdeps := harness.SessionDeps{Model: deps.Model, Prompts: deps.Prompts} + if deps.Stats != nil { + deps.Stats.RecordCall("formalize") + } + q, kw := Formalize(ctx, fdeps, deps.Messages, deps.MaxLength) + if deps.Stats != nil && q == "" { + deps.Stats.RecordFailed("formalize") + } + if q != "" { + req.Question = q + } + if kw != "" && req.Keywords == "" { + req.Keywords = kw + } + if logger != nil && q != "" { + logger.Printf("[Agentic RAG] formalized the question into %q", trunc(q, 80)) + } +} + +// RunAgenticRAG mirrors Python run_agentic_rag: the mode +// dispatch plus execution of the selected pipeline. It is the counterpart of +// RAGTools.rag (Go: Run), which owns the conversation-level concerns around it — cache +// lookup, the effective question, attachments and storing the result. +// +// The dispatch is run_agentic_rag: +// +// mode is NAIVE → _naive_rag (plain retrieval) +// mode.Agentic → build_agentic_graph (medium / high / ultra) +// else → build_low_graph (low: formalize → direct_search) +// +// Formalization belongs to the graphs, not to Run: Python makes it the first node of +// build_agentic_graph and build_low_graph, while _naive_rag has +// none, so each path below runs it where its Python counterpart does. +func RunAgenticRAG(ctx context.Context, deps RAGTools, req harness.RunRequest, sd harness.SearchDeps, kb *harness.Kbinfos, resp *RunResponse, logger *log.Logger, spec harness.ModeSpec) { + // The graph budget (formalize_question, mirrored by NewAgenticState) is NOT started + // here: Python sets that deadline inside the first node's return, i.e. after + // formalization has run, so formalization is not charged to it. + switch { + case spec.Agentic: + // build_agentic_graph — formalization is the graph's first node, + // so it happens inside runAgentic. + runAgentic(ctx, deps, req, sd, kb, resp, logger) + case spec.Label != "naive": + // build_low_graph — formalize → direct_search. + if err := BuildLowGraph(ctx, deps, req, sd, kb, resp, logger); err != nil { + // run_agentic_rag — a graph exception is recorded separately from + // "research found nothing"; the fallback below only fires when the + // run also produced nothing. + resp.GraphFailed = true + } + default: + // _naive_rag: no formalize node, a plain retrieve with no + // keyword extraction, and its own composition (flat "[i] content" + // evidence under naiveAnswerSystem). It must therefore not fall + // through to composeFinalAnswer. + NaiveRAG(ctx, deps, req, kb, resp, logger) + } + + // run_agentic_rag — only when research produced NOTHING *and* the graph + // itself failed. An empty result without a failure is not an error: that is + // EmptyResponse's job, and overwriting it here would hide the real reason. + if resp.GraphFailed && resp.Answer == "" && len(resp.Slots) == 0 { + logger.Printf("[Agentic RAG] research failed without producing anything") + resp.Answer = graphFailureFallback + } +} + +// runDirectFallback retrieves once when no model is configured: the loop cannot +// plan, research, or review without one, so the caller still gets evidence +// rather than an error. +func runDirectFallback(ctx context.Context, deps RAGTools, req harness.RunRequest, kb *harness.Kbinfos, logger *log.Logger) { + chunks, aggs := harness.HybridSearch(ctx, + searchDepsFor(ctx, deps, req, req.DatasetIDs, req.TenantID, kb, logger), + harness.SearchParams{ + Question: req.Question, + Keywords: req.Keywords, + UseCompiled: req.UseCompiled, + TopN: req.TopN, + // Mirrors Python RAGTools.retrieve. + Channel: harness.ChannelRetrieve, + }) + kb.Merge(chunks, aggs) +} + +// Final answer composition (the graph's last node). +// +// Mirrors Python agentic_rag_graph.py: +// - _compose_answer_from_evidence +// - _naive_rag +// +// Every thinking mode ends here: it turns the gathered evidence into a grounded, +// cited answer in the user's language. The evidence-block and citation-rule +// prompts it renders (generator.py kb_prompt/citation_prompt) live in +// internal/rag/prompts; the system-prompt texts live in the harness package +// (report_prompt.go, mirroring report_prompt.py). + +const ( + // evidenceBudgetTokens is the token ceiling of the evidence block + // (Python agentic_rag._EVIDENCE_BUDGET_TOKENS). + evidenceBudgetTokens = 8000 + // citeChunkCap caps chunks rendered as citation reference + // (Python _CITE_CHUNK_CAP). + citeChunkCap = 6 + // answerTimeoutS bounds the answer-composition call. + answerTimeoutS = 150.0 + // naiveEvidenceChunkCap caps evidence chunks in the naive path + // (Python: chunks[:8]). + naiveEvidenceChunkCap = 8 + // naiveEvidenceCharCap caps each naive evidence chunk + // (Python: [:1500]). + naiveEvidenceCharCap = 1500 + // answerErrorFallback mirrors Python's stream-failure message. + answerErrorFallback = "I'm sorry, I encountered an error while composing the answer." + // graphFailureFallback mirrors Python run_agentic_rag's last-resort message + // (run_agentic_rag), used only when the graph failed AND produced nothing. + graphFailureFallback = "I couldn't complete the search due to an internal error." + // AgenticRecursionLimit mirrors Python run_agentic_rag for the agentic + // graph: the maximum number of node visits before the graph aborts. Go has + // no graph runtime, so the loop counts its own node visits against it. + AgenticRecursionLimit = 60 + // agenticRoundVisits is the number of LangGraph node visits one research + // round costs: rag_agent → draft → sca (build_agentic_graph). + agenticRoundVisits = 3 + // lowRecursionLimitBase is the floor of Python's `max(25, max_loops * 8)` + // (run_agentic_rag) for the non-agentic graph. + lowRecursionLimitBase = 25 +) + +// FinalAnswerSystem and PartialAnswerPreamble are defined in the harness +// package (harness/report_prompt.go), mirroring +// rag/advanced_rag/harness/prompts/report_prompt.py. They are re-used here via +// the harness import rather than duplicated. + +var reAnswerThink = regexp.MustCompile(`(?s)^.*`) + +// AnswerDeps are the dependencies of ComposeAnswer. +type AnswerDeps struct { + // Model drives the composition call. + Model harness.SessionModel + // CiteRules overrides DEFAULT_CITE_RULES. Empty uses the default. + CiteRules string + // SystemPrompt is the dialog-level UI configuration (Python + // tools.system_prompt). Appended AFTER the agentic contract — see the + // precedence note in composeSystem. + SystemPrompt string + // EmptyResponse is returned verbatim when there is no evidence + // (Python tools.empty_response), skipping the LLM entirely. + EmptyResponse string + // MaxTokens caps the evidence block. <=0 uses evidenceBudgetTokens. + MaxTokens int + // MaxLength is the chat model's context window (Python + // tools.chat_mdl.max_length). It bounds message_fit_in; <=0 falls back to + // chat.EffectiveContextLength's 8192 default. + MaxLength int + // Logger is optional; nil uses the default logger. + Logger *log.Logger + // UserImages are the vision-gated base64 data URIs (Python image_attachments) + // that survive gateImageAttachments. Mirroring Python's direct async_chat + // fallback — which is called with the original multimodal messages — they are + // attached to the final-answer user message so the compose model sees the + // images even on the non-outer path. Empty for text-only models / no images. + UserImages []string +} + +// AnswerResult is the composed final answer. +type AnswerResult struct { + // Answer is the composed text. + Answer string + // Partial is true when the underlying research ended without a satisfying + // verdict; the answer carries a partial-information preamble. + Partial bool + // NoEvidence is true when composition was skipped for lack of evidence. + NoEvidence bool + // Failed is true when the composition call failed and the fallback message + // was returned. + Failed bool +} + +// ComposeAnswer mirrors Python _compose_answer_from_evidence: turn the gathered +// evidence into a grounded, cited answer. +// +// Behaviour, in Python's order: +// 1. no evidence + configured empty_response → return it WITHOUT calling the LLM; +// 2. rank chunks by similarity, keep the top citeChunkCap as citation reference; +// 3. render the evidence block under the token budget (kb_prompt); +// 4. prepend the fact-preserving pre_summary (the SCA-reviewed draft) when set; +// 5. call the model with FINAL_ANSWER_SYSTEM + the composed user content. +func ComposeAnswer(ctx context.Context, deps AnswerDeps, kb *harness.Kbinfos, question string, partial, abstain bool) AnswerResult { + return ComposeAnswerWith(ctx, deps, kb, question, partial, abstain, false) +} + +// multimodalUserMsg builds a user message that carries the given text plus any +// vision-gated image data URIs (mirroring Python async_chat receiving the +// original multimodal messages). Returns nil when there is no text and no +// images, so callers fall back to schema.UserMessage. Used by the non-outer +// final-answer path so the compose model sees images even without the outer +// react loop. +func multimodalUserMsg(text string, images []string) *schema.Message { + parts := make([]schema.MessageInputPart, 0, 1+len(images)) + if text != "" { + parts = append(parts, schema.MessageInputPart{Type: schema.ChatMessagePartTypeText, Text: text}) + } + for i := range images { + uri := images[i] + parts = append(parts, schema.MessageInputPart{ + Type: schema.ChatMessagePartTypeImageURL, + Image: &schema.MessageInputImage{MessagePartCommon: schema.MessagePartCommon{URL: &uri}}, + }) + } + if len(parts) == 0 { + return nil + } + return &schema.Message{Role: schema.User, UserInputMultiContent: parts} +} + +// ComposeAnswerWith is ComposeAnswer with Python's third no-evidence term: Python +// computes `no_evidence = abstain or empty_result or not chunks` (_compose_answer_from_evidence) and uses it +// both for the empty_response short circuit and for the degradation instructions in +// the prompt. The extra `emptyResult` term is the agentic loop's own "nothing was +// found" signal, distinct from "we abstained" and from "the pool happens to be empty". +func ComposeAnswerWith(ctx context.Context, deps AnswerDeps, kb *harness.Kbinfos, question string, partial, abstain, emptyResult bool) AnswerResult { + logger := deps.Logger + if logger == nil { + logger = _LOG + } + chunks := []map[string]any{} + if kb != nil { + chunks = kb.Chunks + } + note := "" + if partial { + note = " — partial answer, some gaps remain" + } else if abstain { + note = " — not enough evidence to answer" + } + logger.Printf("[Composing the answer] Writing the final answer to %q from %d gathered passage(s)%s.", + trunc(question, 60), len(chunks), note) + + // 1. No-evidence short circuit. + // _compose_answer_from_evidence: no_evidence = abstain or empty_result or not chunks. + noEvidence := abstain || emptyResult || len(chunks) == 0 + if noEvidence && deps.EmptyResponse != "" { + logger.Printf("[Composing the answer] No supporting evidence was found; returning the configured empty response without calling the answer model.") + return AnswerResult{Answer: deps.EmptyResponse, NoEvidence: true} + } + if deps.Model == nil { + return AnswerResult{Answer: "", Failed: true, NoEvidence: len(chunks) == 0} + } + + // 2. Build the prompt: ranked evidence under its token budget, plus the + // question and any research findings. + preSummary := "" + if kb != nil { + preSummary = kb.PreSummary + } + prompt := deps.answerPromptWithEvidence(kb, question, partial, noEvidence) + + // 3. Call the model. + callCtx, cancel := context.WithTimeout(ctx, deadlineToDuration(answerTimeoutS)) + defer cancel() + + logger.Printf("[Formalize][pre_summary] question=%q pre_summary_len=%d evidence_len=%d", + trunc(question, 160), len(preSummary), len(prompt.user)) + + userMsg := schema.UserMessage(prompt.user) + if len(deps.UserImages) > 0 { + // Mirror Python's direct async_chat fallback, which is called with the + // original multimodal messages: attach the vision-gated images to the + // final-answer user message so the compose model can see them. + userMsg = multimodalUserMsg(prompt.user, deps.UserImages) + } + reply, err := deps.Model.Complete(callCtx, []schema.Message{ + *schema.SystemMessage(prompt.system), + *userMsg, + }, nil) + if err != nil { + logger.Printf("[Composing the answer] composition failed: %v", err) + return AnswerResult{Answer: answerErrorFallback, Failed: true} + } + return AnswerResult{Answer: cleanAnswer(reply.Content), Partial: partial} +} + +// answerPrompt is the terminal node's input: the ranked evidence under its token +// budget plus the question and any research findings. Shared by the one-shot and +// the streaming compose so both render exactly the same prompt. +type answerPrompt struct { + system string + user string + partial bool +} + +// answerTargetContract mirrors Python's static answer-target guardrail +// (_compose_answer_from_evidence). It costs no LLM call — it is injected into +// every final-answer prompt. +// +// The EXTREME-SELECTION clause is the load-bearing part: for +// shortest/longest/smallest/largest/most/least/最 questions, a model otherwise +// tends to name the most common or first-listed candidate. Naming the clause +// explicitly forces a comparison against the evidence instead. +const answerTargetContract = "Answer Target Contract:\n" + + "Final answer must directly satisfy the user's top-level who/what request. " + + "Use bridge entities only as clues, and verify any proposed answer against " + + "the evidence. In EXTREME-SELECTION questions (shortest/longest/smallest/" + + "largest/most/least/最), compare the alternatives in the evidence and name " + + "the EXTREME one rather than the most common or first-listed.\n" + +// noEvidenceWithSummary / noEvidenceWithoutSummary mirror Python's +// no-evidence instructions (_compose_answer_from_evidence). Unlike the empty_response short circuit +// they apply when composition still goes ahead (no empty_response configured), +// and they tell the model to degrade honestly rather than guess. +const ( + noEvidenceWithSummary = "The retrieved passages are limited. Answer as completely as possible " + + "from the Research Summary below, using the known facts; where a " + + "specific number/entity is missing, say what is known and avoid " + + "flatly refusing to answer.\n" + noEvidenceWithoutSummary = "No supporting evidence was retrieved. State clearly that the available " + + "sources are insufficient, and do not answer from general knowledge.\n" +) + +func (d AnswerDeps) answerPrompt(kb *harness.Kbinfos, question string, partial bool) answerPrompt { + return d.answerPromptWithEvidence(kb, question, partial, false) +} + +// answerPromptWithEvidence renders Python's parts list (_compose_answer_from_evidence) in order: +// question, answer-target contract, optional no-evidence instruction, research +// summary, partial preamble, evidence. The no-evidence flag is Python's +// `no_evidence = abstain or empty_result or not chunks` (_compose_answer_from_evidence). +func (d AnswerDeps) answerPromptWithEvidence(kb *harness.Kbinfos, question string, partial, noEvidence bool) answerPrompt { + chunks := []map[string]any{} + if kb != nil { + chunks = kb.Chunks + } + ranked := rankBySimilarity(chunks) + citeChunks := ranked + if len(citeChunks) > citeChunkCap { + citeChunks = citeChunks[:citeChunkCap] + } + if len(citeChunks) == 0 { + citeChunks = chunks + } + maxTokens := d.MaxTokens + if maxTokens <= 0 { + maxTokens = evidenceBudgetTokens + } + evidence := strings.Join(prompts.KBPrompt(citeChunks, maxTokens), "\n") + + summary := "" + if kb != nil { + summary = strings.TrimSpace(kb.PreSummary) + } + + parts := []string{fmt.Sprintf("Question:\n%s\n", question)} + + // _compose_answer_from_evidence: the static guardrail, always present. + parts = append(parts, answerTargetContract) + + // _compose_answer_from_evidence: how to degrade when there is no evidence (reached only + // when no empty_response short-circuited the call). + if noEvidence { + if summary != "" { + parts = append(parts, noEvidenceWithSummary) + } else { + parts = append(parts, noEvidenceWithoutSummary) + } + } + + if summary != "" { + parts = append(parts, fmt.Sprintf("Research Summary (primary evidence):\n%s\n", summary)) + } + // _compose_answer_from_evidence: the partial preamble goes HERE — after the research + // summary and before the evidence — not at the very front of the prompt. + if partial { + parts = append(parts, fmt.Sprintf("%s\n", harness.PartialAnswerPreamble)) + } + parts = append(parts, fmt.Sprintf("Evidence:\n%s", evidence)) + + return answerPrompt{system: d.composeSystem(), user: strings.Join(parts, "\n"), partial: partial} +} + +// ComposeAnswerStream is ComposeAnswer for models that can emit incrementally: +// it renders the same prompt, forwards each piece as it arrives, and returns the +// assembled answer. A streaming failure is returned so the caller can fall back +// to the one-shot call. +func ComposeAnswerStream(ctx context.Context, deps AnswerDeps, model harness.StreamingSessionModel, kb *harness.Kbinfos, question string, partial bool, onDelta func(delta string, isThink bool) error) (AnswerResult, error) { + logger := deps.Logger + if logger == nil { + logger = _LOG + } + if model == nil { + return AnswerResult{Answer: "", Failed: true}, nil + } + chunks := []map[string]any{} + if kb != nil { + chunks = kb.Chunks + } + // Same no-evidence rule as the one-shot path (_compose_answer_from_evidence): the prompt must carry + // the degradation instruction even when no empty_response short-circuits. + noEvidence := len(chunks) == 0 + prompt := deps.answerPromptWithEvidence(kb, question, partial, noEvidence) + if noEvidence && deps.EmptyResponse != "" { + return AnswerResult{Answer: deps.EmptyResponse, NoEvidence: true}, nil + } + + callCtx, cancel := context.WithTimeout(ctx, deadlineToDuration(answerTimeoutS)) + defer cancel() + + userMsg := schema.UserMessage(prompt.user) + if len(deps.UserImages) > 0 { + // Same as ComposeAnswerWith: attach the vision-gated images so the + // compose model sees them on the non-outer path. + userMsg = multimodalUserMsg(prompt.user, deps.UserImages) + } + reply, err := model.StreamComplete(callCtx, []schema.Message{ + *schema.SystemMessage(prompt.system), + *userMsg, + }, nil, func(delta string, isThink bool) error { + if onDelta == nil || delta == "" { + return nil + } + return onDelta(delta, isThink) + }) + if err != nil { + logger.Printf("[Composing the answer] streaming composition failed: %v", err) + return AnswerResult{Answer: "", Failed: true}, err + } + if reply == nil { + return AnswerResult{Answer: "", Failed: true}, errors.New("streaming composition returned no reply") + } + return AnswerResult{Answer: cleanAnswer(reply.Content), Partial: partial}, nil +} + +// composeSystem builds the system prompt, mirroring Python's precedence rules. +// +// LANGUAGE IS DELIBERATELY LEFT OVERRIDABLE: "answer in the same language as the +// question" is exactly the rule a user setting "answer in English" means to +// replace, so it must not be listed as protected. What stays protected is the +// evidence contract: citing sources, answering the exact attribute asked for, +// and never substituting prior knowledge for missing evidence. +func (d AnswerDeps) composeSystem() string { + // Mirror Python compose_system: the citation rules are citation_prompt + // (citation_prompt.md) with an optional user-defined override + // (RAGConfig.CiteRules / user_defined_prompts). + rules := prompts.CitationPrompt(d.CiteRules) + system := strings.ReplaceAll(harness.FinalAnswerSystem, "{cite_rules}", rules) + if sp := strings.TrimSpace(d.SystemPrompt); sp != "" { + system = fmt.Sprintf("%s\n\n# Assistant configuration (set by the user)\n%s\n\nFollow the configuration above for language, tone, style, format and any other presentational instruction, including where it overrides the language rule above. Where it conflicts with the citation rules, attribute fidelity, or the requirement to answer only from the provided evidence, those three take precedence.", + system, sp) + } + return system +} + +// cleanAnswer strips a leading thinking preamble from the composed answer. +func cleanAnswer(s string) string { + return strings.TrimSpace(reAnswerThink.ReplaceAllString(s, "")) +} + +// rankBySimilarity mirrors Python's sorted(..., key=similarity or score, +// reverse=True). Stable, so equal-scored chunks keep their retrieval order. +func rankBySimilarity(chunks []map[string]any) []map[string]any { + out := append([]map[string]any(nil), chunks...) + sort.SliceStable(out, func(i, j int) bool { + return similarityOf(out[i]) > similarityOf(out[j]) + }) + return out +} + +func similarityOf(c map[string]any) float64 { + if v, ok := toFloat(c["similarity"]); ok { + return v + } + if v, ok := toFloat(c["score"]); ok { + return v + } + return 0.0 +} + +// naiveAnswerSystem is the fixed system prompt Python _naive_rag sends +// (_compose_fallback_draft). It is deliberately NOT FinalAnswerSystem: the naive path is a +// plain single-pass answer and carries neither the citation contract nor the +// partial-answer preamble the agentic modes compose. +const naiveAnswerSystem = "Answer the question using ONLY the numbered evidence below. Cite with [n] markers. If the evidence does not answer it, say so plainly — do not use outside knowledge." + +// naiveAnswerTemperature is the sampling temperature of the naive answer call +// (Python 1556: answer_conf = gen_conf or {"temperature": 0.3}). Go's RunRequest +// carries no per-call generation config, so this is always the no-gen_conf +// branch. +const naiveAnswerTemperature = 0.3 + +// naiveFallbackChars caps the evidence echoed back when the naive answer call +// fails (Python 1568: evidence[:4000]). +const naiveFallbackChars = 4000 + +// ComposeNaiveAnswer mirrors Python _naive_rag's answer composition +// (lines 1555-1568): one retrieve pass, then a single composed answer over the +// top chunks. +// +// Unlike ComposeAnswer this does NOT use kb_prompt and does NOT use +// FinalAnswerSystem — Python renders a flat "[i] content" list truncated to the +// first 1500 chars of each chunk, capped at 8 chunks, and sends it under a +// short fixed system prompt. +// +// The messages are run through message_fit_in (Python 1561) against +// deps.MaxLength before the call. +func ComposeNaiveAnswer(ctx context.Context, deps AnswerDeps, chunks []map[string]any, question string) AnswerResult { + logger := deps.Logger + if logger == nil { + logger = _LOG + } + if len(chunks) == 0 { + if deps.EmptyResponse != "" { + return AnswerResult{Answer: deps.EmptyResponse, NoEvidence: true} + } + return AnswerResult{NoEvidence: true} + } + + // Python 1555: a flat "[i] content" list over the first 8 chunks, each + // truncated to 1500 characters. + var parts []string + for i, c := range chunks { + if i >= naiveEvidenceChunkCap { + break + } + content := harness.ChunkTextOf(c) + if len(content) > naiveEvidenceCharCap { + content = content[:naiveEvidenceCharCap] + } + parts = append(parts, fmt.Sprintf("[%d] %s", i+1, content)) + } + evidence := strings.Join(parts, "\n\n") + fallback := evidence + if len(fallback) > naiveFallbackChars { + fallback = fallback[:naiveFallbackChars] + } + + if deps.Model == nil { + // Python has no model guard here, but calling a nil model would panic; + // return the evidence the same way a failed call does. + return AnswerResult{Answer: fallback, Failed: true} + } + + callCtx, cancel := context.WithTimeout(ctx, deadlineToDuration(answerTimeoutS)) + defer cancel() + + // Python 1561: message_fit_in(form_message(system, user), max_length). + fitted, fitErr := chat.FitMessages(naiveAnswerSystem, []schema.Message{ + *schema.UserMessage(fmt.Sprintf("Question: %s\n\nEvidence:\n%s", question, evidence)), + }, deps.MaxLength) + if fitErr != "" { + logger.Printf("[Naive RAG] prompt fitting failed: %s", fitErr) + return AnswerResult{Answer: fallback, Failed: true} + } + + // Python 1562: async_chat(msg[0]["content"], msg[1:], answer_conf) — the + // fitted system text is the first entry and the rest is the history. + // Splitting explicitly keeps the call shaped like Python's, even though + // Go's Complete takes the two parts re-joined. + system := naiveAnswerSystem + history := fitted + if len(fitted) > 0 && fitted[0].Role == schema.System { + system = fitted[0].Content + history = fitted[1:] + } + messages := make([]schema.Message, 0, 1+len(history)) + messages = append(messages, *schema.SystemMessage(system)) + messages = append(messages, history...) + + reply, err := modelWithTemperature(deps.Model, naiveAnswerTemperature).Complete(callCtx, messages, nil) + if err != nil { + // Python 1567-1568: on failure yield the raw evidence, not an error. + logger.Printf("[Naive RAG] composition failed: %v", err) + return AnswerResult{Answer: fallback, Failed: true} + } + // Python 1565: str(ans or "").strip() or empty_response — an empty answer + // degrades to the configured empty response. + answer := cleanAnswer(reply.Content) + if answer == "" { + answer = deps.EmptyResponse + } + return AnswerResult{Answer: answer} +} + +// modelWithTemperature returns a view of mdl that samples at temp, falling back +// to the model's default when it does not support per-call temperature. +func modelWithTemperature(mdl harness.SessionModel, temp float64) harness.SessionModel { + if tm, ok := mdl.(harness.TemperatureModel); ok { + return &temperatureModel{mdl: tm, temp: temp} + } + return mdl +} + +type temperatureModel struct { + mdl harness.TemperatureModel + temp float64 +} + +func (m *temperatureModel) Complete(ctx context.Context, messages []schema.Message, tools []harness.ToolSpec) (*harness.ModelReply, error) { + return m.mdl.CompleteWithTemperature(ctx, messages, tools, m.temp) +} diff --git a/internal/rag/advanced_rag/agentic_rag_graph_test.go b/internal/rag/advanced_rag/agentic_rag_graph_test.go new file mode 100644 index 00000000000..1646037bd2c --- /dev/null +++ b/internal/rag/advanced_rag/agentic_rag_graph_test.go @@ -0,0 +1,2523 @@ +package advanced_rag + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "log" + "os" + "strings" + "sync" + "testing" + "time" + + "github.com/cloudwego/eino/compose" + "github.com/cloudwego/eino/schema" + "ragflow/internal/entity" + "ragflow/internal/rag/advanced_rag/harness" +) + +// --------------------------------------------------------------------------- +// Test doubles +// --------------------------------------------------------------------------- + +// scriptedModel answers with a fixed set of canned replies, one per call, +// looping on the last if exhausted. It satisfies harness.SessionModel. seen +// records every message slice handed to Complete, for assertions on retry turns. +type scriptedModel struct { + mu sync.Mutex + replies []string + idx int + seen [][]schema.Message +} + +func (m *scriptedModel) push(reply string) { + m.replies = append(m.replies, reply) +} + +func (m *scriptedModel) Complete(ctx context.Context, msgs []schema.Message, _ []harness.ToolSpec) (*harness.ModelReply, error) { + if ctx.Err() != nil { + return nil, ctx.Err() + } + m.mu.Lock() + defer m.mu.Unlock() + m.seen = append(m.seen, msgs) + if len(m.replies) == 0 { + return &harness.ModelReply{Content: ""}, nil + } + r := m.replies[m.idx] + if m.idx < len(m.replies)-1 { + m.idx++ + } + return &harness.ModelReply{Content: r}, nil +} + +// promptRoutedModel answers by inspecting the prompt instead of by call order, +// so a test survives the graph adding or reordering node LLM calls. The SCA call +// returns insufficient on its FIRST invocation and sufficient afterwards, which +// is what drives one rewrite round. +type promptRoutedModel struct { + mu sync.Mutex + scaSeen int +} + +func (m *promptRoutedModel) Complete(ctx context.Context, msgs []schema.Message, _ []harness.ToolSpec) (*harness.ModelReply, error) { + if ctx.Err() != nil { + return nil, ctx.Err() + } + m.mu.Lock() + defer m.mu.Unlock() + var text strings.Builder + for _, msg := range msgs { + text.WriteString(msg.Content) + } + switch { + case strings.Contains(text.String(), "Break the user's question into 2 to 5"): + return &harness.ModelReply{Content: `{"fanouts": ["when built", "where located"]}`}, nil + case strings.Contains(text.String(), "research strategist"): + return &harness.ModelReply{Content: `{"slots":[{"id":0,"type":"aspect","question":"when built","clues":["1865"]},{"id":1,"type":"aspect","question":"where located","clues":["geneva"]}], "first_queries":["when built","where located"]}`}, nil + case strings.Contains(text.String(), "Sufficient Context Agent"): + m.scaSeen++ + if m.scaSeen == 1 { + return &harness.ModelReply{Content: `{"is_sufficient": false, "score": 0.2, "contradictions": [], "reasoning": "missing the builder", "sub_queries": [{"missing_fact": "who built it", "search_hint": "builder", "satisfied": false}], "claims": {}}`}, nil + } + return &harness.ModelReply{Content: `{"is_sufficient": true, "score": 0.9, "contradictions": [], "reasoning": "ok", "claims": {}}`}, nil + case strings.Contains(text.String(), "Query Rewriter"): + return &harness.ModelReply{Content: `{"queries": [{"query": "who built it"}]}`}, nil + default: + return &harness.ModelReply{Content: "Built in 1865, in Geneva."}, nil + } +} + +// stubExecutor is a deterministic ToolExecutor recording every call. +type stubExecutor struct { + mu sync.Mutex + calls []string + responses map[string]harness.ToolOutcome +} + +func newStubExecutor() *stubExecutor { + return &stubExecutor{responses: map[string]harness.ToolOutcome{}} +} + +func (e *stubExecutor) add(name, payload string, status string) { + e.responses[name] = harness.ToolOutcome{ + Status: status, + Payload: []any{payload}, + } +} + +func (e *stubExecutor) Execute(ctx context.Context, name string, args map[string]any) (harness.ToolOutcome, error) { + e.mu.Lock() + defer e.mu.Unlock() + e.calls = append(e.calls, name) + if o, ok := e.responses[name]; ok { + return o, nil + } + return harness.ToolOutcome{Status: harness.StatusOK, Payload: []any{"{}"}}, nil +} + +func newToolset(exec *stubExecutor) *harness.Toolset { + return &harness.Toolset{ + ThinkingMode: "high", + HasWebSearch: true, + DisabledTools: map[string]bool{}, + Exec: exec, + } +} + +// countingRetriever is a no-op retriever recording the requested top-N. It +// satisfies harness.Retriever (= tools.Retriever). +type countingRetriever struct { + mu sync.Mutex + topN int +} + +func (r *countingRetriever) Retrieve(_ context.Context, req harness.RetrieveRequest) ([]map[string]any, error) { + r.mu.Lock() + r.topN = req.TopN + r.mu.Unlock() + return []map[string]any{{"doc_id": "d1", "docnm_kwd": "doc1", "content": "Saint Lawrence River; 14 April 1865; 9 December 2019."}}, nil +} + +// --------------------------------------------------------------------------- +// Unit tests for the routing / helpers (no init() required). +// --------------------------------------------------------------------------- + +func TestRouteSCAAlwaysCloseoutOnNoProgress(t *testing.T) { + // NoProgress is the hard stop: regardless of SCA enablement or verdict, the + // loop must close out rather than spin another round. + st := &AgenticState{Verdict: VerdictInsufficient, MaxLoops: 3, NoProgress: true} + if n := routeSCA(st, true, 3); n != nodeFormalizeAnswer { + t.Fatalf("SCA on: expected formalize on no-progress, got %v", n) + } + if n := routeSCA(st, false, 3); n != nodeFormalizeAnswer { + t.Fatalf("SCA off: expected formalize on no-progress, got %v", n) + } +} + +func TestRouteSCADisabledSCAClosesOut(t *testing.T) { + // With SCA disabled the single research pass' verdict is informational; we + // never start a rewrite round. + st := &AgenticState{Verdict: VerdictInsufficient, MaxLoops: 3} + if n := routeSCA(st, false, 3); n != nodeFormalizeAnswer { + t.Fatalf("expected formalize when SCA disabled, got %v", n) + } +} + +func TestRouteSCAInsufficientStartsRewrite(t *testing.T) { + // Sufficient verdict closes out. + st := &AgenticState{Verdict: VerdictSufficient, MaxLoops: 3} + if n := routeSCA(st, true, 3); n != nodeFormalizeAnswer { + t.Fatalf("expected formalize on sufficient, got %v", n) + } + // Insufficient + rounds under cap + headroom remaining => rewrite. + st = &AgenticState{Verdict: VerdictInsufficient, MaxLoops: 3, SearchRounds: 0} + st.Deadline = time.Now().Add(120 * time.Second) // 120s remaining >> MinRoundHeadroomS + if n := routeSCA(st, true, 3); n != nodeQueryRewrite { + t.Fatalf("expected rewrite on insufficient+headroom, got %v", n) + } + // At max rounds => formalize. + st = &AgenticState{Verdict: VerdictInsufficient, MaxLoops: 3, SearchRounds: 3} + st.Deadline = time.Now().Add(120 * time.Second) + if n := routeSCA(st, true, 3); n != nodeFormalizeAnswer { + t.Fatalf("expected formalize at max rounds, got %v", n) + } +} + +func TestSelectSCAViewIdentity(t *testing.T) { + chunks := make([]map[string]any, 0, 80) + for i := 0; i < 80; i++ { + chunks = append(chunks, map[string]any{ + "chunk_id": fmt.Sprintf("c%d", i), + "content": fmt.Sprintf("the quick brown fox %d", i), + "similarity": 1.0 - float64(i)/100.0, + }) + } + v1, id1 := SelectSCAView(chunks, []string{"quick", "brown"}) + if len(v1) != SCAViewCap { + t.Fatalf("expected view cap %d, got %d", SCAViewCap, len(v1)) + } + // Same inputs => same identity (no Process-randomised hash). + _, id2 := SelectSCAView(chunks, []string{"quick", "brown"}) + if id1 != id2 { + t.Fatalf("view identity should be deterministic, got %q vs %q", id1, id2) + } + // An enlarged pool with the SAME selected ids keeps the same identity — this + // is exactly the "review view unchanged" early-exit signal. + more := append(chunks, map[string]any{"chunk_id": "extra", "content": "unrelated tail", "similarity": 0.0}) + _, id3 := SelectSCAView(more, []string{"quick", "brown"}) + if id1 != id3 { + t.Fatalf("adding non-selected chunks should NOT change the view identity, got %q vs %q", id1, id3) + } +} + +func TestMergeSlotPatchAdoptsStronger(t *testing.T) { + strong := 0.95 + base := harness.NewState([]harness.Variable{ + {ID: 0, Type: "aspect", Candidate: strPtr("base"), CandidateStrength: &strong}, + }, 0, nil) + // A weak branch (0.30) must NOT downgrade the strong base. + weak := 0.30 + branch := harness.NewState([]harness.Variable{ + {ID: 0, Type: "aspect", Candidate: strPtr("weak-candidate"), CandidateStrength: &weak}, + }, 1, nil) + merged := MergeSlotPatch(base, branch) + // A weak branch does not downgrade the strong base, AND produces no change + // at all — MergeSlotPatch returns nil to signal "no new patch". + if merged != nil { + t.Fatalf("weak branch over strong base should yield NO change (nil patch), got %+v", merged) + } + + // A stronger branch wins. + stronger := 0.99 + branch2 := harness.NewState([]harness.Variable{ + {ID: 0, Type: "aspect", Candidate: strPtr("strong-candidate"), CandidateStrength: &stronger}, + }, 1, nil) + merged2 := MergeSlotPatch(base, branch2) + if merged2 == nil { + t.Fatal("expected a merge result") + } + if got := merged2.State[0].Candidate; got == nil || *got != "strong-candidate" { + t.Fatalf("strong branch should upgrade, got %v", got) + } +} + +func TestMergeSlotPatchNoChangeReturnsNil(t *testing.T) { + base := harness.NewState([]harness.Variable{ + {ID: 0, Type: "aspect", Candidate: strPtr("same")}, + }, 0, nil) + branch := harness.NewState([]harness.Variable{ + {ID: 0, Type: "aspect", Candidate: strPtr("same")}, + }, 1, nil) + if m := MergeSlotPatch(base, branch); m != nil { + t.Fatalf("identical patch should return nil, got %+v", m) + } +} + +func TestExpandFanoutsParsesJSON(t *testing.T) { + mdl := &scriptedModel{} + mdl.push(`{"fanouts": ["who discovered it", "when was it discovered"]}`) + got := ExpandFanouts(context.Background(), RAGTools{Model: mdl}, "What was discovered and by whom?") + if len(got) != 2 { + t.Fatalf("expected 2 fan-outs, got %v", got) + } + if got[0] != "who discovered it" || got[1] != "when was it discovered" { + t.Fatalf("unexpected fan-outs: %v", got) + } +} + +func TestExpandFanoutsFallbackOnBadJSON(t *testing.T) { + mdl := &scriptedModel{} + mdl.push("I cannot break this down.") + got := ExpandFanouts(context.Background(), RAGTools{Model: mdl}, "single question") + // Bad JSON: the loop falls back to line-splitting the model's reply, which + // yields the reply itself (single line), not the raw question. + if len(got) != 1 || got[0] != "I cannot break this down." { + t.Fatalf("expected line-split fallback, got %v", got) + } +} + +func TestExpandFanoutsNilModelReturnsQuestion(t *testing.T) { + got := ExpandFanouts(context.Background(), RAGTools{}, "single question") + if len(got) != 1 || got[0] != "single question" { + t.Fatalf("expected raw question when no model, got %v", got) + } +} + +// TestExpandFanoutsRetriesWithStrictJSON covers Python's retry (:478-488): a +// prose answer must not be line-split into fan-outs (it poisons the slot table), +// so the prompt is re-sent with the strict JSON instruction instead. +func TestExpandFanoutsRetriesWithStrictJSON(t *testing.T) { + mdl := &scriptedModel{} + mdl.push("The woman was **Rocio Restrepo**.\nSupporting sources: https://example.com") + mdl.push(`{"fanouts": ["who was she", "when did it happen"]}`) + got := ExpandFanouts(context.Background(), RAGTools{Model: mdl}, "Who was she?") + if len(got) != 2 || got[0] != "who was she" || got[1] != "when did it happen" { + t.Fatalf("expected the strict-retry fan-outs, got %v", got) + } + if len(mdl.seen) != 2 { + t.Fatalf("model calls = %d, want 2 (original + one strict retry)", len(mdl.seen)) + } +} + +// TestExpandFanoutsDropsAnswerLikeEntries covers _fanout_looks_like_query: a +// fan-out is used verbatim as a retrieval query and as the slot hint, so an +// answered fact must never survive into either. +func TestExpandFanoutsDropsAnswerLikeEntries(t *testing.T) { + mdl := &scriptedModel{} + mdl.push(`{"fanouts": ["who won the medal", "The winner was **Ann** according to the citation", "when was the race"]}`) + got := ExpandFanouts(context.Background(), RAGTools{Model: mdl}, "Who won the medal and when?") + if len(got) != 2 || got[0] != "who won the medal" || got[1] != "when was the race" { + t.Fatalf("expected the answer-like entry to be dropped, got %v", got) + } +} + +func TestFanoutLooksLikeQueryBounds(t *testing.T) { + // The loose (non-JSON) path holds a tighter bound than the JSON path. + long := "who opened the new library downtown last spring and who paid for the building" + if !fanoutLooksLikeQuery(long, false) { + t.Errorf("JSON-path fan-out %q should pass the %d-word bound", long, fanoutMaxWords) + } + if fanoutLooksLikeQuery(long, true) { + t.Errorf("loose fan-out %q should exceed the %d-word bound", long, fanoutLooseMaxWords) + } + // A question keeps its full length even on the loose path. + if !fanoutLooksLikeQuery(long+"?", true) { + t.Error("a question-shaped line should survive the loose bound") + } + if fanoutLooksLikeQuery(strings.Repeat("word ", fanoutMaxWords+2), false) { + t.Errorf("fan-outs over %d words must be rejected", fanoutMaxWords) + } + if fanoutLooksLikeQuery(strings.Repeat("a", fanoutMaxChars+1), false) { + t.Errorf("fan-outs over %d chars must be rejected", fanoutMaxChars) + } +} + +// TestRenderSlotDraftMatchesPythonFormat pins Python _render_slot_draft +// (agentic_rag_graph.py:1278-1326) exactly: the collected answer leads with its +// evidence metadata, a resolved slot carries strength + terminal + evidence ids + +// its discovered-clue tail, and an unresolved slot is rendered as +// "NOT RESOLVED ()". This text is the SCA's claim context, so a +// different shape changes what the reviewer sees. +func TestRenderSlotDraftMatchesPythonFormat(t *testing.T) { + strong := 0.9 + st := harness.NewState([]harness.Variable{ + { + ID: 0, + Type: "aspect", + Candidate: strPtr("answer A"), + CandidateStrength: &strong, + DiscoveredClues: []string{"clue one", "clue two"}, + }, + {ID: 1, Type: "aspect", QuestionClues: []string{"who opened it?"}}, + }, 0, nil) + evidence := map[string]SlotEvidence{ + "0": {EvidenceIDs: []string{"c1", "c2"}, TerminalType: "state"}, + } + + draft := RenderSlotDraft(st, "the collected answer", evidence) + want := "Candidate answer: the collected answer\n" + + "\n" + + "- slot 0 [aspect]: answer A (strength=0.90) [terminal=state, evidence_ids=['c1', 'c2']] — clue one; clue two\n" + + "- slot 1 [aspect]: NOT RESOLVED (who opened it?)" + if draft != want { + t.Fatalf("draft = %q\nwant %q", draft, want) + } +} + +// TestSelectSCAViewPrefersScoreWhenSimilarityIsZero pins Python +// _select_sca_view:140 (`float(c.get("similarity") or c.get("score") or 0.0)`): +// a similarity of 0.0 is FALSY, so the score must be used instead. The +// presence-based read ranked such a chunk last instead of first. +func TestSelectSCAViewPrefersScoreWhenSimilarityIsZero(t *testing.T) { + chunks := []map[string]any{ + {"chunk_id": "zero-sim", "content": "irrelevant", "similarity": 0.0, "score": 0.9}, + {"chunk_id": "half", "content": "irrelevant", "similarity": 0.5}, + } + view, _ := SelectSCAView(chunks, nil) + if len(view) != 2 { + t.Fatalf("view size = %d, want 2", len(view)) + } + if got := harness.ChunkIDOf(view[0]); got != "zero-sim" { + t.Errorf("first chunk = %q, want zero-sim (score 0.9 must beat similarity 0.5)", got) + } +} + +// TestComposeFallbackDraftMatchesPythonPrompt pins the draft prompt of Python +// _compose_fallback_draft (:1585-1598) byte for byte: the FOUND/MISSING +// instructions, the "Retrieved evidence:" label, the "\n"-joined numbered +// snippets, and the language clause appended without a separator. +func TestComposeFallbackDraftMatchesPythonPrompt(t *testing.T) { + mdl := &fakeModel{replies: []*harness.ModelReply{{Content: "FOUND: x\nMISSING: none"}}} + st := &AgenticState{ + Question: "谁开的?", + KB: &harness.Kbinfos{Chunks: []map[string]any{{"content_with_weight": "证据一"}}}, + } + if got := ComposeFallbackDraft(context.Background(), RAGTools{Model: mdl}, st); got != "FOUND: x\nMISSING: none" { + t.Fatalf("draft = %q", got) + } + if len(mdl.messages) != 2 { + t.Fatalf("model received %d message(s), want system+user", len(mdl.messages)) + } + wantSystem := "You are a research assistant writing an INTERMEDIATE DRAFT toward answering the user's " + + "question, using ONLY the retrieved evidence snippets below.\n" + + "Requirements:\n" + + "1. First list concrete FACTS FOUND in the snippets (exact numbers, dates, names preserved).\n" + + "2. Then output a line starting with 'MISSING:' naming precisely which part(s) of the " + + "question the snippets do NOT answer yet.\n" + + "3. No conclusions beyond the evidence; no general knowledge.\n" + + "Keep it under 250 words." + + "Write your draft in the same language as the question." + if got := mdl.messages[0].Content; got != wantSystem { + t.Errorf("system prompt = %q\nwant %q", got, wantSystem) + } + wantUser := "Question: 谁开的?\n\nRetrieved evidence:\n[1] 证据一" + if got := mdl.messages[1].Content; got != wantUser { + t.Errorf("user prompt = %q\nwant %q", got, wantUser) + } +} + +// TestBuildSlotTableKeepsAllFanoutsOnFailure pins Python _build_slot_table's +// exception branch (:1347-1350): when initialize_state fails, first_queries is +// the FULL fan-out list — the [:3] cap only applies to the empty-root path +// (:1360). Losing the list made the first prefetch narrower than Python's. +func TestBuildSlotTableKeepsAllFanoutsOnFailure(t *testing.T) { + fanouts := []string{"q1", "q2", "q3", "q4", "q5"} + // No model → initialize_state cannot run, so the failure path is taken. + root, first := BuildSlotTable(context.Background(), harness.SessionDeps{}, "raw question", fanouts, 60) + if len(root.State) != 4 { + t.Fatalf("fallback slots = %d, want 4 (Python queries[:4])", len(root.State)) + } + if len(first) != len(fanouts) { + t.Errorf("firstQueries = %v, want the full fan-out list on the failure path", first) + } +} + +// TestBuildSlotTableFallsBackOnSpentBudget pins the planner's deadline +// (Python agentic_rag_graph.py:917, `lambda: _remaining_s(state) - 15.0`): the +// value is NOT floored, so once the round budget is spent the decomposition times +// out at once and the table falls back to the planner fan-outs. +func TestBuildSlotTableFallsBackOnSpentBudget(t *testing.T) { + mdl := &fakeModel{replies: []*harness.ModelReply{ + {Content: `{"slots":[{"id":0,"type":"aspect","clues":["a"]}]}`}, + }} + fanouts := []string{"f1", "f2"} + root, first := BuildSlotTable(context.Background(), harness.SessionDeps{Model: mdl}, "q", fanouts, -15) + if len(root.State) != len(fanouts) { + t.Fatalf("slots = %d, want the %d fan-out fallback slots", len(root.State), len(fanouts)) + } + if mdl.calls != 0 { + t.Errorf("model called %d time(s); a spent budget must not reach the provider", mdl.calls) + } + if len(first) != len(fanouts) { + t.Errorf("firstQueries = %v, want %v", first, fanouts) + } +} + +// TestBuildSlotTableFallsBackWhenIDIsNotAnInteger covers the end-to-end effect of +// the strict parser: Python's int(s["id"]) raises, _build_slot_table catches it +// and rebuilds the table from the planner fan-outs. +func TestBuildSlotTableFallsBackWhenIDIsNotAnInteger(t *testing.T) { + fanouts := []string{"q1", "q2"} + deps := harness.SessionDeps{Model: &fakeModel{replies: []*harness.ModelReply{ + {Content: `{"slots":[{"id":"abc","type":"aspect","clues":["a"]}]}`}, + }}} + root, first := BuildSlotTable(context.Background(), deps, "raw question", fanouts, 60) + if len(root.State) != len(fanouts) { + t.Fatalf("slots = %d, want the %d fan-out fallback slots", len(root.State), len(fanouts)) + } + for i, v := range root.State { + if v.Type != "aspect" || len(v.QuestionClues) != 1 || v.QuestionClues[0] != fanouts[i] { + t.Errorf("slot %d = %+v, want aspect/%s", i, v, fanouts[i]) + } + } + if len(first) != len(fanouts) { + t.Errorf("firstQueries = %v, want %v", first, fanouts) + } +} + +// TestPythonMessageListPrefixMatchesLangchain pins the ledger's q fallback +// (Python _run_slot_research_pass:1446 `(r.found_answer or str(r.messages))[:80]`). +// The expectation is the byte-exact output of the installed langchain_core: +// +// >>> str([SystemMessage(content='You are a slot-filling research agent.\n' +// ... 'Direction: who opened it?')])[:80] +// "[SystemMessage(content='You are a slot-filling research agent.\\nDirection: who o" +func TestPythonMessageListPrefixMatchesLangchain(t *testing.T) { + msgs := []schema.Message{ + *schema.SystemMessage("You are a slot-filling research agent.\nDirection: who opened it?"), + *schema.UserMessage("Direction: who opened it?\n\nState:\n- slot 0 [aspect]: NOT RESOLVED"), + } + want := "[SystemMessage(content='You are a slot-filling research agent.\\nDirection: who o" + if got := pythonMessageListPrefix(msgs, 80); got != want { + t.Errorf("prefix = %q\nwant %q", got, want) + } + + // The full (untruncated) repr must match langchain's field list, including the + // normalized tool_call dict and the ToolMessage shape. + full := []schema.Message{ + *schema.SystemMessage("sys"), + *schema.UserMessage("usr"), + *schema.AssistantMessage("", []schema.ToolCall{{ + ID: "call_0", + Type: "function", + Function: schema.FunctionCall{ + Name: "retrieve", + Arguments: `{"query":"who opened it?"}`, + }, + }}), + *schema.ToolMessage(`{"passages": []}`, "call_0"), + } + wantFull := "[SystemMessage(content='sys', additional_kwargs={}, response_metadata={}), " + + "HumanMessage(content='usr', additional_kwargs={}, response_metadata={}), " + + "AIMessage(content='', additional_kwargs={}, response_metadata={}, " + + "tool_calls=[{'name': 'retrieve', 'args': {'query': 'who opened it?'}, 'id': 'call_0', 'type': 'tool_call'}], " + + "invalid_tool_calls=[]), " + + `ToolMessage(content='{"passages": []}', tool_call_id='call_0')]` + if got := pythonMessageListPrefix(full, 4096); got != wantFull { + t.Errorf("full repr = %q\nwant %q", got, wantFull) + } + if got := pythonMessageListPrefix(nil, 80); got != "[]" { + t.Errorf("nil messages = %q, want []", got) + } +} + +// sessionStubExec answers every tool call with a hit, so a session runs its turns +// without a real retriever. +type sessionStubExec struct{} + +func (sessionStubExec) Execute(_ context.Context, name string, _ map[string]any) (harness.ToolOutcome, error) { + return harness.ToolOutcome{ + Status: harness.StatusOK, + Payload: []any{map[string]any{"kind": name, "content": "hit"}}, + EvidenceIDs: []string{"c-" + name}, + }, nil +} + +// TestRunSlotResearchPassLedgerRecordsSessionHint drives a real round whose +// session produces no terminal answer, and asserts the ledger row still carries a +// query hint (the transcript digest) rather than an empty string. +func TestRunSlotResearchPassLedgerRecordsSessionHint(t *testing.T) { + st := &AgenticState{ + Question: "who opened it?", + SlotTable: harness.NewState([]harness.Variable{ + {ID: 0, Type: "aspect", QuestionClues: []string{"who opened it?"}}, + }, 0, nil), + } + deps := harness.SessionDeps{ + Model: &fakeModel{replies: []*harness.ModelReply{ + {Content: "I could not find any evidence about the opening date in the retrieved passages."}, + }}, + Tools: &harness.Toolset{Exec: sessionStubExec{}}, + KB: &harness.Kbinfos{}, + } + res := RunSlotResearchPass(context.Background(), deps, "who opened it?", st, 60) + if res == nil { + t.Fatal("RunSlotResearchPass returned nil") + } + if len(res.Attempted) == 0 { + t.Fatal("no ledger entry recorded") + } + q, _ := res.Attempted[len(res.Attempted)-1]["q"].(string) + if !strings.HasPrefix(q, "[SystemMessage(content='") { + t.Errorf("ledger q = %q, want the langchain repr prefix (Python :1446)", q) + } +} + +// TestRunSlotResearchPassLogsSlotEvidenceBound pins Python :1459-1463: the round +// reports how many passages each slot's session bound, so a slot whose session +// retrieved nothing is visible in the run log. +func TestRunSlotResearchPassLogsSlotEvidenceBound(t *testing.T) { + var buf bytes.Buffer + orig := _LOG + _LOG = log.New(&buf, "", 0) + defer func() { _LOG = orig }() + + st := &AgenticState{ + Question: "who opened it?", + SlotTable: harness.NewState([]harness.Variable{ + {ID: 0, Type: "aspect", QuestionClues: []string{"who opened it?"}}, + }, 0, nil), + } + deps := harness.SessionDeps{ + Model: &fakeModel{replies: []*harness.ModelReply{{ + Content: "Let me look that up.", + ToolCalls: []harness.ToolCall{ + {ID: "call_0", Name: "retrieve", Args: map[string]any{"query": "who opened it?"}}, + }, + }}}, + Tools: &harness.Toolset{Exec: sessionStubExec{}}, + KB: &harness.Kbinfos{}, + } + if res := RunSlotResearchPass(context.Background(), deps, "who opened it?", st, 60); res == nil { + t.Fatal("RunSlotResearchPass returned nil") + } + if !strings.Contains(buf.String(), "slot evidence bound") { + t.Errorf("missing the per-slot evidence report; log:\n%s", buf.String()) + } +} + +// channelRetriever records the channel each retrieve call belongs to: the exact +// leg is keyword-only (weight 0, top_n=60, query terms folded into the query), +// the semantic-bypass leg has the vector weight on (top_n=30, plain query). +type channelRetriever struct { + weights []float64 + topN []int + queries []string +} + +func (r *channelRetriever) Retrieve(_ context.Context, req harness.RetrieveRequest) ([]map[string]any, error) { + r.weights = append(r.weights, req.KeywordsSimilarityWeight) + r.topN = append(r.topN, req.TopN) + r.queries = append(r.queries, req.Query) + return nil, nil +} + +// TestFanoutSearchIsDualChannel pins the property the single-channel +// implementation could not express: each fan-out issues BOTH a keyword BM25 leg +// (narrowed, wide pool) and a dense semantic leg (narrowing BYPASSED, top_n=30). +// One hybrid call per query cannot distinguish exact from paraphrase-only hits, +// so it cannot apply the semantic quota that keeps the bypass low-precision hits +// from displacing exact ones. +func TestFanoutSearchIsDualChannel(t *testing.T) { + ctx := context.Background() + r := &channelRetriever{} + deps := RAGTools{Search: harness.SearchDeps{Backend: r, KbIDs: []string{"kb1"}, HasEmbedder: true}} + st := &AgenticState{KB: &harness.Kbinfos{}} + FanoutSearch(ctx, deps, st, []string{"when was it built", "where located"}, 8, 60) + + // Two fan-outs x two channels. + if len(r.weights) != 4 { + t.Fatalf("expected 4 retrieve calls (2 fan-outs x 2 channels), got %d", len(r.weights)) + } + for i := 0; i < 4; i += 2 { + // Channel A: keyword-only weight, wide pool, query terms folded in. + if r.weights[i] != 0 { + t.Errorf("fan-out %d channel A: weight = %v, want 0 (BM25 keyword leg)", i/2, r.weights[i]) + } + if r.topN[i] != fanoutBM25TopN { + t.Errorf("fan-out %d channel A: TopN = %d, want %d", i/2, r.topN[i], fanoutBM25TopN) + } + if !strings.Contains(r.queries[i], "built") && !strings.Contains(r.queries[i], "located") { + t.Errorf("fan-out %d channel A: query = %q, want the fan-out query (terms folded in)", i/2, r.queries[i]) + } + // Channel B: vector weight on, top_n=30 (narrowing bypassed). + if r.weights[i+1] <= 0 { + t.Errorf("fan-out %d channel B: weight = %v, want > 0 (semantic bypass leg)", i/2, r.weights[i+1]) + } + if r.topN[i+1] != fanoutHybridTopN { + t.Errorf("fan-out %d channel B: TopN = %d, want %d", i/2, r.topN[i+1], fanoutHybridTopN) + } + } +} + +// TestFanoutSearchPrefersExactOverSemantic pins the admission order across +// FAN-OUTS: every fan-out's exact channel is admitted before any fan-out's +// semantic channel. With room for only two snippets and two fan-outs each +// offering one exact and one semantic hit, the two exact hits must win — a +// single merged channel could not express this preference at all. +func TestFanoutSearchPrefersExactOverSemantic(t *testing.T) { + ctx := context.Background() + r := &fanoutHitRetriever{} + deps := RAGTools{Search: harness.SearchDeps{Backend: r, KbIDs: []string{"kb1"}, HasEmbedder: true}} + st := &AgenticState{KB: &harness.Kbinfos{}} + added := FanoutSearch(ctx, deps, st, []string{"alpha", "beta"}, 8, 2) + + if added != 2 { + t.Fatalf("added = %d, want 2 (the pool's remaining room)", added) + } + ids := make([]string, 0, len(st.KB.Chunks)) + for _, c := range st.KB.Chunks { + ids = append(ids, harness.ChunkIDOf(c)) + } + if len(ids) != 2 || ids[0] != "ex-alpha" || ids[1] != "ex-beta" { + t.Errorf("admitted %v, want the two exact-leg hits [ex-alpha ex-beta]", ids) + } +} + +// fanoutHitRetriever returns one exact hit and one semantic hit per fan-out, +// distinguished by the leg's top_n (30 = semantic bypass, 60 = exact BM25). +type fanoutHitRetriever struct{} + +func (r *fanoutHitRetriever) Retrieve(_ context.Context, req harness.RetrieveRequest) ([]map[string]any, error) { + which := "beta" + if strings.Contains(req.Query, "alpha") { + which = "alpha" + } + if req.TopN == fanoutHybridTopN { + return []map[string]any{ + {"chunk_id": "sem-" + which, "content": "paraphrase only", "doc_name": "semantic"}, + }, nil + } + return []map[string]any{ + {"chunk_id": "ex-" + which, "content": which + " term", "doc_name": "exact"}, + }, nil +} + +// draftModel returns a canned draft and records the prompt it was given. +type draftModel struct { + reply string + err error + lastUser string + lastSys string + calls int +} + +func (m *draftModel) Complete(_ context.Context, msgs []schema.Message, _ []harness.ToolSpec) (*harness.ModelReply, error) { + m.calls++ + for _, msg := range msgs { + switch msg.Role { + case schema.System: + m.lastSys = msg.Content + case schema.User: + m.lastUser = msg.Content + } + } + if m.err != nil { + return nil, m.err + } + return &harness.ModelReply{Content: m.reply}, nil +} + +// TestComposeFallbackDraftUsesLLM pins that the fallback draft is SYNTHESISED, +// not concatenated. The draft feeds PreSummary as "Research findings +// (authoritative)" and is what the SCA reviews, so its shape matters: it must +// ask for a MISSING: line, and a plain list of truncated snippets cannot express +// one. +func TestComposeFallbackDraftUsesLLM(t *testing.T) { + st := &AgenticState{ + Question: "When was it built?", + KB: &harness.Kbinfos{Chunks: []map[string]any{{"content": "It was built in 1874."}}}, + } + mdl := &draftModel{reply: "Built in 1874.\nMISSING: architect"} + got := ComposeFallbackDraft(context.Background(), RAGTools{Model: mdl}, st) + + if mdl.calls != 1 { + t.Fatalf("model calls = %d, want 1 (the draft is synthesised)", mdl.calls) + } + if got != "Built in 1874.\nMISSING: architect" { + t.Fatalf("draft = %q, want the model's synthesis", got) + } + // The system prompt must demand the MISSING line — that is the whole point. + if !strings.Contains(mdl.lastSys, "MISSING:") { + t.Errorf("system = %q, want it to require a MISSING: line", mdl.lastSys) + } + // Python :1479-1481: numbered "[i]" evidence, 1-indexed. + if !strings.Contains(mdl.lastUser, "[1] It was built in 1874.") { + t.Errorf("user = %q, want '[1] ' evidence", mdl.lastUser) + } +} + +// TestComposeFallbackDraftFallsBackToEvidence pins Python :1485-1486 and +// :1512-1514: with no model, or when the call fails, the draft degrades to the +// raw evidence capped at 4000 chars. +func TestComposeFallbackDraftFallsBackToEvidence(t *testing.T) { + st := &AgenticState{ + Question: "When?", + KB: &harness.Kbinfos{Chunks: []map[string]any{{"content": "Evidence body."}}}, + } + if got := ComposeFallbackDraft(context.Background(), RAGTools{}, st); !strings.Contains(got, "Evidence body.") { + t.Errorf("no-model draft = %q, want the raw evidence", got) + } + failing := &draftModel{err: errors.New("boom")} + if got := ComposeFallbackDraft(context.Background(), RAGTools{Model: failing}, st); !strings.Contains(got, "Evidence body.") { + t.Errorf("failed-call draft = %q, want the raw evidence", got) + } +} + +// TestComposeFallbackDraftOrdersByRelevance pins Python :1478: the fixed 16-slot +// budget is spent on the STRONGEST evidence, not on insertion order. +func TestComposeFallbackDraftOrdersByRelevance(t *testing.T) { + st := &AgenticState{ + Question: "When?", + KB: &harness.Kbinfos{Chunks: []map[string]any{ + {"content": "weak hit", "similarity": 0.1}, + {"content": "strong hit", "similarity": 0.9}, + }}, + } + mdl := &draftModel{reply: "draft"} + ComposeFallbackDraft(context.Background(), RAGTools{Model: mdl}, st) + + iWeak := strings.Index(mdl.lastUser, "weak hit") + iStrong := strings.Index(mdl.lastUser, "strong hit") + if iWeak < 0 || iStrong < 0 { + t.Fatalf("evidence missing from prompt: %q", mdl.lastUser) + } + if iStrong > iWeak { + t.Errorf("order = weak@%d strong@%d, want strongest evidence first", iWeak, iStrong) + } +} + +// TestRagCollectsPerPhaseUsage pins the wiring that makes per-phase LLM usage +// measurable: Python builds LLMUsageStats and wraps the chat model at +// agentic_rag.py:266-267, then logs at :930. Without the Go equivalent the +// counting machinery stays inert — CurrentStats(ctx) is nil, so the phase +// markers already in the graph record nothing and even the explicit +// deps.Stats.RecordCall sites are skipped by their nil guard. +func TestRagCollectsPerPhaseUsage(t *testing.T) { + mdl := &countingModel{} + Rag(context.Background(), RAGTools{ + Retriever: &corpusRetriever{}, + Model: mdl, + }, harness.RunRequest{ + Question: "Who created Culdcept?", + ThinkingMode: "high", + DatasetIDs: []string{"kb1"}, + }) + + // The decisive assertion: Rag must bind stats AND a phase onto the context, + // because that is what makes every LLM call beneath attributable. The + // explicit deps.Stats.RecordCall sites fire regardless, so counting calls + // alone would pass even with the binding removed — hence the ctx probe. + if mdl.nilStats > 0 { + t.Errorf("CurrentStats(ctx) was nil on %d of %d calls: Rag did not bind "+ + "stats to the context, so per-phase usage is not collected", mdl.nilStats, mdl.calls) + } + if mdl.calls == 0 { + t.Fatal("the model was never called; the probe proves nothing") + } + if mdl.unknownPhase == mdl.calls { + t.Errorf("every call saw phase \"unknown\": no phase marker reached the " + + "model, so usage cannot be attributed per phase") + } + for p := range mdl.phases { + t.Logf("observed phase: %s", p) + } +} + +// countingModel records what the context looked like at each completion, so the +// test can prove stats and phase were actually bound. +type countingModel struct { + calls int + nilStats int + unknownPhase int + phases map[string]bool +} + +func (m *countingModel) Complete(ctx context.Context, msgs []schema.Message, _ []harness.ToolSpec) (*harness.ModelReply, error) { + m.calls++ + if harness.CurrentStats(ctx) == nil { + m.nilStats++ + } + if p := harness.CurrentPhase(ctx); p == "unknown" { + m.unknownPhase++ + } else { + if m.phases == nil { + m.phases = map[string]bool{} + } + m.phases[p] = true + } + return &harness.ModelReply{Content: "ok"}, nil +} + +// TestSCAFeedbackIsStatusOnly pins Python agentic_rag.py:902-929: the +// "[Research status]" note is the status hint ALONE. Python's verdict dict +// carries only a "status" key, so its missing_claims / hard_violations / +// agent_confidence / feedback segments are always empty — a Go port that +// rendered them (from the separate SCA payload) diverged from upstream and +// invented a "0.00" confidence fallback Python never emits. +func TestSCAFeedbackIsStatusOnly(t *testing.T) { + rich := map[string]any{ + "contradictions": []any{"A says 1874, B says 1881"}, + "confidence": 0.42, + "claims": map[string]any{ + "c1": map[string]any{"grounded": false, "missing_information": []any{ + map[string]any{"what": "the architect"}, + }}, + }, + } + got := scaFeedback(rich, VerdictInsufficient) + if got != "evidence is not yet sufficient" { + t.Errorf("scaFeedback = %q, want the status hint alone", got) + } + // Empty (and thus un-appended) for a SUFFICIENT verdict, per :910. + if got := scaFeedback(rich, VerdictSufficient); got != "" { + t.Errorf("scaFeedback(SUFFICIENT) = %q, want empty", got) + } + // The unused-status fallback mirrors :915. + if got := scaFeedback(rich, "WEIRD"); got != "sufficiency status: WEIRD" { + t.Errorf("scaFeedback(WEIRD) = %q, want the :915 fallback", got) + } +} + +// TestComposeFallbackDraftMirrorsLanguage pins Python :1505-1506: a non-English +// question gets an explicit same-language instruction. +func TestComposeFallbackDraftMirrorsLanguage(t *testing.T) { + st := &AgenticState{ + Question: "它是什么时候建造的?", + KB: &harness.Kbinfos{Chunks: []map[string]any{{"content": "1874年建成。"}}}, + } + mdl := &draftModel{reply: "1874年建成。\nMISSING: 无"} + ComposeFallbackDraft(context.Background(), RAGTools{Model: mdl}, st) + + if !strings.Contains(mdl.lastSys, "same language") { + t.Errorf("system = %q, want the same-language instruction for a CJK question", mdl.lastSys) + } +} + +func TestSCAGapsToRewriteFromSubQueries(t *testing.T) { + sca := map[string]any{ + "sub_queries": []any{ + map[string]any{"sub_query": "q1", "satisfied": true, "missing_fact": "", "search_hint": ""}, + map[string]any{"sub_query": "q2", "satisfied": false, "missing_fact": "the year", "search_hint": "search for dates"}, + }, + } + gaps := SCAGapsToRewrite(sca) + if len(gaps) != 1 { + t.Fatalf("expected 1 gap, got %d: %+v", len(gaps), gaps) + } + if gaps[0].What != "the year" || gaps[0].SearchHint != "search for dates" { + t.Fatalf("unexpected gap: %+v", gaps[0]) + } +} + +func TestSCAGapsToRewriteFallbackToClaims(t *testing.T) { + sca := map[string]any{ + "claims": map[string]any{ + "c1": map[string]any{ + "verdict": "unverified", + "missing_information": []any{ + map[string]any{"what": "population", "search_hint": "demographics"}, + }, + }, + }, + } + gaps := SCAGapsToRewrite(sca) + if len(gaps) != 1 { + t.Fatalf("expected 1 gap from claims fallback, got %d: %+v", len(gaps), gaps) + } + if gaps[0].What != "population" { + t.Fatalf("unexpected gap: %+v", gaps[0]) + } +} + +func TestRunReturnsNonNilState(t *testing.T) { + ctx := context.Background() + mdl := &scriptedModel{} + mdl.push(`{"fanouts": ["when built", "where located"]}`) + mdl.push(`{"slots":[{"id":0,"type":"aspect","question":"when built","clues":["1865"]},{"id":1,"type":"aspect","question":"where located","clues":["geneva"]}], "first_queries":["when built","where located"]}`) + mdl.push("Built in 1865.") + mdl.push("In Geneva.") + mdl.push(`{"is_sufficient": true, "score": 0.9, "contradictions": [], "reasoning": "ok", "claims": {}}`) + + exec := newStubExecutor() + exec.add("search_chunks", `{"hit":[{"doc_id":"d1","docnm_kwd":"doc1","content":"Built 1865, Geneva."}],"doc_aggs":[]}`, harness.StatusOK) + + st, err := BuildAgenticGraph(ctx, RAGTools{ + Model: mdl, + Tools: newToolset(exec), + // The dual-channel fan-out retrieves directly, so it needs the search + // config; without it the prefetch contributes nothing. + Search: harness.SearchDeps{Backend: &corpusRetriever{}, KbIDs: []string{"kb1"}, HasEmbedder: true}, + Logger: log.Default(), + }, "When and where was it built?", "", 3, nil) + if err != nil { + t.Fatalf("BuildAgenticGraph: %v", err) + } + + if st == nil { + t.Fatal("expected a non-nil AgenticState") + } + if strings.TrimSpace(st.Draft) == "" { + t.Fatal("expected a non-empty research draft") + } + if st.NoProgress { + t.Fatal("a completed run should not report NoProgress") + } +} + +// TestAgenticGraphPushesPhaseProgress asserts that the agentic loop forwards +// tagged engine-stage lines to the caller's Progress sink (Python think_log +// counterpart) as it runs — planner, research round, SCA — so a streaming chat +// can show live research progress in the reasoning block. +func TestAgenticGraphPushesPhaseProgress(t *testing.T) { + ctx := context.Background() + mdl := &scriptedModel{} + mdl.push(`{"fanouts": ["when built", "where located"]}`) + mdl.push(`{"slots":[{"id":0,"type":"aspect","question":"when built","clues":["1865"]},{"id":1,"type":"aspect","question":"where located","clues":["geneva"]}], "first_queries":["when built","where located"]}`) + mdl.push("Built in 1865.") + mdl.push("In Geneva.") + mdl.push(`{"is_sufficient": true, "score": 0.9, "contradictions": [], "reasoning": "ok", "claims": {}}`) + + exec := newStubExecutor() + exec.add("search_chunks", `{"hit":[{"doc_id":"d1","docnm_kwd":"doc1","content":"Built 1865, Geneva."}],"doc_aggs":[]}`, harness.StatusOK) + + var lines []string + // Mirror production: Rag wraps the run logger with thinkLogger using the + // same Progress sink. Python has no explicit "push" API at all — the think + // block is fed purely by intercepting tagged logger lines — so everything + // asserted here must come from a logger.Printf. + sink := func(line string) { lines = append(lines, line) } + st, err := BuildAgenticGraph(ctx, RAGTools{ + Model: mdl, + Tools: newToolset(exec), + Search: harness.SearchDeps{Backend: &corpusRetriever{}, KbIDs: []string{"kb1"}, HasEmbedder: true}, + Logger: thinkLogger(log.Default(), sink), + Progress: sink, + }, "When and where was it built?", "", 3, nil) + if err != nil { + t.Fatalf("BuildAgenticGraph: %v", err) + } + + if st == nil { + t.Fatal("expected a non-nil AgenticState") + } + joined := strings.Join(lines, "\n") + // Each stage is announced by its node's own tagged log line (Python parity: + // no separate push), so assert on what the nodes actually log. + for _, want := range []string{ + "[Agentic RAG] Starting research", + "[Planner] Decomposing", + "[RAGAgent] ROUND 1 start", + "[Draft] intermediate draft", + "[SCA] verdict=", + "[Finalize] partial=", + } { + if !strings.Contains(joined, want) { + t.Errorf("think-log lines missing %q; got:\n%s", want, joined) + } + } +} + +// TestAgenticGraphCyclesBackThroughQueryRewrite drives the research loop: the +// SCA returns insufficient once, so the graph must run query_rewrite and re-enter +// rag_agent. The loop is the only cycle in the graph — it is why the graph is +// compiled in Pregel mode (DAG mode rejects cycles). +func TestAgenticGraphCyclesBackThroughQueryRewrite(t *testing.T) { + ctx := context.Background() + mdl := &promptRoutedModel{} + + exec := newStubExecutor() + exec.add("search_chunks", `{"hit":[{"doc_id":"d1","docnm_kwd":"doc1","content":"Built 1865, Geneva."}],"doc_aggs":[]}`, harness.StatusOK) + + var buf bytes.Buffer + var lines []string + sink := func(line string) { lines = append(lines, line) } + st, err := BuildAgenticGraph(ctx, RAGTools{ + Model: mdl, + Tools: newToolset(exec), + Search: harness.SearchDeps{Backend: &corpusRetriever{}, KbIDs: []string{"kb1"}, HasEmbedder: true}, + Logger: thinkLogger(log.New(&buf, "", 0), sink), + Progress: sink, + }, "When and where was it built?", "", 3, nil) + if err != nil { + t.Fatalf("BuildAgenticGraph: %v", err) + } + + if st == nil { + t.Fatal("expected a non-nil AgenticState") + } + joined := strings.Join(lines, "\n") + for _, want := range []string{ + "[QueryRewriter]", + "[RAGAgent] ROUND 2 start", + "[Finalize] partial=", + } { + if !strings.Contains(joined, want) { + t.Errorf("cycle not driven: missing %q; got:\n%s", want, joined) + } + } + // The second research round must actually run: the SCA is only reached again + // through query_rewrite → rag_agent, i.e. the graph's only cycle. + if !strings.Contains(joined, "[SCA] verdict=INSUFFICIENT") { + t.Errorf("expected the first SCA to be insufficient:\n%s", joined) + } +} + +// TestBuildLowGraphRunsFormalizeThenDirectSearch covers the low-mode graph +// (Python build_low_graph:733). It has no planner and no SCA loop, so the only +// observable contract is: formalize rewrites the question, then direct_search +// merges retrieved evidence into the kbinfos. +func TestBuildLowGraphRunsFormalizeThenDirectSearch(t *testing.T) { + ctx := context.Background() + mdl := &scriptedModel{} + mdl.push("When was Culdcept released?") // Formalize + mdl.push(`{"keywords": "Culdcept, released"}`) // weighted keyword extraction + + kb := &harness.Kbinfos{} + sd := harness.SearchDeps{Backend: &corpusRetriever{}, KbIDs: []string{"kb1"}, HasEmbedder: true} + resp := &RunResponse{Mode: harness.ResolveMode(&harness.Toolset{ThinkingMode: "low"})} + req := harness.RunRequest{Question: "when was it made?", TopN: 8} + + var buf bytes.Buffer + BuildLowGraph(ctx, RAGTools{ + Model: mdl, + Messages: []schema.Message{ + {Role: schema.User, Content: "Culdcept was made by OmiyaSoft."}, + {Role: schema.User, Content: "when was it made?"}, + }, + Search: sd, + Logger: log.New(&buf, "", 0), + }, req, sd, kb, resp, log.New(&buf, "", 0)) + + // direct_search ran and merged evidence into the shared kbinfos. + if !kb.HasChunks() { + t.Fatalf("direct_search did not deposit any chunk; log:\n%s", buf.String()) + } + // formalize ran and rewrote the question (the graph's first node). + if !strings.Contains(buf.String(), "[Agentic RAG] formalized the question") { + t.Errorf("formalize_question node did not run; log:\n%s", buf.String()) + } +} + +// lowGraphCountingExpander counts compiled-expansion calls (harness.CompiledExpander). +type lowGraphCountingExpander struct{ calls int } + +func (c *lowGraphCountingExpander) Expand(context.Context, *harness.Kbinfos, string, string, []string) error { + c.calls++ + return nil +} + +// TestBuildLowGraphAlwaysExpandsCompiled mirrors Python low mode: direct.py +// calls hybrid_search(..., use_compiled=True) unconditionally, so the low +// graph's direct_search must expand even when the caller's RunRequest leaves +// UseCompiled false — which production always does. +func TestBuildLowGraphAlwaysExpandsCompiled(t *testing.T) { + ctx := context.Background() + kb := &harness.Kbinfos{} + exp := &lowGraphCountingExpander{} + sd := harness.SearchDeps{Backend: &corpusRetriever{}, KbIDs: []string{"kb1"}, HasEmbedder: true, Expand: exp} + resp := &RunResponse{Mode: harness.ResolveMode(&harness.Toolset{ThinkingMode: "low"})} + req := harness.RunRequest{Question: "when was it made?", TopN: 8, UseCompiled: false} + + var buf bytes.Buffer + if err := BuildLowGraph(ctx, RAGTools{Search: sd}, req, sd, kb, resp, log.New(&buf, "", 0)); err != nil { + t.Fatalf("BuildLowGraph: %v", err) + } + if exp.calls == 0 { + t.Errorf("low mode's direct_search must expand compiled structure "+ + "(Python direct.py use_compiled=True); log:\n%s", buf.String()) + } +} + +// TestFinalizeRunsOnceFromInsideTheGraph locks in the Python parity of the +// terminal node: both graphs end in a formalize_answer node that composes +// (:1214 / :834), so the composition happens INSIDE the graph — and exactly +// once, even though Rag also has a post-graph call for runs that never reach +// the last node. A double composition would overwrite the answer with the +// model's next reply, which is what this test watches for. +func TestFinalizeRunsOnceFromInsideTheGraph(t *testing.T) { + ctx := context.Background() + finalized := 0 + resp := &RunResponse{Mode: harness.ResolveMode(&harness.Toolset{ThinkingMode: "low"})} + kb := &harness.Kbinfos{} + sd := harness.SearchDeps{Backend: &corpusRetriever{}, KbIDs: []string{"kb1"}, HasEmbedder: true} + req := harness.RunRequest{Question: "when was it made?", TopN: 8} + deps := RAGTools{ + Model: &scriptedModel{}, + Search: sd, + } + // Mirror Rag: the hook is idempotent, so the graph's node and the + // post-graph safety net cannot both compose. + composed := false + deps.Finalize = func(context.Context) { + if composed { + return + } + composed = true + finalized++ + } + + var buf bytes.Buffer + if err := BuildLowGraph(ctx, deps, req, sd, kb, resp, log.New(&buf, "", 0)); err != nil { + t.Fatalf("BuildLowGraph: %v", err) + } + // The graph's last node composed... + if finalized != 1 { + t.Fatalf("formalize_answer node composed %d time(s), want 1; log:\n%s", finalized, buf.String()) + } + // ...and the post-graph call is then a no-op. + deps.Finalize(ctx) + if finalized != 1 { + t.Errorf("composition ran %d time(s) after the post-graph call, want 1", finalized) + } +} + +// TestSCAUnavailableMarksInsufficient pins Python :1096-1098: when the SCA +// produces no usable result (timeout, unparsable reply, no model) the verdict is +// INSUFFICIENT so unresolved slots can drive another research round — NOT +// SUFFICIENT, which would ship the unverified draft as if it had passed review. +func TestSCAUnavailableMarksInsufficient(t *testing.T) { + st := NewAgenticState("When was it built?", "", 3, nil) + st.Draft = "Built in 1865." + st.KB = &harness.Kbinfos{Chunks: []map[string]any{ + {"chunk_id": "c1", "content": "Built 1865, Geneva."}, + }} + // A model that never returns JSON: GenJSON fails, so the SCA has no result. + mdl := &scriptedModel{} + mdl.push("this is not json at all") + + scaNode(context.Background(), RAGTools{Model: mdl}, st, log.New(&bytes.Buffer{}, "", 0)) + + if st.Verdict != VerdictInsufficient { + t.Errorf("Verdict = %q, want INSUFFICIENT (Python marks an unavailable SCA insufficient)", st.Verdict) + } + if st.SCA == nil { + t.Error("SCA payload must stay an (empty) map, like Python's sca={}") + } +} + +// TestQueryRewriteFoldsUnresolvedCluesWhenNoGaps pins Python :1114-1128: with +// no structured SCA gaps, the unresolved slots' question_clues become the gaps, +// so the loop keeps going instead of accepting an unresolved draft. +func TestQueryRewriteFoldsUnresolvedCluesWhenNoGaps(t *testing.T) { + st := NewAgenticState("When and where was it built?", "", 3, nil) + st.SCA = map[string]any{} // no sub_queries, no claims -> no gaps + st.UnresolvedSlots = []map[string]any{ + {"question_clues": []string{"when opened", "where located", "ignored third clue"}}, + } + st.Deadline = time.Now().Add(60 * time.Second) + + mdl := &scriptedModel{} + mdl.push(`{"queries": [{"query": "when was it opened"}]}`) + + queryRewriteNode(context.Background(), RAGTools{ + Model: mdl, + Search: harness.SearchDeps{Backend: &corpusRetriever{}, KbIDs: []string{"kb1"}, HasEmbedder: true}, + }, st, log.New(&bytes.Buffer{}, "", 0)) + + if st.NoProgress { + t.Fatal("NoProgress = true; Python folds unresolved slot clues into the gaps and keeps researching") + } + joined := strings.Join(st.CurrentQueries, "|") + if !strings.Contains(joined, "when opened") { + t.Errorf("CurrentQueries = %v, want the unresolved slot clue to be pursued", st.CurrentQueries) + } +} + +// TestUnresolvedClueGapsCapsAtTwoClues mirrors Python's `[:2]` per slot. +func TestUnresolvedClueGapsCapsAtTwoClues(t *testing.T) { + st := &AgenticState{UnresolvedSlots: []map[string]any{ + {"question_clues": []string{"a", "b", "c"}}, + {"question_clues": []string{"a", "d"}}, // duplicate "a" is dropped + }} + gaps := unresolvedClueGaps(st) + if len(gaps) != 3 { + t.Fatalf("gaps = %d, want 3 (2 from the first slot + 1 new from the second)", len(gaps)) + } + if gaps[0].What != "a" || gaps[0].SearchHint != "a" { + t.Errorf("gaps[0] = %+v, want what=hint=\"a\"", gaps[0]) + } +} + +// TestBuildSCAClaimsFallsBackToEvidenceOnlyClaim pins Python :1072-1073: with no +// draft and no slot evidence, the SCA still gets one claim carrying EVERY chunk +// in the view, so it can judge the evidence instead of the node short-circuiting. +func TestBuildSCAClaimsFallsBackToEvidenceOnlyClaim(t *testing.T) { + view := []map[string]any{ + {"chunk_id": "c1", "content": "Built 1865."}, + {"chunk_id": "c2", "content": "In Geneva."}, + } + claims, _ := buildSCAClaims("", view, view, nil) + if len(claims) != 1 { + t.Fatalf("claims = %d, want 1", len(claims)) + } + if claims[0].Draft != "(no draft)" { + t.Errorf("draft = %q, want %q", claims[0].Draft, "(no draft)") + } + // Evidence is addressed by POSITION (renderClaimContext keys by index), so + // the fallback claim must carry 0..len(view)-1. + if len(claims[0].EvidenceIDs) != 2 || claims[0].EvidenceIDs[0] != "0" || claims[0].EvidenceIDs[1] != "1" { + t.Errorf("EvidenceIDs = %v, want [0 1]", claims[0].EvidenceIDs) + } +} + +// TestBuildSCAClaimsAppendsMissingSlotEvidence pins Python :1057-1071: a slot +// whose evidence chunk is NOT in the view has that chunk appended, and the claim +// carries its new POSITION. Python appends to the same list and reviews against +// it, so buildSCAClaims returns the grown view. +func TestBuildSCAClaimsAppendsMissingSlotEvidence(t *testing.T) { + chunks := []map[string]any{ + {"chunk_id": "c1", "content": "Built 1865."}, + {"chunk_id": "c2", "content": "In Geneva."}, + {"chunk_id": "c3", "content": "Designed by OmiyaSoft."}, + } + view := []map[string]any{chunks[0]} + slotEvidence := map[string]SlotEvidence{ + "0": {EvidenceIDs: []string{"2"}, Candidate: "designer"}, // pool position 2 + } + + claims, grown := buildSCAClaims("", view, chunks, slotEvidence) + if len(claims) != 1 { + t.Fatalf("claims = %d, want 1", len(claims)) + } + if len(grown) != 2 { + t.Fatalf("grown view = %d, want 2 (the missing chunk must be appended)", len(grown)) + } + if got := claims[0].EvidenceIDs; len(got) != 1 || got[0] != "1" { + t.Errorf("EvidenceIDs = %v, want [1] (its position in the grown view)", got) + } +} + +// TestResolveEvidenceChunkAcceptsBothIdSpaces covers the heterogeneous ids: +// retrieval tools emit pool positions, navigation tools emit doc ids. +func TestResolveEvidenceChunkAcceptsBothIdSpaces(t *testing.T) { + chunks := []map[string]any{ + {"chunk_id": "c1", "doc_id": "d1", "content": "a"}, + {"chunk_id": "c2", "doc_id": "d2", "content": "b"}, + } + if got := resolveEvidenceChunk("1", chunks); got["chunk_id"] != "c2" { + t.Errorf("position id \"1\" resolved to %v, want chunk c2", got) + } + if got := resolveEvidenceChunk("c1", chunks); got["chunk_id"] != "c1" { + t.Errorf("chunk id \"c1\" resolved to %v, want chunk c1", got) + } + if got := resolveEvidenceChunk("d2", chunks); got["chunk_id"] != "c2" { + t.Errorf("doc id \"d2\" resolved to %v, want chunk c2", got) + } + if got := resolveEvidenceChunk("nope", chunks); got != nil { + t.Errorf("unknown id resolved to %v, want nil", got) + } +} + +func TestAgenticNodeNameMapsRoutingToGraphKeys(t *testing.T) { + cases := map[agenticNode]string{ + nodeQueryRewrite: "query_rewrite", + nodeRagAgentFirst: "rag_agent", + nodeRagAgentLoop: "rag_agent", + nodeFormalizeAnswer: "formalize_answer", + nodeFormalizeQuestion: "formalize_answer", + } + for n, want := range cases { + if got := agenticNodeName(n); got != want { + t.Errorf("agenticNodeName(%d) = %q, want %q", n, got, want) + } + } +} + +// --------------------------------------------------------------------------- +// Explicit-wiring integration tests (replaces the old init()-based registration +// checks). Activation is explicit, mirroring Python's dialog_service.py +// instantiating RAGTools: the test registers the loop before calling Run. +// --------------------------------------------------------------------------- + +// TestMain keeps the package's tests on in-memory doubles: graph exploration +// otherwise seeds its dense search from the tenant embedding model, which +// reaches a database these tests do not have. Returning nil keeps the keyword +// fallback, which is the path under test. +func TestMain(m *testing.M) { + harness.SetSeedEncoder(func(context.Context, string, string) []float64 { return nil }) + os.Exit(m.Run()) +} + +func TestNewAgenticLoopDrivesHarnessRun(t *testing.T) { + SetAgenticLoop(NewAgenticLoop()) + defer SetAgenticLoop(nil) + + facts := `{"fact":"Saint Lawrence River; 14 April 1865; 9 December 2019."}` + if err := json.Unmarshal([]byte(facts), &struct{}{}); err != nil { + t.Fatalf("bad fixture: %v", err) + } + + mdl := &scriptedModel{} + mdl.push(`{"fanouts": ["when was it opened", "what river"]}`) + mdl.push(`{"slots":[{"id":0,"type":"aspect","question":"when opened","clues":["1865"]},{"id":1,"type":"aspect","question":"which river","clues":["river"]}], "first_queries":["when opened","which river"]}`) + mdl.push("It opened on 14 April 1865.") + mdl.push("The Saint Lawrence River.") + mdl.push(`{"is_sufficient": true, "score": 0.9, "contradictions": [], "reasoning": "ok", "claims": {}}`) + + deps := RAGTools{ + Retriever: &countingRetriever{}, + Model: mdl, + Prompts: &fakePrompts{}, + } + + got := runHarnessRun(t, deps, "When did it open and on which river?") + if got == nil { + t.Fatal("expected a non-nil RunResponse") + } + if got.Mode.Label != "high" { + t.Fatalf("expected high mode, got %q", got.Mode.Label) + } + // The agentic loop routed through the planner + slot research; at minimum the + // response is produced without error. + if len(got.Chunks) == 0 { + t.Fatalf("expected >=1 chunk (retriever stub fills KB), got %d", len(got.Chunks)) + } +} + +// rfRetriever records the rank feature every retrieve call carried. +type rfRetriever struct { + features []map[string]float64 + queries []string + docScopes [][]string +} + +func (r *rfRetriever) Retrieve(_ context.Context, req harness.RetrieveRequest) ([]map[string]any, error) { + r.features = append(r.features, req.RankFeature) + r.queries = append(r.queries, req.Query) + r.docScopes = append(r.docScopes, req.DocScope) + return []map[string]any{{ + "chunk_id": "c1", + "content": "The bridge opened in 1865.", + "doc_id": "d1", + "doc_name": "Bridge", + }}, nil +} + +type rfTagger struct{} + +func (rfTagger) LabelQuestion(_ context.Context, _ string, _ []*entity.Knowledgebase) map[string]float64 { + return map[string]float64{"location": 1.0} +} + +// TestAgenticLoopProjectsRankFeature guards the projection that Python gets for +// free: tools.retrieve reads every setting (incl. +// rank_feature=label_question(question, self.kbs), agentic_rag.py:668) off the +// RAGTools instance, so the agentic loop's fan-out and action-session retrieval +// must see the same Tagger/KBs. A partial SearchDeps projection silently drops +// the tag boost and degrades ranking with no error. +func TestAgenticLoopProjectsRankFeature(t *testing.T) { + SetAgenticLoop(NewAgenticLoop()) + defer SetAgenticLoop(nil) + + mdl := &scriptedModel{} + // Call order: formalize (single-turn keyword extraction, Python + // agentic_rag.py:446) → planner fan-out → slot table → draft → SCA. + mdl.push(`{"entity": ["it"], "aliases": [], "fact_type": [], "qualifiers": []}`) + mdl.push(`{"fanouts": ["when was it opened"]}`) + mdl.push(`{"slots":[{"id":0,"type":"aspect","question":"when opened","clues":["1865"]}], "first_queries":["when opened"]}`) + mdl.push("It opened in 1865.") + mdl.push(`{"is_sufficient": true, "score": 0.9, "contradictions": [], "reasoning": "ok", "claims": {}}`) + + r := &rfRetriever{} + got := runHarnessRun(t, RAGTools{ + Retriever: r, + Model: mdl, + Prompts: &fakePrompts{}, + KBs: []*entity.Knowledgebase{{}}, + Tagger: rfTagger{}, + }, "When did it open?") + if got == nil { + t.Fatal("expected a non-nil RunResponse") + } + if len(r.features) == 0 { + t.Fatal("the agentic loop performed no retrieval") + } + // Scope to the fan-out / slot research retrievals — the ones Python issues + // through tools.retrieve / search_chunks and therefore the ones that must + // carry rank_feature. + // + // Deliberately exempt: the navigation tools' own recalls (chunk-agg routing + // via chunkAggRetrieveFrom, and _recall_chunk_ids_in_doc) which mirror + // Python's _search_layers_nav_chunk_agg / _recall_chunk_ids_in_doc + // (navigation.py:1399) — neither passes rank_feature there. + research := map[string]bool{"when was it opened": true, "when opened": true} + checked := 0 + for i, q := range r.queries { + if !research[q] { + continue + } + checked++ + if r.features[i]["location"] != 1.0 { + t.Errorf("retrieve %q RankFeature = %v, want the label_question tag boost", q, r.features[i]) + } + } + if checked == 0 { + t.Fatalf("no fan-out/slot retrieval was performed (saw %v); assertion would be vacuous", r.queries) + } +} + +func TestNewAgenticLoopDegradesWithoutModel(t *testing.T) { + SetAgenticLoop(NewAgenticLoop()) + defer SetAgenticLoop(nil) + + deps := RAGTools{ + Retriever: &countingRetriever{}, + Model: nil, // no model => direct fallback + Prompts: &fakePrompts{}, + } + + got := runHarnessRun(t, deps, "Any question?") + if got == nil { + t.Fatal("expected a non-nil RunResponse") + } + // With no model the loop falls back to a single direct retrieval; no slots. + if len(got.Slots) != 0 { + t.Fatalf("expected 0 slots when no model, got %d", len(got.Slots)) + } + if len(got.Chunks) == 0 { + t.Fatalf("expected >=1 chunk from direct fallback, got %d", len(got.Chunks)) + } +} + +func TestNewAgenticLoopRoundsToggleDeactivates(t *testing.T) { + // After deregistering (nil), Run must NOT enter the agentic loop. + SetAgenticLoop(nil) + + mdl := &scriptedModel{} + mdl.push(`{"fanouts": ["x", "y"]}`) // would only be produced by the loop's planner + deps := RAGTools{ + Retriever: &countingRetriever{}, + Model: mdl, + Prompts: &fakePrompts{}, + } + got := runHarnessRun(t, deps, "Question?") + if got == nil { + t.Fatal("expected a non-nil RunResponse") + } + // In single-session fallback the planner fan-out prompt is never issued, so + // the scripted model's first reply is never consumed. + if mdl.idx != 0 { + t.Fatalf("expected agentic planner NOT to run (model idx %d, want 0)", mdl.idx) + } + _ = got +} + +// runHarnessRun drives Run in high mode and returns the response. It is +// the Go analogue of dialog_service.py invoking RAGTools for an agentic answer. +func runHarnessRun(t *testing.T, deps RAGTools, question string) *RunResponse { + t.Helper() + req := harness.RunRequest{ + Question: question, + DatasetIDs: []string{"kb1"}, + ThinkingMode: "high", + } + resp := Rag(context.Background(), deps, req) + if resp == nil { + t.Fatalf("Run returned nil response") + } + return resp +} + +// strPtr / fltPtr / fakePrompts are tiny helpers shared across the tests. +func strPtr(s string) *string { return &s } + +type fakePrompts struct{} + +func (f *fakePrompts) Load(name string) (string, error) { return "", nil } + +// Test doubles for the RAGTools method tests. Kept local to the advanced_rag package so +// the tests can call Run/ComposeAnswer (which live here) without importing agent +// from the harness test package (that would be an import cycle). + +// fakeModel replays a scripted sequence of replies, so the session's control +// flow can be driven without a provider. +type fakeModel struct { + replies []*harness.ModelReply + calls int + messages []schema.Message +} + +func (f *fakeModel) Complete(_ context.Context, msgs []schema.Message, _ []harness.ToolSpec) (*harness.ModelReply, error) { + f.messages = msgs + if f.calls >= len(f.replies) { + return &harness.ModelReply{Content: `{"new_states": []}`}, nil + } + r := f.replies[f.calls] + f.calls++ + return r, nil +} + +// lastUserPrompt returns the content of the most recent user message, so tests +// can assert on the prompt the model actually received. +func (f *fakeModel) lastUserPrompt() string { + for i := len(f.messages) - 1; i >= 0; i-- { + if f.messages[i].Role == schema.User { + return f.messages[i].Content + } + } + return "" +} + +// corpusRetriever answers every query from a fixed corpus. +type corpusRetriever struct{ calls []string } + +func (c *corpusRetriever) Retrieve(_ context.Context, req harness.RetrieveRequest) ([]map[string]any, error) { + c.calls = append(c.calls, req.Query) + return []map[string]any{{ + "chunk_id": "c1", + "content": "Culdcept was created by OmiyaSoft and released in 1999.", + "doc_id": "doc-culdcept", + "docnm_kwd": "Culdcept History", + "dataset_id": "kb1", + }}, nil +} + +// emptyRetriever simulates a corpus with no matches. +type emptyRetriever struct{} + +func (emptyRetriever) Retrieve(_ context.Context, _ harness.RetrieveRequest) ([]map[string]any, error) { + return nil, nil +} + +func TestRunLowModeIsSinglePass(t *testing.T) { + r := &corpusRetriever{} + resp := Rag(context.Background(), RAGTools{Retriever: r}, harness.RunRequest{ + Question: "Who created Culdcept?", + ThinkingMode: "low", + DatasetIDs: []string{"kb1"}, + UseCompiled: true, + }) + if resp.EmptyResult { + t.Fatal("low mode must retrieve evidence") + } + if len(resp.Chunks) != 1 { + t.Fatalf("chunks = %d, want 1", len(resp.Chunks)) + } + if len(r.calls) != 1 { + t.Errorf("retrieval calls = %d, want 1 (low is a single pass)", len(r.calls)) + } + if resp.Mode.Agentic { + t.Error("low must resolve to a non-agentic spec") + } + if len(resp.DocAggs) != 1 || resp.DocAggs[0]["doc_id"] != "doc-culdcept" { + t.Fatalf("doc_aggs = %v", resp.DocAggs) + } + if resp.DocAggs[0]["doc_name"] != "Culdcept History" { + t.Errorf("doc_name = %v, want 'Culdcept History'", resp.DocAggs[0]["doc_name"]) + } + if harness.MemorySize(resp.Kbinfos) != 1 { + t.Errorf("memory size = %d, want 1", harness.MemorySize(resp.Kbinfos)) + } +} + +func TestRunUnknownModeFallsBackToNaive(t *testing.T) { + r := &corpusRetriever{} + resp := Rag(context.Background(), RAGTools{Retriever: r}, harness.RunRequest{ + Question: "Who created Culdcept?", + ThinkingMode: "not-a-real-mode", + DatasetIDs: []string{"kb1"}, + }) + if resp.Mode.Label != "naive" { + t.Errorf("mode = %q, want naive", resp.Mode.Label) + } + if resp.EmptyResult { + t.Error("naive must still retrieve (it degrades, not fails)") + } +} + +// TestNaiveUsesFlatEvidenceAndOwnComposition pins the semantics that separate +// the naive path from low/direct. Python's _naive_rag (:1517) is NOT +// "direct_search minus formalize": it does a plain retrieve with no weighted +// keyword extraction (:1533) and composes under a short fixed system prompt +// from flat "[i] content" evidence (:1555-1568), never FinalAnswerSystem / +// kb_prompt. Routing naive through runDirect + composeFinalAnswer silently +// substituted the agentic composition, which is what this test guards. +func TestNaiveUsesFlatEvidenceAndOwnComposition(t *testing.T) { + mdl := &fakeModel{replies: []*harness.ModelReply{{Content: "OmiyaSoft [1]."}}} + r := &corpusRetriever{} + resp := Rag(context.Background(), RAGTools{Retriever: r, Model: mdl}, harness.RunRequest{ + Question: "Who created Culdcept?", + ThinkingMode: "not-a-real-mode", + DatasetIDs: []string{"kb1"}, + UseCompiled: true, // naive must ignore compiled expansion + }) + + if resp.Mode.Label != "naive" { + t.Fatalf("mode = %q, want naive", resp.Mode.Label) + } + if resp.EmptyResult || len(resp.Chunks) != 1 { + t.Fatalf("naive must retrieve evidence (chunks=%d, empty=%v)", len(resp.Chunks), resp.EmptyResult) + } + // Python 1533: one PLAIN retrieve — no ExtractWeightedKeywords, so the model + // is called exactly once. The old runDirect path spent a second call on + // keyword extraction before composing. + if mdl.calls != 1 { + t.Fatalf("model calls = %d, want 1 (naive composes without extracting keywords)", mdl.calls) + } + + // Python 1555: flat "[i] content" evidence, not kb_prompt's "ID: n" blocks. + got := mdl.lastUserPrompt() + if !strings.Contains(got, "[1] Culdcept was created") { + t.Errorf("evidence = %q, want flat \"[1] \"", got) + } + if strings.Contains(got, "ID: 1") { + t.Errorf("evidence = %q, must not use kb_prompt's \"ID: n\" blocks", got) + } + if resp.Answer != "OmiyaSoft [1]." { + t.Errorf("answer = %q, want the naive composition", resp.Answer) + } +} + +func TestRunAgenticDegradesToDirectWithoutModel(t *testing.T) { + r := &corpusRetriever{} + resp := Rag(context.Background(), RAGTools{Retriever: r}, harness.RunRequest{ + Question: "Who created Culdcept?", + ThinkingMode: "high", + DatasetIDs: []string{"kb1"}, + }) + if resp.EmptyResult { + t.Error("agentic mode without a model must degrade to direct search") + } +} + +func TestRunAgenticSeedsSlotsAndRunsSession(t *testing.T) { + r := &corpusRetriever{} + mdl := &fakeModel{replies: []*harness.ModelReply{ + {Content: `{"slots": [{"id": 0, "type": "entity", "clues": ["creator"]}, {"id": 1, "type": "date", "clues": ["released"]}], "first_queries": ["creator"]}`}, + {Content: "", ToolCalls: []harness.ToolCall{{ID: "c0", Name: "retrieve", Args: map[string]any{"query": []any{"Culdcept creator"}}}}}, + {Content: `{"new_states":[{"state":[{"id":0,"candidate":"OmiyaSoft","candidate_strength":0.95}]}]}`}, + }} + resp := Rag(context.Background(), RAGTools{Retriever: r, Model: mdl}, harness.RunRequest{ + Question: "Who created Culdcept and when?", + ThinkingMode: "medium", + DatasetIDs: []string{"kb1"}, + }) + if resp.EmptyResult { + t.Fatal("the session's retrieval must land in kbinfos") + } + if len(resp.Slots) != 2 { + t.Fatalf("slots = %d, want 2 (from the seeded table)", len(resp.Slots)) + } + filled := 0 + for _, v := range resp.Slots { + if v.Filled() { + filled++ + } + } + if filled != 1 { + t.Errorf("filled slots = %d, want 1 (the patched candidate)", filled) + } + if len(r.calls) == 0 { + t.Error("the retrieve tool call never reached the retriever") + } +} + +func TestRunNeverPanicsWithoutBackend(t *testing.T) { + resp := Rag(context.Background(), RAGTools{}, harness.RunRequest{ + Question: "anything", + ThinkingMode: "low", + DatasetIDs: []string{"kb1"}, + }) + if !resp.EmptyResult { + t.Error("an unavailable backend must yield an empty result, not an error") + } +} + +func TestRunLowReturnsComposedAnswer(t *testing.T) { + mdl := &fakeModel{replies: []*harness.ModelReply{ + // formalize (single-turn keyword extraction, Python + // agentic_rag.py:446) and the low graph's direct search each extract + // keywords in their own call (Python direct.py:22 does the same), so + // the composed answer is the third reply. + {Content: `{"entity": ["Culdcept"], "aliases": [], "fact_type": [], "qualifiers": []}`}, + {Content: `{"entity": ["Culdcept"], "aliases": [], "fact_type": [], "qualifiers": []}`}, + {Content: "Culdcept was created by OmiyaSoft and released in 1999 [1]."}, + }} + resp := Rag(context.Background(), RAGTools{ + Retriever: &corpusRetriever{}, + Model: mdl, + }, harness.RunRequest{ + Question: "Who created Culdcept?", + ThinkingMode: "low", + DatasetIDs: []string{"kb1"}, + }) + if resp.EmptyResult { + t.Fatal("low must retrieve evidence") + } + if resp.Answer == "" { + t.Fatal("low must return a composed answer (was empty before the composition node)") + } + if !strings.Contains(resp.Answer, "OmiyaSoft") { + t.Errorf("answer = %q, want it grounded in the retrieved evidence", resp.Answer) + } + if len(resp.Chunks) == 0 || len(resp.DocAggs) == 0 { + t.Error("chunks/aggs must be reported alongside the answer") + } +} + +func TestRunUnknownModeReturnsComposedAnswer(t *testing.T) { + mdl := &fakeModel{replies: []*harness.ModelReply{{Content: "OmiyaSoft [1]"}}} + resp := Rag(context.Background(), RAGTools{ + Retriever: &corpusRetriever{}, + Model: mdl, + }, harness.RunRequest{ + Question: "Who created Culdcept?", + ThinkingMode: "not-a-mode", + DatasetIDs: []string{"kb1"}, + }) + if resp.Mode.Label != "naive" { + t.Fatalf("mode = %q, want naive", resp.Mode.Label) + } + if resp.Answer == "" { + t.Error("naive must compose an answer") + } +} + +func TestRunEmptyResponseShortCircuits(t *testing.T) { + mdl := &fakeModel{} + resp := Rag(context.Background(), RAGTools{ + Retriever: &emptyRetriever{}, + Model: mdl, + EmptyResponse: "I don't have enough information.", + }, harness.RunRequest{ + Question: "Who created Culdcept?", + ThinkingMode: "low", + DatasetIDs: []string{"kb1"}, + }) + if !resp.EmptyResult { + t.Fatal("expected no evidence") + } + if resp.Answer != "I don't have enough information." { + t.Errorf("answer = %q, want the configured empty response", resp.Answer) + } + if mdl.calls != 0 { + t.Errorf("model calls = %d, want 0 (short-circuited before composition)", mdl.calls) + } +} + +func TestRunCanDisableComposition(t *testing.T) { + no := false + resp := Rag(context.Background(), RAGTools{ + Retriever: &corpusRetriever{}, + Model: &fakeModel{}, + ComposeAnswer: &no, + }, harness.RunRequest{ + Question: "Who created Culdcept?", + ThinkingMode: "low", + DatasetIDs: []string{"kb1"}, + }) + if resp.Answer != "" { + t.Errorf("answer = %q, want empty when composition is disabled", resp.Answer) + } + if len(resp.Chunks) == 0 { + t.Error("evidence must still be returned") + } +} + +func TestRunFormalizesFromConversation(t *testing.T) { + mdl := &fakeModel{replies: []*harness.ModelReply{ + {Content: `{"question": "When was Culdcept released?", "keywords": "Culdcept, release, released"}`}, + {Content: "Culdcept was released in 1999 [1]."}, + }} + retriever := &corpusRetriever{} + resp := Rag(context.Background(), RAGTools{ + Retriever: retriever, + Model: mdl, + Messages: []schema.Message{ + *schema.UserMessage("Who created Culdcept?"), + *schema.AssistantMessage("OmiyaSoft.", nil), + *schema.UserMessage("When was it released?"), + }, + }, harness.RunRequest{ + Question: "When was it released?", + ThinkingMode: "low", + DatasetIDs: []string{"kb1"}, + }) + if len(retriever.calls) == 0 { + t.Fatal("retriever was never called") + } + if !strings.HasPrefix(retriever.calls[0], "When was Culdcept released?") { + t.Errorf("retrieval query = %q, want it to start with the formalized question", retriever.calls[0]) + } + if !strings.Contains(retriever.calls[0], "Culdcept") { + t.Errorf("retrieval query = %q, want the formalized keywords appended", retriever.calls[0]) + } + if resp.Answer == "" { + t.Error("answer must be composed after formalization") + } +} + +func TestRunFormalizeDisabledByDefault(t *testing.T) { + mdl := &fakeModel{replies: []*harness.ModelReply{{Content: "answer [1]"}}} + Rag(context.Background(), RAGTools{ + Retriever: &corpusRetriever{}, + Model: mdl, + Messages: []schema.Message{ + *schema.UserMessage("Who created Culdcept?"), + *schema.AssistantMessage("OmiyaSoft.", nil), + *schema.UserMessage("When was it released?"), + }, + }, harness.RunRequest{ + Question: "When was it released?", + ThinkingMode: "low", + DatasetIDs: []string{"kb1"}, + }) + if mdl.calls != 1 { + t.Errorf("model calls = %d, want 1 (formalize is opt-in)", mdl.calls) + } +} + +func TestRunAgenticComposesFromResearchFindings(t *testing.T) { + kb := &harness.Kbinfos{ + Chunks: []map[string]any{{"chunk_id": "c1", "content": "Culdcept: OmiyaSoft, 1999.", "similarity": 0.9}}, + PreSummary: "Culdcept was created by OmiyaSoft and released in 1999.", + } + mdl := &fakeModel{replies: []*harness.ModelReply{{Content: "Culdcept was created by OmiyaSoft and released in 1999 [1]."}}} + res := ComposeAnswer(context.Background(), AnswerDeps{Model: mdl}, kb, "Who created Culdcept?", false, false) + if res.Failed { + t.Fatal("composition must succeed") + } + if !strings.Contains(mdl.lastUserPrompt(), "Culdcept was created by OmiyaSoft and released in 1999.") { + t.Errorf("prompt missing the research findings:\n%s", mdl.lastUserPrompt()) + } +} + +// TestAnswerPromptCarriesTargetContract pins the EXTREME-SELECTION guardrail +// (Python :643-652). Without it a "longest/shortest/most…" question tends to be +// answered with the most common or first-listed candidate rather than the +// extreme one, because nothing asks the model to compare. +func TestAnswerPromptCarriesTargetContract(t *testing.T) { + kb := &harness.Kbinfos{ + Chunks: []map[string]any{{"chunk_id": "c1", "content": "river A is 300km; river B is 900km"}}, + } + mdl := &fakeModel{replies: []*harness.ModelReply{{Content: "river B [1]."}}} + if res := ComposeAnswer(context.Background(), AnswerDeps{Model: mdl}, kb, + "Which river is the longest?", false, false); res.Failed { + t.Fatal("composition must succeed") + } + got := mdl.lastUserPrompt() + if !strings.Contains(got, "Answer Target Contract:") { + t.Errorf("prompt missing the Answer Target Contract:\n%s", got) + } + if !strings.Contains(got, "EXTREME-SELECTION") || !strings.Contains(got, "EXTREME one") { + t.Errorf("prompt missing the EXTREME-SELECTION guardrail:\n%s", got) + } +} + +// TestAnswerPromptNoEvidenceInstructions pins Python :654-663: when the call is +// not short-circuited by empty_response, the prompt must still tell the model how +// to degrade — from the research summary if there is one, otherwise with an +// explicit insufficiency statement. +func TestAnswerPromptNoEvidenceInstructions(t *testing.T) { + // No chunks, no summary -> insufficiency statement. + mdl := &fakeModel{replies: []*harness.ModelReply{{Content: "unknown [1]."}}} + ComposeAnswer(context.Background(), AnswerDeps{Model: mdl}, &harness.Kbinfos{}, "q?", false, false) + if got := mdl.lastUserPrompt(); !strings.Contains(got, "No supporting evidence was retrieved") { + t.Errorf("prompt missing the no-evidence instruction:\n%s", got) + } + + // No chunks but a draft exists -> answer from the summary, do not refuse. + kb := &harness.Kbinfos{PreSummary: "partial findings"} + mdl2 := &fakeModel{replies: []*harness.ModelReply{{Content: "x [1]."}}} + ComposeAnswer(context.Background(), AnswerDeps{Model: mdl2}, kb, "q?", false, false) + if got := mdl2.lastUserPrompt(); !strings.Contains(got, "The retrieved passages are limited") { + t.Errorf("prompt missing the limited-evidence instruction:\n%s", got) + } +} + +// TestAnswerPromptOrdersPartialPreamble pins Python :668-671: the partial +// preamble sits AFTER the research summary and BEFORE the evidence — not at the +// front of the prompt, where it would precede the question. +func TestAnswerPromptOrdersPartialPreamble(t *testing.T) { + kb := &harness.Kbinfos{ + Chunks: []map[string]any{{"chunk_id": "c1", "content": "body"}}, + PreSummary: "the draft", + } + mdl := &fakeModel{replies: []*harness.ModelReply{{Content: "x [1]."}}} + ComposeAnswer(context.Background(), AnswerDeps{Model: mdl}, kb, "q?", true, false) + + got := mdl.lastUserPrompt() + iQ := strings.Index(got, "Question:") + iSummary := strings.Index(got, "Research Summary") + iPartial := strings.Index(got, strings.TrimSpace(harness.PartialAnswerPreamble)) + iEvidence := strings.Index(got, "Evidence:") + if iQ < 0 || iSummary < 0 || iPartial < 0 || iEvidence < 0 { + t.Fatalf("prompt missing one of the parts:\n%s", got) + } + if !(iQ < iSummary && iSummary < iPartial && iPartial < iEvidence) { + t.Errorf("order = question@%d summary@%d partial@%d evidence@%d, want question < summary < partial < evidence", + iQ, iSummary, iPartial, iEvidence) + } +} + +// TestComposeAnswerWithAttachesUserImages pins the non-outer path fix: when +// AnswerDeps.UserImages carries vision-gated data URIs (Python image_attachments +// surviving gateImageAttachments), the final-answer user message must be +// multimodal — an image_url content block beside the text question — so the +// compose model sees the images exactly like Python's direct async_chat +// fallback (called with the original multimodal messages). Without this the +// direct (no-outer) path composed from a text-only prompt and silently dropped +// the picture. +func TestComposeAnswerWithAttachesUserImages(t *testing.T) { + mdl := &fakeModel{replies: []*harness.ModelReply{{Content: "answer [1]."}}} + kb := &harness.Kbinfos{Chunks: []map[string]any{{"chunk_id": "c1", "content": "evidence"}}} + if res := ComposeAnswerWith(context.Background(), AnswerDeps{ + Model: mdl, + UserImages: []string{"data:image/png;base64,AAAA"}, + }, kb, "What is in this image?", false, false, false); res.Failed { + t.Fatal("composition must succeed") + } + var user *schema.Message + for i := len(mdl.messages) - 1; i >= 0; i-- { + if mdl.messages[i].Role == schema.User { + user = &mdl.messages[i] + break + } + } + if user == nil { + t.Fatal("no user message captured") + } + if len(user.UserInputMultiContent) == 0 { + t.Fatalf("expected multimodal content blocks on the user message; content=%q", user.Content) + } + hasImage := false + for _, p := range user.UserInputMultiContent { + if p.Type == schema.ChatMessagePartTypeImageURL { + hasImage = true + } + } + if !hasImage { + t.Errorf("expected an image_url block in the user message; got %+v", user.UserInputMultiContent) + } + // The text question must accompany the image (leading text block), so the + // model reads both the picture and the question. + sawText := user.Content != "" + for _, p := range user.UserInputMultiContent { + if p.Type == schema.ChatMessagePartTypeText && p.Text != "" { + sawText = true + } + } + if !sawText { + t.Errorf("expected the question text to accompany the image; content=%q blocks=%+v", user.Content, user.UserInputMultiContent) + } +} + +// TestComposeAnswerWithNoImagesStaysTextOnly pins the default: without +// UserImages the prompt is the plain-text question (no multimodal block), so +// non-vision callers are unaffected. +func TestComposeAnswerWithNoImagesStaysTextOnly(t *testing.T) { + mdl := &fakeModel{replies: []*harness.ModelReply{{Content: "answer [1]."}}} + kb := &harness.Kbinfos{Chunks: []map[string]any{{"chunk_id": "c1", "content": "evidence"}}} + if res := ComposeAnswerWith(context.Background(), AnswerDeps{Model: mdl}, kb, "plain?", false, false, false); res.Failed { + t.Fatal("composition must succeed") + } + user := mdl.messages[len(mdl.messages)-1] + if len(user.UserInputMultiContent) != 0 { + t.Errorf("expected no multimodal blocks when there are no images; got %+v", user.UserInputMultiContent) + } +} + +// userTurnAt returns the Content of the last message of the idx-th Complete +// call (0-based), i.e. the user turn of that attempt. +func userTurnAt(m *scriptedModel, idx int) string { + m.mu.Lock() + defer m.mu.Unlock() + if idx >= len(m.seen) || len(m.seen[idx]) == 0 { + return "" + } + return m.seen[idx][len(m.seen[idx])-1].Content +} + +// TestGenJSONUsesOutputNewlineUserTurn locks the contract that every JSONModel +// round mirrors Python gen_json's "Output:\n" user turn. It was previously an +// invisible convention buried inside jsonModelAdapter.GenJSON — a second JSONModel +// implementation could silently drop it and diverge from Python without any test +// catching it. See query_rewriter.go parity note (diff ②). +func TestGenJSONUsesOutputNewlineUserTurn(t *testing.T) { + mdl := &scriptedModel{} + mdl.push("{\"ok\": true}") + + if _, err := (&jsonModelAdapter{inner: mdl}).GenJSON(context.Background(), "Render JSON."); err != nil { + t.Fatalf("GenJSON failed: %v", err) + } + if got := userTurnAt(mdl, 0); got != "Output:\n" { + t.Errorf("first-round user turn = %q, want exactly %q (Python gen_json separator)", got, "Output:\n") + } +} + +func TestGenJSONRetriesMalformedReplyWithCorrection(t *testing.T) { + mdl := &scriptedModel{} + // First round: fenced but unparseable JSON. Second round: well-formed. + mdl.push("```json\n{\"queries\": [broken") + mdl.push("{\"queries\": [{\"query\": \"q1\"}]}") + + got, err := (&jsonModelAdapter{inner: mdl}).GenJSON(context.Background(), "Rewrite the query.") + if err != nil { + t.Fatalf("GenJSON failed after corrective retry: %v", err) + } + m, ok := got.(map[string]any) + if !ok { + t.Fatalf("GenJSON returned %T, want map[string]any", got) + } + queries, ok := m["queries"].([]any) + if !ok || len(queries) != 1 { + t.Fatalf("queries = %#v, want a 1-element list", m["queries"]) + } + + // The retry must feed the previous answer and the parse error back to the + // model, mirroring gen_json's corrective prompt. + turn := userTurnAt(mdl, 1) + for _, want := range []string{"Generated JSON is as following:", "broken", "But exception while loading:", "Please reconsider and correct it."} { + if !strings.Contains(turn, want) { + t.Errorf("retry user turn missing %q; got: %s", want, turn) + } + } +} + +func TestGenJSONStripsThinkAndFenceOnFirstTry(t *testing.T) { + mdl := &scriptedModel{} + mdl.push("Sure.\ndrafting...\n```json\n{\"ok\": true}\n```\n") + + got, err := (&jsonModelAdapter{inner: mdl}).GenJSON(context.Background(), "Render JSON.") + if err != nil { + t.Fatalf("GenJSON failed on a wrapper-padded reply: %v", err) + } + m, ok := got.(map[string]any) + if !ok { + t.Fatalf("GenJSON returned %T, want map[string]any", got) + } + if m["ok"] != true { + t.Errorf(`m["ok"] = %#v, want true`, m["ok"]) + } + if len(mdl.seen) != 1 { + t.Errorf("expected a single attempt, got %d", len(mdl.seen)) + } +} + +// fakeLLMCache is an in-memory LLMCache double. +type fakeLLMCache struct { + entries map[string]string + gets int + sets int +} + +func newFakeLLMCache() *fakeLLMCache { return &fakeLLMCache{entries: map[string]string{}} } + +func (c *fakeLLMCache) Get(_ context.Context, key string) (string, bool) { + c.gets++ + v, ok := c.entries[key] + return v, ok +} + +func (c *fakeLLMCache) Set(_ context.Context, key, value string) { + c.sets++ + c.entries[key] = value +} + +// TestGenJSONCachesFirstSuccessfulReply pins gen_json's 24h reply cache +// (Python get_llm_cache / set_llm_cache): the CLEANED answer of the first +// successful parse is stored, and an identical (model, system, user) triple is +// served from the cache WITHOUT a second model call. +func TestGenJSONCachesFirstSuccessfulReply(t *testing.T) { + cache := newFakeLLMCache() + mdl := &scriptedModel{} + mdl.push("Sure.\n```json\n{\"ok\": true}\n```\n") + + adapter := &jsonModelAdapter{inner: mdl, modelName: "gpt-4o", cache: cache} + first, err := adapter.GenJSON(context.Background(), "Render JSON.") + if err != nil { + t.Fatalf("first GenJSON: %v", err) + } + if m, ok := first.(map[string]any); !ok || m["ok"] != true { + t.Fatalf("first GenJSON = %#v", first) + } + if len(mdl.seen) != 1 || cache.sets != 1 { + t.Fatalf("first call: model calls = %d, cache sets = %d, want 1/1", len(mdl.seen), cache.sets) + } + wantKey := genJSONCacheKey("gpt-4o", "Render JSON.", "Output:\n") + // The cleanup regex removes only the ```json fence and the trailing fence: + // the "Sure.\n" prose prefix has no terminator, so it survives — + // exactly as it does in Python. + if got := cache.entries[wantKey]; got != "Sure.\n{\"ok\": true}\n" { + t.Errorf("cached value = %q, want the cleaned answer", got) + } + + second, err := adapter.GenJSON(context.Background(), "Render JSON.") + if err != nil { + t.Fatalf("second GenJSON: %v", err) + } + if m, ok := second.(map[string]any); !ok || m["ok"] != true { + t.Fatalf("second GenJSON = %#v", second) + } + if len(mdl.seen) != 1 { + t.Errorf("cache hit still called the model: %d calls", len(mdl.seen)) + } +} + +// TestGenJSONCacheKeyMatchesPython locks the key SHAPE: %x over the xxh64 of +// model+system+user+"{}" (str(gen_conf) of the default {} is "{}"), i.e. the 16 +// lowercase hex digits Python's xxhash.xxh64(...).hexdigest() produces. An empty +// model name yields "" so the cache is skipped rather than collapsing models. +func TestGenJSONCacheKeyMatchesPython(t *testing.T) { + got := genJSONCacheKey("gpt-4o", "SYS", "Output:\n") + // Reference value produced by Python itself: + // xxhash.xxh64(('gpt-4o' + 'SYS' + 'Output:\n' + '{}').encode('utf-8')).hexdigest() + // -> '02dffaad8465c0c9' + // Note the LEADING ZERO: a plain %x prints 15 digits ('2dffaad8465c0c9'), + // which would silently stop sharing the cache with Python. + if got != "02dffaad8465c0c9" { + t.Fatalf("key = %q, want 02dffaad8465c0c9 (Python xxh64 hexdigest)", got) + } + // Empty model name yields "" so callers SKIP the cache rather than collapse + // every model onto one bucket. + if genJSONCacheKey("", "SYS", "Output:\n") != "" { + t.Error("empty model name must disable the cache key") + } + if genJSONCacheKey("a", "SYS", "u") == genJSONCacheKey("b", "SYS", "u") { + t.Error("distinct model names produced the same key") + } +} + +// TestGenJSONFitsPromptToContextWindow pins Python gen_json's +// message_fit_in(form_message(system_prompt, user_prompt), chat_mdl.max_length): +// an oversized system prompt must be trimmed to the model window BEFORE the +// first call instead of being sent verbatim (the provider would reject it). +func TestGenJSONFitsPromptToContextWindow(t *testing.T) { + huge := strings.Repeat("token ", 40000) // far past any window + mdl := &scriptedModel{} + mdl.push(`{"ok": true}`) + + if _, err := (&jsonModelAdapter{inner: mdl, maxLength: 4096}).GenJSON(context.Background(), huge); err != nil { + t.Fatalf("GenJSON failed: %v", err) + } + if len(mdl.seen) != 1 || len(mdl.seen[0]) == 0 { + t.Fatalf("expected one call with messages, got %#v", mdl.seen) + } + sent := mdl.seen[0][0] + if sent.Role != schema.System { + t.Fatalf("first message role = %v, want system", sent.Role) + } + if len(sent.Content) >= len(huge) { + t.Errorf("system prompt not fitted: %d bytes sent of %d", len(sent.Content), len(huge)) + } +} + +// TestGenJSONAcceptsTopLevelArrayAndScalar pins json_repair parity: gen_json +// parses ANY top-level JSON value, so an array or scalar reply must come back +// as-is instead of being treated as a parse failure (which a map-only unmarshal +// did before). +func TestGenJSONAcceptsTopLevelArrayAndScalar(t *testing.T) { + mdl := &scriptedModel{} + mdl.push(`[{"query": "q1"}]`) + got, err := (&jsonModelAdapter{inner: mdl}).GenJSON(context.Background(), "Render JSON.") + if err != nil { + t.Fatalf("array reply: %v", err) + } + arr, ok := got.([]any) + if !ok || len(arr) != 1 { + t.Fatalf("array reply = %#v, want a 1-element list", got) + } + if len(mdl.seen) != 1 { + t.Errorf("array reply made %d attempt(s), want 1", len(mdl.seen)) + } + + mdl = &scriptedModel{} + mdl.push(`42`) + got, err = (&jsonModelAdapter{inner: mdl}).GenJSON(context.Background(), "Render JSON.") + if err != nil { + t.Fatalf("scalar reply: %v", err) + } + if n, ok := got.(float64); !ok || n != 42 { + t.Fatalf("scalar reply = %#v, want 42", got) + } +} + +func TestGenJSONGivesUpAfterMaxRetries(t *testing.T) { + mdl := &scriptedModel{} + mdl.push("I cannot produce JSON today.") + mdl.push("Still not JSON.") + + _, err := (&jsonModelAdapter{inner: mdl}).GenJSON(context.Background(), "Rewrite the query.") + if err == nil { + t.Fatal("GenJSON succeeded, want error after exhausting retries") + } + if len(mdl.seen) != 2 { + t.Errorf("expected 2 attempts (genJSONMaxRetry), got %d", len(mdl.seen)) + } +} + +// errOnceModel fails the underlying chat call and counts invocations, proving +// chat/transport errors are NOT retried (gen_json propagates them immediately). +type errOnceModel struct { + n int +} + +func (m *errOnceModel) Complete(_ context.Context, _ []schema.Message, _ []harness.ToolSpec) (*harness.ModelReply, error) { + m.n++ + return nil, errors.New("provider down") +} + +func TestGenJSONPropagatesChatErrorWithoutRetry(t *testing.T) { + mdl := &errOnceModel{} + _, err := (&jsonModelAdapter{inner: mdl}).GenJSON(context.Background(), "Rewrite the query.") + if err == nil { + t.Fatal("GenJSON succeeded, want the chat error") + } + if mdl.n != 1 { + t.Errorf("chat invoked %d times, want exactly 1 (no retry on transport error)", mdl.n) + } +} + +func TestGenJSONNilModel(t *testing.T) { + if _, err := (&jsonModelAdapter{inner: nil}).GenJSON(context.Background(), "x"); err == nil { + t.Fatal("GenJSON with a nil inner model succeeded, want error") + } +} + +// stubDocChunks implements harness.DocChunkLister for injection tests. +type stubDocChunks struct{} + +func (stubDocChunks) DocChunks(context.Context, harness.DocChunksRequest) ([]map[string]any, error) { + return nil, nil +} + +// TestSearchDepsForProjectsDocChunks locks the injection seam: RAGTools.DocChunks +// must be projected onto SearchDeps so the document-level tools (summarize_document +// / fetch_full_document) can reach a real chunk reader once the caller wires one. +func TestSearchDepsForProjectsDocChunks(t *testing.T) { + got := searchDepsFor(context.Background(), RAGTools{ + DocChunks: stubDocChunks{}, + }, harness.RunRequest{}, nil, "", &harness.Kbinfos{}, log.New(os.Stderr, "", 0)) + + if got.DocChunks == nil { + t.Fatal("RAGTools.DocChunks was not projected onto SearchDeps") + } + if _, ok := got.DocChunks.(stubDocChunks); !ok { + t.Fatalf("SearchDeps.DocChunks = %T, want the injected stubDocChunks", got.DocChunks) + } + + // Nil RAGTools.DocChunks must stay nil (disables whole-document reading). + gotNil := searchDepsFor(context.Background(), RAGTools{}, harness.RunRequest{}, nil, "", &harness.Kbinfos{}, log.New(os.Stderr, "", 0)) + if gotNil.DocChunks != nil { + t.Fatal("nil RAGTools.DocChunks must stay nil on SearchDeps") + } +} + +// These benchmarks isolate the cost Eino charges for declaring + compiling a +// graph — exactly what the "build once, inject deps via state" alternative +// (B2) would save. The per-run Invoke cost is identical in both designs, so it +// is deliberately not measured here. + +func benchCompile(b *testing.B, build func() error) { + b.Helper() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + if err := build(); err != nil { + b.Fatal(err) + } + } +} + +// low graph shape: 3 nodes, 3 edges, no branch. +func BenchmarkCompileLowGraphShape(b *testing.B) { + ctx := context.Background() + benchCompile(b, func() error { + g := compose.NewGraph[*harness.RunRequest, *harness.RunRequest]() + node := func(c context.Context, r *harness.RunRequest) (*harness.RunRequest, error) { return r, nil } + if err := g.AddLambdaNode("formalize_question", compose.InvokableLambda(node)); err != nil { + return err + } + if err := g.AddLambdaNode("direct_search", compose.InvokableLambda(node)); err != nil { + return err + } + if err := g.AddLambdaNode("formalize_answer", compose.InvokableLambda(node)); err != nil { + return err + } + if err := g.AddEdge(compose.START, "formalize_question"); err != nil { + return err + } + if err := g.AddEdge("formalize_question", "direct_search"); err != nil { + return err + } + if err := g.AddEdge("direct_search", "formalize_answer"); err != nil { + return err + } + if err := g.AddEdge("formalize_answer", compose.END); err != nil { + return err + } + _, err := g.Compile(ctx, compose.WithGraphName("bench_low")) + return err + }) +} + +// action session shape: 3 nodes, 2 edges, 2 branches (with cycles). +func BenchmarkCompileActionSessionShape(b *testing.B) { + ctx := context.Background() + benchCompile(b, func() error { + g := compose.NewGraph[*AgenticState, *AgenticState]() + node := func(c context.Context, s *AgenticState) (*AgenticState, error) { return s, nil } + for _, n := range []string{"run_action", "tool", "finalize"} { + if err := g.AddLambdaNode(n, compose.InvokableLambda(node)); err != nil { + return err + } + } + if err := g.AddEdge(compose.START, "run_action"); err != nil { + return err + } + if err := g.AddEdge("finalize", compose.END); err != nil { + return err + } + ends := map[string]bool{"tool": true, "finalize": true, "run_action": true, compose.END: true} + if err := g.AddBranch("run_action", compose.NewGraphBranch(func(context.Context, *AgenticState) (string, error) { + return "run_action", nil + }, ends)); err != nil { + return err + } + if err := g.AddBranch("tool", compose.NewGraphBranch(func(context.Context, *AgenticState) (string, error) { + return "run_action", nil + }, map[string]bool{"run_action": true, "finalize": true})); err != nil { + return err + } + _, err := g.Compile(ctx, compose.WithGraphName("bench_session"), compose.WithMaxRunSteps(32)) + return err + }) +} + +// agentic graph shape: 7 nodes, 4 edges, 5 branches. +func BenchmarkCompileAgenticShape(b *testing.B) { + ctx := context.Background() + benchCompile(b, func() error { + g := compose.NewGraph[*AgenticState, *AgenticState]() + node := func(c context.Context, s *AgenticState) (*AgenticState, error) { return s, nil } + for _, n := range []string{ + "formalize_question", "planner", "prefetch", "rag_agent", + "query_rewrite", "formalize_answer", "stop", + } { + if err := g.AddLambdaNode(n, compose.InvokableLambda(node)); err != nil { + return err + } + } + for _, e := range [][2]string{ + {compose.START, "formalize_question"}, + {"prefetch", "rag_agent"}, + {"formalize_answer", compose.END}, + {"stop", compose.END}, + } { + if err := g.AddEdge(e[0], e[1]); err != nil { + return err + } + } + branches := map[string]map[string]bool{ + "formalize_question": {"stop": true, "planner": true, "rag_agent": true}, + "planner": {"stop": true, "prefetch": true, "rag_agent": true}, + "prefetch": {"stop": true, "rag_agent": true}, + "rag_agent": {"stop": true, "query_rewrite": true, "formalize_answer": true}, + "query_rewrite": {"stop": true, "rag_agent": true, "formalize_answer": true}, + } + for from, ends := range branches { + if err := g.AddBranch(from, compose.NewGraphBranch(func(context.Context, *AgenticState) (string, error) { + return "rag_agent", nil + }, ends)); err != nil { + return err + } + } + _, err := g.Compile(ctx, compose.WithGraphName("bench_agentic"), compose.WithMaxRunSteps(136)) + return err + }) +} + +func TestGraphRecursionLimitMatchesPython(t *testing.T) { + // Python :1619 — 60 for the agentic graph, else max(25, max_loops*8). + if got := graphRecursionLimit(true, 3); got != 60 { + t.Fatalf("agentic limit = %d, want 60", got) + } + if got := graphRecursionLimit(false, 3); got != 25 { + t.Fatalf("low limit with 3 loops = %d, want 25", got) + } + if got := graphRecursionLimit(false, 5); got != 40 { + t.Fatalf("low limit with 5 loops = %d, want 40", got) + } +} + +func TestAgenticResearchRoundCostsThreeVisits(t *testing.T) { + // One research round is rag_agent → draft → sca. If the loop counted + // iterations instead of node visits, 20 rounds would cost 20 instead of 60 + // and the guard would trip ~3x later than Python's. + if got, want := agenticRoundVisits, 3; got != want { + t.Fatalf("round cost = %d, want %d", got, want) + } +} + +func TestNewAgenticStateDoesNotArmBudget(t *testing.T) { + // Python :823 — the budget is armed in the formalize_question node's + // return, not at state creation, so formalization is not charged to it. + st := NewAgenticState("q", "", 3, nil) + + if !st.Deadline.IsZero() { + t.Fatalf("Deadline = %v, want zero until formalize_question runs", st.Deadline) + } +} + +func TestFormalizeQuestionNodeArmsBudget(t *testing.T) { + st := NewAgenticState("when did it open?", "", 3, nil) + // No model: the node still arms the budget, mirroring Python :823. + formalizeQuestionNode(context.Background(), RAGTools{}, st, nil) + + if st.Deadline.IsZero() { + t.Fatal("formalize_question must arm the budget (Python :823)") + } + if st.Question != "when did it open?" { + t.Fatalf("Question = %q, want it unchanged without a model", st.Question) + } +} + +// TestRecordConsecutiveUnanswerableAcrossOuterRagCalls mirrors the Python +// outer react loop in dialog_service.rag_agent: the model may call rag() +// several times within one user turn, and each unsatisfying verdict should +// bump the shared _consecutive_unanswerable counter. Go keeps that counter on +// the *RAGCache that Rag() now builds before the outer-react branch, so the +// same cache is reused across the outer loop's multiple rag() calls. This test +// simulates two such outer rag() calls with INSUFFICIENT verdicts and asserts +// the counter reaches 2 — the threshold at which Rag() tells the outer agent to +// STOP calling rag again. +func TestRecordConsecutiveUnanswerableAcrossOuterRagCalls(t *testing.T) { + cache := NewRAGCache() + + // First outer rag() call — unsatisfying verdict bumps the counter to 1. + recordConsecutiveUnanswerable(cache, VerdictInsufficient) + if cache.ConsecutiveUnanswerable != 1 { + t.Fatalf("after 1st outer rag() call: ConsecutiveUnanswerable = %d, want 1", + cache.ConsecutiveUnanswerable) + } + + // Second outer rag() call — still unsatisfying: counter must reach 2 so the + // STOP guard can fire (the state the pre-fix code could never reach on the + // outer path, because deps.Cache was nil and the increment was skipped). + recordConsecutiveUnanswerable(cache, VerdictInsufficient) + if cache.ConsecutiveUnanswerable != 2 { + t.Fatalf("after 2nd outer rag() call: ConsecutiveUnanswerable = %d, want 2", + cache.ConsecutiveUnanswerable) + } + + // A satisfying verdict resets the streak, matching Python rag (:921-924). + recordConsecutiveUnanswerable(cache, VerdictSufficient) + if cache.ConsecutiveUnanswerable != 0 { + t.Fatalf("after a SUFFICIENT verdict: ConsecutiveUnanswerable = %d, want 0", + cache.ConsecutiveUnanswerable) + } +} + +// TestRecordConsecutiveUnanswerableNoCacheIsNoOp makes sure the guard is safe +// when no cache is wired (nil deps.Cache): the helper must not panic and the +// outer loop simply loses the cross-call STOP protection — which is exactly +// why Rag() now auto-builds a cache before branching into the outer react loop. +func TestRecordConsecutiveUnanswerableNoCacheIsNoOp(t *testing.T) { + // Must not panic with a nil cache. + recordConsecutiveUnanswerable(nil, VerdictInsufficient) + recordConsecutiveUnanswerable(nil, VerdictSufficient) +} diff --git a/internal/rag/advanced_rag/agentic_rag_test.go b/internal/rag/advanced_rag/agentic_rag_test.go new file mode 100644 index 00000000000..9fcfb409f5c --- /dev/null +++ b/internal/rag/advanced_rag/agentic_rag_test.go @@ -0,0 +1,503 @@ +// +// 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. +// + +package advanced_rag + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/cloudwego/eino/schema" + "ragflow/internal/rag/advanced_rag/harness" +) + +type muxChunk struct { + text string + isThink bool +} + +func newTestMux() (*outerStreamMux, *[]muxChunk) { + got := make([]muxChunk, 0) + mux := &outerStreamMux{sink: &AnswerSink{OnDelta: func(delta string, isThink bool) { + got = append(got, muxChunk{delta, isThink}) + }}} + return mux, &got +} + +// The outer model's stream carries literal / markers, which the +// mux must turn into the sink's isThink flag instead of forwarding as text. +func TestOuterStreamMuxRoutesThinkThenAnswer(t *testing.T) { + mux, got := newTestMux() + for _, d := range []string{"", "reasoning", "", "the answer"} { + text := d + if err := mux.sender(&text, nil); err != nil { + t.Fatalf("sender(%q): %v", d, err) + } + } + + want := []muxChunk{{"reasoning", true}, {"the answer", false}} + if len(*got) != len(want) { + t.Fatalf("got %v, want %v", *got, want) + } + for i, w := range want { + if (*got)[i] != w { + t.Fatalf("chunk %d = %v, want %v", i, (*got)[i], w) + } + } +} + +// Python drops outer text once the terminal tool fired, because what follows is +// the aggregate tool result and the answer already streamed from inside. +func TestOuterStreamMuxDropsTextAfterTerminalFired(t *testing.T) { + mux, got := newTestMux() + mux.markTerminal() + + plain := "aggregate tool result" + if err := mux.sender(&plain, nil); err != nil { + t.Fatalf("sender: %v", err) + } + if len(*got) != 0 { + t.Fatalf("got %v, want the non-think text dropped after terminal fired", *got) + } + + // Thinking text is still forwarded even after the terminal fired. + open := "" + late := "late thinking" + if err := mux.sender(&open, nil); err != nil { + t.Fatalf("sender: %v", err) + } + if err := mux.sender(&late, nil); err != nil { + t.Fatalf("sender: %v", err) + } + if len(*got) != 1 || (*got)[0] != (muxChunk{"late thinking", true}) { + t.Fatalf("got %v, want only the late thinking chunk", *got) + } +} + +// The inner run's research log and composed answer reach the same sink. +func TestOuterStreamMuxDeliversInnerStream(t *testing.T) { + mux, got := newTestMux() + mux.deliver("[Research] planning\n", true) + mux.deliver("final answer", false) + + want := []muxChunk{{"[Research] planning\n", true}, {"final answer", false}} + if len(*got) != len(want) { + t.Fatalf("got %v, want %v", *got, want) + } + for i, w := range want { + if (*got)[i] != w { + t.Fatalf("chunk %d = %v, want %v", i, (*got)[i], w) + } + } +} + +// A nil sink must not panic: the mux is built even when the caller supplied no +// AnswerSink. +func TestOuterStreamMuxNilSinkIsSafe(t *testing.T) { + mux := &outerStreamMux{} + text := "anything" + if err := mux.sender(&text, nil); err != nil { + t.Fatalf("sender: %v", err) + } + mux.deliver("anything", true) + mux.markTerminal() +} + +func TestQuestionKeywordsSeparatesNumbers(t *testing.T) { + gram := questionKeywords("Population of Paris in 2019") + + if !gram.numbers["2019"] { + t.Fatalf("numbers = %v, want 2019 separated out", gram.numbers) + } + if gram.words["2019"] { + t.Fatal("2019 must not count as a significant word") + } + if !gram.words["population"] || !gram.words["paris"] { + t.Fatalf("words = %v, want population and paris", gram.words) + } + // Stopwords are dropped. + if gram.words["of"] || gram.words["in"] { + t.Fatalf("words = %v, stopwords must be dropped", gram.words) + } +} + +func TestCacheSimilarCollapsesReask(t *testing.T) { + // Python's observed re-ask: "legal population" → "estimated population of + // Paris in 2019" (overlap 0.75 while numbers match). + a := questionKeywords("population of Paris 2019") + b := questionKeywords("legal population of Paris in 2019") + + if !cacheSimilar(a, b) { + t.Fatal("near-identical re-ask must be judged similar") + } +} + +func TestCacheSimilarRejectsDifferentNumbers(t *testing.T) { + // Different years are different questions and must not share an answer. + a := questionKeywords("population of Paris 2019") + b := questionKeywords("population of Paris 2015") + + if cacheSimilar(a, b) { + t.Fatal("questions naming different numbers must not be similar") + } +} + +func TestCacheSimilarRejectsDifferentSubjects(t *testing.T) { + // Paris vs. Brown County ≈ 0.25 overlap. + a := questionKeywords("population of Paris 2019") + b := questionKeywords("population of Brown County 2019") + + if cacheSimilar(a, b) { + t.Fatal("genuinely different questions must not be similar") + } +} + +func TestCacheLookupAndStore(t *testing.T) { + c := NewRAGCache() + c.Store("population of Paris 2019", "2.1 million") + + got, ok := c.Lookup("legal population of Paris in 2019") + if !ok || got != "2.1 million" { + t.Fatalf("Lookup = %q, %v; want the cached answer", got, ok) + } +} + +func TestCacheLookupMissesUnrelatedQuestion(t *testing.T) { + c := NewRAGCache() + c.Store("population of Paris 2019", "2.1 million") + + if _, ok := c.Lookup("who wrote the book about Brown County"); ok { + t.Fatal("unrelated question must not hit the cache") + } +} + +func TestCacheReuseBlockedAfterInsufficientRound(t *testing.T) { + // Python :848-852 — when the last round was not SUFFICIENT the caller is + // asking again for more evidence, so the cached answer must not be reused. + c := NewRAGCache() + c.Store("population of Paris 2019", "2.1 million") + c.noteVerdict("INSUFFICIENT") + + if _, ok := c.Lookup("legal population of Paris in 2019"); ok { + t.Fatal("reuse must be blocked after an INSUFFICIENT round") + } + + c.noteVerdict("SUFFICIENT") + if _, ok := c.Lookup("legal population of Paris in 2019"); !ok { + t.Fatal("reuse must resume once the round is sufficient") + } +} + +func TestRagDefaultsToPerTurnCache(t *testing.T) { + // Go mirrors Python's default-on, per-turn _rag_cache: Rag auto-builds a + // RAGCache when deps.Cache is nil, so caching is never off. Two independent + // instances never share, matching Python's per-turn RAGTools._rag_cache + // (rebuilt every turn). + a := NewRAGCache() + b := NewRAGCache() + a.Store("population of Paris 2019", "2.1 million") + + if _, ok := b.Lookup("legal population of Paris in 2019"); ok { + t.Fatal("an independent cache must not hit another instance's answer") + } + + // A nil cache is still inert to direct calls (Rag builds its own internally + // only for the duration of the call), so no cross-call reuse happens without + // an explicitly shared instance. + var nilCache *RAGCache + if _, ok := nilCache.Lookup("population of Paris 2019"); ok { + t.Fatal("a nil cache must never hit") + } +} + +func TestCacheSharedWhenCallerInjectsSameInstance(t *testing.T) { + // A caller may widen reuse beyond one request by injecting the same + // *RAGCache via RAGTools.Cache (e.g. across `rag` tool calls within a turn). + c := NewRAGCache() + c.Store("population of Paris 2019", "2.1 million") + c2 := c // same instance passed on a later call + + if _, ok := c2.Lookup("legal population of Paris in 2019"); !ok { + t.Fatal("an injected shared cache must reuse answers across calls") + } +} + +func TestNilCacheIsInert(t *testing.T) { + var c *RAGCache + + if _, ok := c.Lookup("anything"); ok { + t.Fatal("nil cache must not hit") + } + c.Store("q", "a") // must not panic + c.noteVerdict("SUFFICIENT") +} + +func TestResolveEffectiveQuestionPrefersOriginal(t *testing.T) { + // The outer rewrite dropped the final target of a multi-hop question. + got := resolveEffectiveQuestion( + "when did the purchaser die", + "when did the purchaser of the shortest abbreviation die", + ) + + if got != "when did the purchaser of the shortest abbreviation die" { + t.Fatalf("got %q, want the original question", got) + } +} + +func TestResolveEffectiveQuestionKeepsDifferentTurn(t *testing.T) { + // A genuine re-ask for a different question must keep its own query. + got := resolveEffectiveQuestion("population of Brown County", "population of Paris 2019") + + if got != "population of Brown County" { + t.Fatalf("got %q, want the rewrite kept for a different question", got) + } +} + +func TestResolveEffectiveQuestionHandlesEmpty(t *testing.T) { + if got := resolveEffectiveQuestion("q", ""); got != "q" { + t.Fatalf("got %q, want q", got) + } + if got := resolveEffectiveQuestion("", "orig"); got != "" { + t.Fatalf("got %q, want empty", got) + } +} + +// TestResearchStatusTrailerStopsAfterTwoUnanswerable asserts that once the +// shared counter has reached 2, Rag() appends the "STOP calling rag again" +// trailing sentence (Python rag:902-929) for an INSUFFICIENT verdict — the +// visible effect of the consecutive-unanswerable guard across multiple outer +// rag() calls. +func TestResearchStatusTrailerStopsAfterTwoUnanswerable(t *testing.T) { + cache := NewRAGCache() + cache.ConsecutiveUnanswerable = 2 + resp := &RunResponse{ + Verdict: VerdictInsufficient, + SCAFeedback: "evidence is not yet sufficient", + Answer: "Partial findings.", + } + got := researchStatusTrailer(cache, resp) + if !strings.Contains(got, "STOP calling rag again") { + t.Fatalf("trailer = %q, want it to tell the outer agent to STOP calling rag again", got) + } +} + +// TestResearchStatusTrailerInvitesFocusedReaskBelowTwo covers the first +// unsatisfying outer rag() call (counter < 2): Rag() should invite a focused +// re-ask rather than tell the agent to stop. + +// TestResearchStatusTrailerInvitesFocusedReaskBelowTwo covers the first +// unsatisfying outer rag() call (counter < 2): Rag() should invite a focused +// re-ask rather than tell the agent to stop. +func TestResearchStatusTrailerInvitesFocusedReaskBelowTwo(t *testing.T) { + cache := NewRAGCache() + cache.ConsecutiveUnanswerable = 1 + resp := &RunResponse{ + Verdict: VerdictInsufficient, + SCAFeedback: "evidence is not yet sufficient", + Answer: "Partial findings.", + } + got := researchStatusTrailer(cache, resp) + if !strings.Contains(got, "call rag again with a question focused on them") { + t.Fatalf("trailer = %q, want a focused re-ask invite (not STOP)", got) + } + if strings.Contains(got, "STOP calling rag again") { + t.Fatalf("trailer = %q, did not expect STOP below threshold", got) + } +} + +// TestResearchStatusTrailerSkipsSufficientOrEmpty ensures the note is omitted +// when there is nothing to annotate: a SUFFICIENT verdict, an empty answer, or +// missing SCA feedback all yield "". + +// TestResearchStatusTrailerSkipsSufficientOrEmpty ensures the note is omitted +// when there is nothing to annotate: a SUFFICIENT verdict, an empty answer, or +// missing SCA feedback all yield "". +func TestResearchStatusTrailerSkipsSufficientOrEmpty(t *testing.T) { + cache := NewRAGCache() + cache.ConsecutiveUnanswerable = 2 + + cases := []struct { + name string + resp *RunResponse + }{ + {"sufficient verdict", &RunResponse{Verdict: VerdictSufficient, SCAFeedback: "ok", Answer: "A"}}, + {"empty answer", &RunResponse{Verdict: VerdictInsufficient, SCAFeedback: "x", Answer: ""}}, + {"missing sca feedback", &RunResponse{Verdict: VerdictInsufficient, SCAFeedback: "", Answer: "A"}}, + } + for _, c := range cases { + if got := researchStatusTrailer(cache, c.resp); got != "" { + t.Errorf("%s: trailer = %q, want empty", c.name, got) + } + } +} + +// streamingModel is a SessionModel that can also stream. +type streamingModel struct { + pieces []string + fail bool +} + +func (m *streamingModel) Complete(_ context.Context, _ []schema.Message, _ []harness.ToolSpec) (*harness.ModelReply, error) { + if m.fail { + return nil, errors.New("boom") + } + out := "" + for _, p := range m.pieces { + out += p + } + return &harness.ModelReply{Content: out}, nil +} + +func (m *streamingModel) StreamComplete(_ context.Context, _ []schema.Message, _ []harness.ToolSpec, onDelta func(string, bool) error) (*harness.ModelReply, error) { + if m.fail { + return nil, errors.New("stream boom") + } + out := "" + for _, p := range m.pieces { + if onDelta != nil { + if err := onDelta(p, false); err != nil { + return nil, err + } + } + out += p + } + return &harness.ModelReply{Content: out}, nil +} + +func TestComposeAnswerStreamForwardsDeltas(t *testing.T) { + m := &streamingModel{pieces: []string{"Hello ", "world"}} + var got []string + res, err := ComposeAnswerStream(context.Background(), AnswerDeps{Model: m}, m, nil, "q", false, + func(delta string, _ bool) error { + got = append(got, delta) + return nil + }) + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if res.Answer != "Hello world" { + t.Fatalf("Answer = %q, want %q", res.Answer, "Hello world") + } + if len(got) != 2 || got[0] != "Hello " || got[1] != "world" { + t.Fatalf("deltas = %v, want the two pieces in order", got) + } +} + +func TestComposeAnswerStreamReturnsErrorOnFailure(t *testing.T) { + m := &streamingModel{fail: true} + + if _, err := ComposeAnswerStream(context.Background(), AnswerDeps{Model: m}, m, nil, "q", false, nil); err == nil { + t.Fatal("want an error so the caller can fall back to one-shot") + } +} + +func TestAnswerSinkDeliverAndReset(t *testing.T) { + var got []string + resets := 0 + s := &AnswerSink{ + OnDelta: func(delta string, _ bool) { got = append(got, delta) }, + OnReset: func() { resets++; got = nil }, + } + + s.deliver("a", false) + s.deliver("b", false) + s.reset() + + if len(got) != 0 || resets != 1 { + t.Fatalf("after reset: got=%v resets=%d, want empty and 1", got, resets) + } + s.deliver("", false) // empty deltas are dropped + if len(got) != 0 { + t.Fatalf("got = %v, want empty delta dropped", got) + } +} + +func TestNilAnswerSinkIsInert(t *testing.T) { + var s *AnswerSink + + s.deliver("x", false) // must not panic + s.reset() +} + +func TestGetCitationGuidelinesUsesDefaultWithoutOverride(t *testing.T) { + got := GetCitationGuidelines("") + // The default is the embedded citation_prompt.md (mirrors Python + // load_prompt("citation_prompt")). It must contain the citation-rules body. + if !strings.Contains(got, "# Citation Requirements:") || + !strings.Contains(got, "Place citations at the end of sentences") { + t.Fatalf("got %q, want the default citation rules", got) + } +} + +func TestGetCitationGuidelinesHonoursOverride(t *testing.T) { + // Python renders the user's template; Go takes the rendered result verbatim. + got := GetCitationGuidelines("Cite as [n].") + if got != "Cite as [n]." { + t.Fatalf("got %q, want the override", got) + } +} + +func TestSysPromptIncludesSummarizeOnlyWithUnstructured(t *testing.T) { + withDoc := SysPrompt("", true) + if !strings.Contains(withDoc, "summarize_document") { + t.Fatal("summarize_document must be offered when unstructured retrieval exists") + } + withoutDoc := SysPrompt("", false) + if strings.Contains(withoutDoc, "summarize_document") { + t.Fatal("summarize_document must be omitted without unstructured retrieval") + } +} + +func TestSysPromptPrependsSystemPrompt(t *testing.T) { + got := SysPrompt("You are helpful.", true) + + if !strings.HasPrefix(got, "You are helpful.\n\n") { + t.Fatalf("got %q, want the system prompt first", got) + } + if !strings.Contains(got, "call the `rag` tool") { + t.Fatalf("got %q, want the router body kept", got) + } +} + +func TestFitEvidenceKeepsShortEvidence(t *testing.T) { + evidence := "short evidence" + if got := FitEvidence("q", evidence); got != evidence { + t.Fatalf("got %q, want %q unchanged", got, evidence) + } +} + +func TestFitEvidenceReturnsEmptyForEmpty(t *testing.T) { + if got := FitEvidence("q", ""); got != "" { + t.Fatalf("got %q, want empty", got) + } +} + +func TestFitEvidenceTrimsOversizedEvidence(t *testing.T) { + // The budget is fixed (not the model window), so a large pool can never fill + // the context — evidence beyond the cap must be dropped. + evidence := strings.Repeat("word ", 200000) + got := FitEvidence("q", evidence) + + if len(got) >= len(evidence) { + t.Fatalf("evidence was not trimmed: %d >= %d", len(got), len(evidence)) + } + if got == "" { + t.Fatal("evidence must not be trimmed to nothing") + } +} diff --git a/internal/rag/advanced_rag/agentic_rag_util.go b/internal/rag/advanced_rag/agentic_rag_util.go new file mode 100644 index 00000000000..f85a83d402b --- /dev/null +++ b/internal/rag/advanced_rag/agentic_rag_util.go @@ -0,0 +1,23 @@ +package advanced_rag + +import "time" + +// trunc truncates s to at most n bytes, returning s unchanged when it already +// fits. Mirrors the harness helper of the same name; kept local so the +// consolidated RAGTools methods do not depend on unexported harness symbols. +func trunc(s string, n int) string { + if len(s) <= n { + return s + } + return s[:n] +} + +// deadlineToDuration converts a seconds budget to a context deadline. A +// non-positive budget falls back to the default answer timeout so a caller that +// omits it does not produce an already-expired context. +func deadlineToDuration(seconds float64) time.Duration { + if seconds <= 0 { + seconds = answerTimeoutS + } + return time.Duration(seconds * float64(time.Second)) +} diff --git a/internal/rag/advanced_rag/harness/action_session.go b/internal/rag/advanced_rag/harness/action_session.go new file mode 100644 index 00000000000..75260cd5176 --- /dev/null +++ b/internal/rag/advanced_rag/harness/action_session.go @@ -0,0 +1,3570 @@ +// +// 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. +// + +package harness + +import ( + "context" + "crypto/rand" + "encoding/json" + "fmt" + "math" + "regexp" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/RealAlexandreAI/json-repair" + "github.com/cloudwego/eino/compose" + "github.com/cloudwego/eino/schema" + "gorm.io/gorm" + + "ragflow/internal/agent/chat" + "ragflow/internal/rag/prompts" + + "ragflow/internal/common" +) + +// action_session.go consolidates the Go port of Python harness/action_session.py +// that was previously split across sessiontypes.go, extract.go, toolschema.go, +// run.go, navchain.go, and session.go. The split is preserved as clearly marked +// section banners below; every symbol keeps its original name and behavior so +// tool_executor.go and the tests are unaffected. +// +// The section ORDER mirrors Python action_session.py's source order +// (helpers → classes → tool specs → executors → model seam → _SessionState → +// nodes → nav prefix → entry points at the end), not a Go dependency order. + +// ===================== sessiontypes.go ===================== +// Slot-table models and the unified tool-result +// +// Mirrors Python harness/action_session.py: +// - Variable / State / Result (lines 80-149) +// - tool status constants (lines 157-162) +// - ToolOutcome (lines 165-183) +// - apply_patch (line 574) + +// Variable is one unknown entity to resolve. ID is immutable across patches. +type Variable struct { + ID int + Type string + QuestionClues []string + DiscoveredClues []string + Candidate *string + CandidateStrength *float64 +} + +// Brief mirrors Python Variable.brief: one-line rendering for prompts. +func (v Variable) Brief() string { + if v.Candidate != nil && *v.Candidate != "" { + cs := "?" + if v.CandidateStrength != nil { + cs = fmt.Sprintf("%.2f", *v.CandidateStrength) + } + return fmt.Sprintf("[%d] %s: %s (%s)", v.ID, v.Type, *v.Candidate, cs) + } + return fmt.Sprintf("[%d] %s: EMPTY", v.ID, v.Type) +} + +// Filled mirrors Python Variable.filled. +func (v Variable) Filled() bool { return v.Candidate != nil && *v.Candidate != "" } + +// State is the slot table carried through one action session. +type State struct { + State []Variable + Depth int + ID string + RetrievedEvidenceIDs []string +} + +// NewState builds a State, generating its ID the way Python's +// __post_init__ does: "_<1 random byte:02x>". +func NewState(vars []Variable, depth int, evidenceIDs []string) State { + s := State{ + State: vars, + Depth: depth, + RetrievedEvidenceIDs: evidenceIDs, + } + if s.ID == "" { + s.ID = newStateID(depth) + } + return s +} + +// newStateID mirrors Python State.__post_init__'s id scheme. +func newStateID(depth int) string { + ms := time.Now().UnixMilli() % 100000000 + var b [1]byte + _, _ = rand.Read(b[:]) + return fmt.Sprintf("%03x_%08x%02x", depth, ms, b[0]) +} + +// Unresolved mirrors Python State.unresolved: slots still missing a candidate. +func (s State) Unresolved() []Variable { + out := make([]Variable, 0, len(s.State)) + for _, v := range s.State { + if !v.Filled() { + out = append(out, v) + } + } + return out +} + +// ByID mirrors Python State.by_id. Returns nil when no slot carries vid. +func (s *State) ByID(vid int) *Variable { + for i := range s.State { + if s.State[i].ID == vid { + return &s.State[i] + } + } + return nil +} + +// Brief mirrors Python State.brief: e.g. "d0(++. )". +func (s State) Brief() string { + var b strings.Builder + b.WriteString(fmt.Sprintf("d%d(", s.Depth)) + for _, v := range s.State { + if v.Filled() { + b.WriteByte('+') + } else { + b.WriteByte('.') + } + } + b.WriteByte(')') + return b.String() +} + +// RenderSlots mirrors Python State.render_slots: the multi-line prompt block +// listing every slot, its clues, and any candidate found so far. +func (s State) RenderSlots() string { + var lines []string + for _, v := range s.State { + line := fmt.Sprintf("- id=%d type=%s", v.ID, v.Type) + if len(v.QuestionClues) > 0 { + line += "\n question_clues: " + strings.Join(v.QuestionClues, "; ") + } + if len(v.DiscoveredClues) > 0 { + tail := v.DiscoveredClues + if len(tail) > 4 { + tail = tail[len(tail)-4:] + } + line += "\n discovered_clues: " + strings.Join(tail, "; ") + } + if v.Candidate != nil && *v.Candidate != "" { + cs := "?" + if v.CandidateStrength != nil { + cs = fmt.Sprintf("%.2f", *v.CandidateStrength) + } + line += fmt.Sprintf("\n CANDIDATE: %s (strength=%s)", *v.Candidate, cs) + } + lines = append(lines, line) + } + return strings.Join(lines, "\n") +} + +// Result is the outcome of ONE run_action session (one of NewStates / +// FoundAnswer). +// +// Messages is typed as []schema.Message rather than Python's untyped list: the +// session builds them through the eino constructors, and a typed slice keeps +// the conversation inspectable (and testable) without type assertions. +type Result struct { + Messages []schema.Message + NewStates []State + FoundAnswer *string + RetrievedEvidenceIDs []string + TerminalType *string + TerminalPayload map[string]any +} + +// ApplyPatch mirrors Python apply_patch: ONLY existing +// ids are patchable; the mutable fields are candidate / candidate_strength / +// discovered_clues. ID is immutable, so patches may not add variables. +// +// Returns nil when a patch entry is malformed (not a map, or missing "id") or +// when nothing actually changed — both mirror Python's early returns. +func ApplyPatch(base State, branchPatches []map[string]any) *State { + newVars := make([]Variable, 0, len(base.State)) + for _, v := range base.State { + nv := Variable{ + ID: v.ID, + Type: v.Type, + QuestionClues: append([]string(nil), v.QuestionClues...), + DiscoveredClues: append([]string(nil), v.DiscoveredClues...), + Candidate: v.Candidate, + CandidateStrength: v.CandidateStrength, + } + newVars = append(newVars, nv) + } + + changed := false + for _, pv := range branchPatches { + if pv == nil { + return nil + } + rawID, ok := pv["id"] + if !ok { + return nil + } + // Python compares `nv.id == pv["id"]` with ints, so a JSON string id + // ("1") simply matches no slot and is skipped. Only JSON numbers match, + // which decode as float64 — accept those, and reject anything else so the + // behaviour is identical rather than silently more permissive. + want, ok := toIntStrict(rawID) + if !ok { + continue + } + idx := -1 + for i := range newVars { + if newVars[i].ID == want { + idx = i + break + } + } + if idx < 0 { + continue + } + nv := &newVars[idx] + + if raw, has := pv["candidate"]; has { + // Mirror Python apply_patch: `str(x) if x else None` — any falsy + // value (0, 0.0, False, "", [], {}, None) becomes None, NOT its + // string form. fmt.Sprint would otherwise turn 0/False into + // "0"/"false", which Python drops. + if !isTruthy(raw) { + nv.Candidate = nil + } else { + s := fmt.Sprint(raw) + nv.Candidate = &s + } + changed = true + } + if raw, has := pv["candidate_strength"]; has && raw != nil { + if f, ok := toFloat(raw); ok { + v := math.Min(math.Max(f, 0.0), 1.0) + nv.CandidateStrength = &v + changed = true + } + // Unparseable strengths are ignored, mirroring Python's except/pass. + } + if raw, has := pv["discovered_clues"]; has { + if list, ok := raw.([]any); ok { + tail := list + if len(tail) > 4 { + tail = tail[len(tail)-4:] + } + for _, c := range tail { + nv.DiscoveredClues = append(nv.DiscoveredClues, truncateRunes(fmt.Sprint(c), 160)) + } + changed = true + } + } + } + if !changed { + return nil + } + out := State{ + State: newVars, + Depth: base.Depth + 1, + RetrievedEvidenceIDs: append([]string(nil), base.RetrievedEvidenceIDs...), + } + out.ID = newStateID(out.Depth) + return &out +} + +// truncateRunes cuts s to at most n characters (runes, not bytes), matching +// Python's str slicing semantics. +func truncateRunes(s string, n int) string { + if len([]rune(s)) <= n { + return s + } + return string([]rune(s)[:n]) +} + +// toInt coerces a JSON-decoded value to int. Handles float64 (the default for +// JSON numbers), the integer types, and numeric strings. +func toInt(v any) (int, bool) { + switch n := v.(type) { + case int: + return n, true + case int32: + return int(n), true + case int64: + return int(n), true + case float32: + return int(n), true + case float64: + return int(n), true + case string: + if i, err := strconv.Atoi(strings.TrimSpace(n)); err == nil { + return i, true + } + } + return 0, false +} + +// toIntStrict converts JSON NUMBER types only, mirroring Python's strict +// integer comparison. Unlike toInt it does NOT parse strings: a patch whose id +// is "1" must match nothing, exactly as in Python. +func toIntStrict(v any) (int, bool) { + switch n := v.(type) { + case int: + return n, true + case int32: + return int(n), true + case int64: + return int(n), true + case float32: + return int(n), true + case float64: + return int(n), true + } + return 0, false +} + +// toFloat coerces a JSON-decoded value to float64. +func toFloat(v any) (float64, bool) { + switch n := v.(type) { + case float64: + return n, true + case float32: + return float64(n), true + case int: + return float64(n), true + case int32: + return float64(n), true + case int64: + return float64(n), true + case string: + return ParseFloat(n) + } + return 0, false +} + +// ParseFloat parses a float64 from a string, tolerating surrounding +// whitespace. Exported for the orchestrator package, whose SCA verdict +// coercion needs the same lenient parsing. +func ParseFloat(s string) (float64, bool) { + f, err := strconv.ParseFloat(strings.TrimSpace(s), 64) + if err != nil { + return 0, false + } + return f, true +} + +// isTruthy mirrors Python's bool() truthiness for the JSON-decoded values that +// reach apply_patch: None/nil, empty string/collection, zero number, and False +// are falsy; everything else (including non-empty objects and any other type) is +// truthy. Used so `str(x) if x else None` behaves identically in Go. +func isTruthy(v any) bool { + switch x := v.(type) { + case nil: + return false + case bool: + return x + case string: + return x != "" + case int: + return x != 0 + case int32: + return x != 0 + case int64: + return x != 0 + case float32: + return x != 0 + case float64: + return x != 0 + case []any: + return len(x) > 0 + case []string: + return len(x) > 0 + case map[string]any: + return len(x) > 0 + default: + return true + } +} + +// --------------------------------------------------------------------------- +// Python value coercion (str / int / repr) +// +// initialize_state parses the model's slot-table reply with Python semantics: +// `int(s.get("id", i))`, `str(s.get("type") or "entity")` and +// `[str(c) for c in (s.get("clues") or [])]`. A value Python cannot convert +// RAISES, and _build_slot_table catches that and falls back to the planner +// fan-outs — so these helpers report failure instead of guessing, and the caller +// discards the whole decomposition. PyStringRepr/PyValueRepr are also the single +// implementation of Python's repr() (used by the research ledger's +// `str(messages)[:80]` emulation in the advanced_rag package). +// --------------------------------------------------------------------------- + +// PyStringRepr mirrors Python's repr() for str: single quotes unless the text +// contains ' but no ", with the standard escapes (\\, \n, \r, \t, \xNN for other +// control characters). Printable non-ASCII is kept verbatim, as in Python 3. +func PyStringRepr(s string) string { + quote := '\'' + if strings.ContainsRune(s, '\'') && !strings.ContainsRune(s, '"') { + quote = '"' + } + var b strings.Builder + b.WriteRune(quote) + for _, r := range s { + switch { + case r == quote: + b.WriteByte('\\') + b.WriteRune(r) + case r == '\\': + b.WriteString(`\\`) + case r == '\n': + b.WriteString(`\n`) + case r == '\r': + b.WriteString(`\r`) + case r == '\t': + b.WriteString(`\t`) + case r < 0x20 || r == 0x7f: + b.WriteString(fmt.Sprintf(`\x%02x`, r)) + default: + b.WriteRune(r) + } + } + b.WriteRune(quote) + return b.String() +} + +// PyValueRepr mirrors Python's repr() for a JSON-decoded value. Map keys are +// rendered in sorted order: Go's maps do not preserve the JSON text's insertion +// order, which is the one thing this cannot reproduce. +func PyValueRepr(v any) string { + switch t := v.(type) { + case nil: + return "None" + case bool: + if t { + return "True" + } + return "False" + case string: + return PyStringRepr(t) + case float64: + return strconv.FormatFloat(t, 'g', -1, 64) + case float32: + return strconv.FormatFloat(float64(t), 'g', -1, 32) + case int: + return strconv.Itoa(t) + case int32: + return strconv.FormatInt(int64(t), 10) + case int64: + return strconv.FormatInt(t, 10) + case []any: + parts := make([]string, 0, len(t)) + for _, item := range t { + parts = append(parts, PyValueRepr(item)) + } + return "[" + strings.Join(parts, ", ") + "]" + case map[string]any: + keys := make([]string, 0, len(t)) + for k := range t { + keys = append(keys, k) + } + sort.Strings(keys) + parts := make([]string, 0, len(keys)) + for _, k := range keys { + parts = append(parts, PyStringRepr(k)+": "+PyValueRepr(t[k])) + } + return "{" + strings.Join(parts, ", ") + "}" + default: + return PyStringRepr(fmt.Sprint(v)) + } +} + +// PyStr mirrors Python's str(): a string is itself; every other value renders as +// its repr (which is how str() prints containers and scalars). +func PyStr(v any) string { + if s, ok := v.(string); ok { + return s + } + return PyValueRepr(v) +} + +// pyInt mirrors Python's int() for the values a slot table can carry. ok=false +// where Python raises ValueError/TypeError: a string that is not a plain integer +// (int("5.5") fails), None, or a container. +func pyInt(v any) (int, bool) { + switch n := v.(type) { + case int: + return n, true + case int32: + return int(n), true + case int64: + return int(n), true + case float32: + if math.IsNaN(float64(n)) || math.IsInf(float64(n), 0) { + return 0, false + } + return int(n), true // Python int() truncates toward zero + case float64: + if math.IsNaN(n) || math.IsInf(n, 0) { + return 0, false + } + return int(n), true + case bool: + // Python's bool is an int subclass: int(True) == 1. + if n { + return 1, true + } + return 0, true + case string: + // Python int(str) tolerates surrounding whitespace and "_" separators. + s := strings.ReplaceAll(strings.TrimSpace(n), "_", "") + if s == "" { + return 0, false + } + i, err := strconv.Atoi(s) + if err != nil { + return 0, false + } + return i, true + } + return 0, false +} + +// pyStringList mirrors Python's `[str(c) for c in (value or [])]`: a falsy value +// yields nothing, a list yields its items, a string its characters and a map its +// keys. ok=false when the value is not iterable (Python raises TypeError there). +func pyStringList(v any) ([]string, bool) { + if !isTruthy(v) { + return nil, true + } + switch t := v.(type) { + case []any: + out := make([]string, 0, len(t)) + for _, item := range t { + out = append(out, PyStr(item)) + } + return out, true + case []string: + return append([]string(nil), t...), true + case string: + out := make([]string, 0, len(t)) + for _, r := range t { + out = append(out, string(r)) + } + return out, true + case map[string]any: + keys := make([]string, 0, len(t)) + for k := range t { + keys = append(keys, k) + } + sort.Strings(keys) + return keys, true + default: + return nil, false + } +} + +// ===================== extract.go ===================== +// JSON / terminal-block extraction from model output. +// +// Mirrors Python action_session.py::extract_json (line 512) and extract_tag +// (line 551). Models wrap JSON in thinking preamble and Markdown fences, and +// often emit a second object after the first — a greedy regex over-captures +// there and the parse then fails with "Extra data", so the extractor +// brace-matches to isolate ONE complete object and walks to the next "{" when +// that one is invalid. + +// JSON / terminal-block extraction from model output (mirrors Python +// action_session.py::extract_json / extract_tag). + +// ExtractJSON returns the first parseable JSON value found in text, or nil. +func ExtractJSON(text string) any { + if text == "" { + return nil + } + n := len(text) + for i := 0; i < n; { + start := strings.IndexByte(text[i:], '{') + if start < 0 { + break + } + start += i + depth := 0 + for j := start; j < n; j++ { + switch text[j] { + case '{': + depth++ + case '}': + depth-- + if depth == 0 { + candidate := text[start : j+1] + var out any + if err := json.Unmarshal([]byte(candidate), &out); err == nil { + return out + } + // Python extract_json first tries json.loads(strict=False), + // then json_repair.loads(candidate); only if BOTH fail does it + // break to the next "{". Mirror that leniency here. + if v := repairJSONObject(candidate); v != nil { + return v + } + if v := repairJSONWhole(candidate); v != nil { + return v + } + // Invalid object; try the next "{". + } + } + } + i = start + 1 + } + // All brace-matched candidates failed strict and shallow repair. Python's + // extract_json ultimately falls back to json_repair.loads(text) over the WHOLE + // text, which can salvage deformities (unquoted keys, dropped separators, a + // lost outer brace) that no single brace-matched candidate can. Mirror it. + return repairJSONWhole(text) +} + +// ExtractJSONObject parses the first JSON object/array found in text, but ONLY +// from a brace/bracket-matched region. It deliberately stops short of +// repairJSONWhole's whole-text prose fallback: prose with no JSON shape (e.g. +// "I cannot produce JSON today.") returns nil so the caller can treat it as a +// parse failure. This is the right gate for gen_json-style loops, where the +// model is expected to emit JSON (possibly fenced or trailing-comma damaged) +// and a non-JSON reply must trigger a corrective retry rather than be silently +// coerced into a value. Keywords-style salvage of prose-wrapped JSON should use +// ExtractJSON instead. +func ExtractJSONObject(text string) any { + if text == "" { + return nil + } + n := len(text) + for i := 0; i < n; { + start := strings.IndexByte(text[i:], '{') + if start < 0 { + break + } + start += i + depth := 0 + for j := start; j < n; j++ { + switch text[j] { + case '{': + depth++ + case '}': + depth-- + if depth == 0 { + candidate := text[start : j+1] + var out any + if err := json.Unmarshal([]byte(candidate), &out); err == nil { + return out + } + if v := repairJSONObject(candidate); v != nil { + return v + } + // Invalid object; try the next "{". + } + } + } + i = start + 1 + } + return nil +} + +// repairJSONObject is a conservative stand-in for Python's json_repair.loads, +// applied only after a candidate fails strict json.Unmarshal. It walks cheap, +// idempotent normalizations that models commonly emit and re-validates after +// each: trailing commas, single-quoted strings, NaN/Infinity numeric literals, +// and illegal control characters inside string literals (which Python's +// json.loads(strict=False) and json_repair both tolerate). It never rewrites +// already-valid JSON and returns nil when no transform yields a parse. +func repairJSONObject(candidate string) any { + steps := []struct { + name string + apply func(string) string + }{ + {"dropTrailingCommas", dropTrailingCommas}, + {"normalizeSingleQuotes", normalizeSingleQuotes}, + {"nullNonFinite", nullNonFiniteLiterals}, + {"stripRawControlChars", stripRawControlChars}, + } + fixed := candidate + for _, s := range steps { + fixed = s.apply(fixed) // accumulate so multi-step repairs compose + var out any + if err := json.Unmarshal([]byte(fixed), &out); err == nil { + return out + } + } + return nil +} + +// dropTrailingCommas removes a comma immediately before a closing brace or +// bracket (e.g. {"a": 1,} or [1, 2,]), repeated until stable. +func dropTrailingCommas(s string) string { + for { + before := s + s = strings.ReplaceAll(s, ",}", "}") + s = strings.ReplaceAll(s, ",]", "]") + if s == before { + return s + } + } +} + +// normalizeSingleQuotes rewrites single-quoted string literals to double-quoted +// ones, mirroring json_repair. It only touches quotes outside of double-quoted +// strings so it never corrupts existing valid JSON. +func normalizeSingleQuotes(s string) string { + var b strings.Builder + inDouble := false + inSingle := false + escaped := false + for i := 0; i < len(s); i++ { + ch := s[i] + if escaped { + b.WriteByte(ch) + escaped = false + continue + } + switch ch { + case '\\': + escaped = true + b.WriteByte(ch) + case '"': + if !inSingle { + inDouble = !inDouble + } + b.WriteByte(ch) + case '\'': + if !inDouble { + inSingle = !inSingle + b.WriteByte('"') // replace single quote with double quote + } else { + b.WriteByte(ch) + } + default: + b.WriteByte(ch) + } + } + return b.String() +} + +// nullNonFiniteLiterals rewrites bare NaN / Infinity / -Infinity tokens (which +// Python's json_repair normalizes) into JSON null so the object can parse. +func nullNonFiniteLiterals(s string) string { + s = strings.ReplaceAll(s, ": NaN", ": null") + s = strings.ReplaceAll(s, ": Infinity", ": null") + s = strings.ReplaceAll(s, ": -Infinity", ": null") + return s +} + +// stripRawControlChars removes raw ASCII control characters (other than tab, +// newline and carriage-return) that would otherwise make Go's json.Unmarshal +// reject a string literal; Python's json.loads(strict=False) accepts them. +func stripRawControlChars(s string) string { + return strings.Map(func(r rune) rune { + if r < 0x20 && r != '\t' && r != '\n' && r != '\r' { + return -1 + } + return r + }, s) +} + +// repairJSONWhole is the deep fallback that mirrors Python's json_repair.loads +// on the WHOLE text (not just one brace-matched candidate). ExtractJSON first +// tries the brace-matched object and the shallow repairJSONObject steps; only +// when BOTH fail does it reach here. This salvages structural deformities that +// the single-object path cannot — unquoted object keys ({a: 1}), missing +// separators between adjacent values ({"a":1} {"b":2} or "x" "y"), bare string +// values ({name: foo}), and any combination the model emits across the full +// output. It delegates to github.com/RealAlexandreAI/json-repair, the Go port of +// the same json_repair library Python uses, so behavior matches exactly. It +// returns nil when nothing parses, exactly as json_repair would yield a parse +// error. +func repairJSONWhole(text string) any { + cleaned := reThinkWrap.ReplaceAllString(text, "") + cleaned = reFencedJSON.ReplaceAllString(cleaned, "$1") + cleaned = strings.TrimSpace(cleaned) + if cleaned == "" { + return nil + } + // Pre-normalize unquoted object keys (e.g. {entity: "x"} -> {"entity": "x"}). + // The underlying json-repair library (Go port) handles unquoted keys with + // unquoted values well but mangles a key that precedes an already-quoted + // value; quoting keys first sidesteps that and matches what Python's + // json_repair does internally. Already-valid JSON is left untouched. + normalized := quoteUnquotedKeys(cleaned) + repaired, err := jsonrepair.RepairJSON(normalized) + if err != nil { + // Fall back to the un-normalized input in case the heuristic mis-fired. + repaired, err = jsonrepair.RepairJSON(cleaned) + if err != nil { + return nil + } + } + return tryUnmarshal(repaired) +} + +// quoteUnquotedKeys wraps bare object keys in double quotes: {a: 1} -> {"a": 1}. +// It only touches a key token (identifier directly followed by a colon) that is +// not already quoted, so already-valid JSON is left untouched. The optional +// brace/bracket/comma prefix is preserved verbatim. +func quoteUnquotedKeys(s string) string { + return reUnquotedKey.ReplaceAllStringFunc(s, func(m string) string { + groups := reUnquotedKey.FindStringSubmatch(m) + return groups[1] + `"` + groups[2] + `":` + }) +} + +// reUnquotedKey matches a structural prefix ({ [ ,) plus optional whitespace, +// then a bare identifier immediately followed by a colon — the shape of an +// unquoted JSON key. Group 1 is the prefix, group 2 is the key name. +var reUnquotedKey = regexp.MustCompile(`([{\[,]\s*)([A-Za-z_][A-Za-z0-9_]*)\s*:`) + +// tryUnmarshal attempts json.Unmarshal and returns the value, or nil on failure. +func tryUnmarshal(s string) any { + if s == "" { + return nil + } + var out any + if err := json.Unmarshal([]byte(s), &out); err == nil { + return out + } + return nil +} + +var reFencedJSON = regexp.MustCompile("(?s)```(?:json)?\\s*(\\{.*?\\}|\\[.*?\\])\\s*```") + +// ExtractTag mirrors Python extract_tag: exact-tag extraction first, then +// lenient fallbacks for models that wrap the JSON in code fences or emit bare +// objects (observed with DeepSeek-class models ignoring the XML protocol). +// +// Returns "" when the tag is absent. +func ExtractTag(text, tag string) string { + if text == "" { + return "" + } + open, closeTag := "<"+tag+">", "" + s := strings.LastIndex(text, open) + e := strings.LastIndex(text, closeTag) + if s >= 0 && e > s { + return strings.TrimSpace(text[s+len(open) : e]) + } + // Fenced ```json ... ``` blocks mentioning the tag name. + fenced := reFencedJSON.FindAllStringSubmatch(text, -1) + if len(fenced) == 0 { + if m, _ := regexp.MatchString(`<`+regexp.QuoteMeta(tag)+`\b`, text); !m { + return "" + } + return "" + } + want := map[string]bool{"new_states": true} + if tag != "state" { + want = map[string]bool{"answer": true, "new_state": true} + } + // Prefer the LAST block (most recent decision). + for i := len(fenced) - 1; i >= 0; i-- { + var obj map[string]any + if err := json.Unmarshal([]byte(fenced[i][1]), &obj); err != nil { + continue + } + for k := range obj { + if want[k] { + return strings.TrimSpace(fenced[i][1]) + } + } + } + return "" +} + +// ===================== toolschema.go ===================== +// Tool schemas, the per-session tool object, and the two seams the action +// session depends on. +// +// Mirrors Python harness/action_session.py: +// - tool specs (lines 187-437) +// - _TOOL_MAP (line 428) +// - _active_tool_specs(line 440) +// - _disable_tool (line 472) +// - _reason_status (line 495) +// - execute_tool (line 1003) + +func arrayParam(desc string, minItems, maxItems int) map[string]any { + return map[string]any{ + "type": "object", + "properties": map[string]any{ + "query": map[string]any{ + "type": "array", + "items": map[string]any{"type": "string"}, + "minItems": minItems, + "maxItems": maxItems, + }, + }, + "required": []string{"query"}, + } +} + +// Tool schemas. Descriptions are copied verbatim from Python: they are the +// model's only guide for when to pick which tool, and rephrasing them changes +// routing behaviour. +var ( + retrieveToolSpec = ToolSpec{ + Type: "function", + Function: ToolFunction{ + Name: "retrieve", + Description: ("Keyword-first search of the fixed document corpus. Pass natural-" + + "language queries; returns SHORT snippets of the most relevant " + + "passages (exact-term matched where possible). Use multiple queries " + + "to cover different aspects. Supports 1-3 queries per call."), + Parameters: arrayParam("", 1, 3), + }, + } + + listChunksToolSpec = ToolSpec{ + Type: "function", + Function: ToolFunction{ + Name: "list_chunks", + Description: ("Deep-read the FULL text of one document by doc_id (returned in " + + "retrieve snippets). Use for enumeration / count / arithmetic answers " + + "when snippets are insufficient. Returns all chunks of the document " + + "in reading order. One doc_id per call."), + Parameters: map[string]any{ + "type": "object", + "properties": map[string]any{ + "doc_id": map[string]any{ + "type": "string", + "description": "document id seen in a retrieve snippet", + }, + }, + "required": []string{"doc_id"}, + }, + }, + } + + searchChunksToolSpec = ToolSpec{ + Type: "function", + Function: ToolFunction{ + Name: "search_chunks", + Description: ("SEMANTIC retrieval (hybrid vector+BM25) with COMPILED-STRUCTURE " + + "EXPANSION. Use as the PRIMARY recall tool when exact-term " + + "``retrieve`` returns nothing useful, or when the dataset is large and " + + "you are unsure which document holds the answer — the answer passage " + + "may share NO surface words with the query. " + + "Compiled expansion: automatically appends related chunks from the " + + "dataset's compiled structure (page index, tree/heading hierarchy, " + + "knowledge graph, wiki pages when present) so a semantic hit carries " + + "its structural neighbours (parent/child headings, sibling pages). " + + "If the dataset has NO compiled structure (incl. no wiki), expansion " + + "is a no-op — no error, just semantic hits. " + + "Returns snippet chunks ranked by relevance. 1-2 queries per call."), + Parameters: arrayParam("", 1, 2), + }, + } + + webSearchToolSpec = ToolSpec{ + Type: "function", + Function: ToolFunction{ + Name: "web_search", + Description: ("Search the open WEB. Use ONLY when the needed fact is world " + + "knowledge / recent event / not covered by the fixed corpus — e.g. " + + "a current event, a person's alive-now status, or a statistic newer " + + "than the corpus. If the fact plausibly lives in the documents, " + + "prefer corpus tools (retrieve/search_chunks) first. 1-2 queries per call."), + Parameters: arrayParam("", 1, 2), + }, + } + + // wikiQueryToolSpec previously mirrored Python tools/exploration.py wiki_query, + // but that function is never registered in Python's _TOOL_MAP (the action + // session dispatch registry), so it has been removed from Go's ToolMap to keep + // the two registries identical. The wiki_query handler still lives in + // tool_exploration.go as an unplugged extension seam. + + navigateTreeToolSpec = ToolSpec{ + Type: "function", + Function: ToolFunction{ + Name: "navigate_tree", + Description: ("LOCATE the RIGHT DOCUMENT among MANY before deep-reading. Use it " + + "BEFORE search_chunks when the dataset is large and you have no " + + "doc_id yet — it routes by TOPIC/CLUSTERING similarity over the " + + "compiled document-navigation tree (not exact surface words), so it " + + "finds the document even when your query words differ from its text. " + + "Returns candidate doc_ids + a first-chunk summary of each. " + + "This is the FIRST hop of a navigation chain: " + + "navigate_tree(query) -> doc_id -> navigate_structure(doc_id, ...) " + + "-> list_chunks(doc_id, chunk_ids). " + + "Use when: the question names a topic/entity/alias but you do not " + + "know which document discusses it; search_chunks returned scattered " + + "hits across many docs and you must pick the source. " + + "Do NOT use if you already hold a doc_id (go straight to " + + "navigate_structure) or if the answer is likely a single exact " + + "passage (prefer retrieve/search_chunks). " + + "If the dataset has no compiled document navigation tree, it returns " + + "empty — fall back to search_chunks."), + Parameters: map[string]any{ + "type": "object", + "properties": map[string]any{ + "query": map[string]any{ + "type": "string", + "description": "topic / entity / alias whose document(s) to locate", + }, + }, + "required": []string{"query"}, + }, + }, + } + + navigateStructureToolSpec = ToolSpec{ + Type: "function", + Function: ToolFunction{ + Name: "navigate_structure", + Description: ("PINPOINT A PASSAGE inside ONE document using its compiled structure " + + "(heading/catalog tree, concept mindmap, or entity graph) — the " + + "in-document counterpart of navigate_tree. " + + "Use AFTER you know the doc_id (from navigate_tree / search_chunks / " + + "retrieve) and need to find where the answer lives WITHOUT reading " + + "every chunk. Returns the structure outline annotated with matching " + + "chunk_ids (reading-order aware). Then call list_chunks(doc_id, " + + "chunk_ids) to read exactly those. " + + "kind: 'catalog' (default) for page-index/heading/timeline trees, " + + "'mindmap' for concept maps, 'graph' for entity-relation graphs. " + + "If the document has NO compiled structure, an empty is " + + "returned — fall back to list_chunks to read the full document."), + Parameters: map[string]any{ + "type": "object", + "properties": map[string]any{ + "doc_id": paramString("document id seen from a prior tool result"), + "query": paramString("what to locate within the document"), + "kind": paramEnum("compiled structure kind, default catalog", "catalog", "mindmap", "graph"), + }, + "required": []string{"doc_id"}, + }, + }, + } + + calculateToolSpec = ToolSpec{ + Type: "function", + Function: ToolFunction{ + Name: "calculate", + Description: ("COMPUTE a numeric answer by generating and safely running code. " + + "MANDATORY whenever the question asks you to DERIVE a number by " + + "combining facts you found (sum/difference/percentage/ratio/sort/" + + "compare/difference in length/age, price, area, growth, etc.) — do " + + "NOT do arithmetic mentally. Language-neutral: the question and " + + "facts may be in ANY language (English, Chinese, ...); pass the " + + "numbers verbatim as written in the evidence regardless of language. " + + "Steps: (1) collect every needed number first (retrieve / " + + "search_chunks / navigate_* / list_chunks); (2) call calculate with " + + "the question + ALL those numbers; (3) report the computed result " + + "verbatim. If a needed number is missing, search for it first — do " + + "not estimate. If the answer IS one of the stated numbers (no " + + "combination needed), answer directly without this tool."), + Parameters: map[string]any{ + "type": "object", + "properties": map[string]any{ + "question": paramString("the user's question, verbatim"), + "facts": map[string]any{ + "type": "array", + "items": map[string]any{"type": "string"}, + "description": "numbers/facts found in the evidence, verbatim", + }, + }, + "required": []string{"question", "facts"}, + }, + }, + } + + graphExploreToolSpec = ToolSpec{ + Type: "function", + Function: ToolFunction{ + Name: "graph_explore", + Description: ("EXPLORE the compiled KNOWLEDGE GRAPH (entities + relations) for a " + + "RELATIONAL/multi-hop answer. Different from navigate_*: instead of " + + "locating a document or passage, it seeds entities for the query, " + + "hops along their RELATIONS, and returns either a direct answer or " + + "the source passages behind the relevant entities/relations. " + + "Use when the answer requires connecting several entities through " + + "their relations (e.g. who-was-related-to-whom, cause-effect chains, " + + "membership/ownership) and you already have a starting entity from a " + + "search result, a navigation outline, or a list_chunks reading. " + + "If the dataset has NO compiled knowledge graph, it returns empty — " + + "fall back to search_chunks / navigate_structure."), + Parameters: map[string]any{ + "type": "object", + "properties": map[string]any{ + "query": paramString("the relational question / starting entity"), + "doc_scope": map[string]any{ + "type": "array", + "items": map[string]any{"type": "string"}, + "description": "optional doc_ids to restrict the graph to (from prior navigation/list_chunks)", + }, + }, + "required": []string{"query"}, + }, + }, + } +) + +func paramString(desc string) map[string]any { + return map[string]any{"type": "string", "description": desc} +} + +func paramEnum(desc string, values ...string) map[string]any { + return map[string]any{"type": "string", "enum": values, "description": desc} +} + +// ToolMap is the multi-tool registry, mirroring Python _TOOL_MAP. +// executeTool dispatches by name; add a tool by registering its schema here. +var ToolMap = map[string]ToolSpec{ + "retrieve": retrieveToolSpec, + "search_chunks": searchChunksToolSpec, + "list_chunks": listChunksToolSpec, + "navigate_tree": navigateTreeToolSpec, + "navigate_structure": navigateStructureToolSpec, + "calculate": calculateToolSpec, + "graph_explore": graphExploreToolSpec, + "web_search": webSearchToolSpec, +} + +// ToolMapNames are the registered tool names, sorted for deterministic output. +func ToolMapNames() []string { + names := make([]string, 0, len(ToolMap)) + for n := range ToolMap { + names = append(names, n) + } + sort.Strings(names) + return names +} + +// --------------------------------------------------------------------------- +// The per-session tool object +// --------------------------------------------------------------------------- + +// ToolExecutor runs one tool call by name and reports what happened. +// +// Every executor returns a ToolOutcome so the tool node can act on the KIND of +// result (empty / miss / poor / redundant / error) instead of measuring payload +// size. +type ToolExecutor interface { + Execute(ctx context.Context, name string, args map[string]any) (ToolOutcome, error) +} + +// Toolset is the per-session tool object, mirroring the Python RAGTools +// surface the session reads: thinking mode, web provider availability, the +// runtime-disabled tool set, and the executor. +// +// Python mutates `tools._disabled_tools` on the request object; Go keeps that +// state here so a session cannot leak it into another request. +type Toolset struct { + // ThinkingMode selects the ModeSpec (see config.go). + ThinkingMode string + // HasWebSearch reports whether a web provider is configured. When false, + // web_search is hidden from the surface rather than merely discouraged. + HasWebSearch bool + // DisabledTools holds tools proven unavailable this session (no compiled + // structure of their kind). + DisabledTools map[string]bool + // Exec runs the tools. + Exec ToolExecutor +} + +// GetThinkingMode implements ThinkingModeCarrier so ResolveMode works on *Toolset. +func (t *Toolset) GetThinkingMode() string { + if t == nil { + return "" + } + return t.ThinkingMode +} + +// ActiveToolSpecs mirrors Python _active_tool_specs: the tool schemas exposed +// to the model for THIS mode. +// +// Visibility rules: +// - the per-mode tool set comes from config.THINKING_MODES (only ultra sees +// the relational graph_explore); +// - web_search is hidden when no web provider is configured — the model +// otherwise retries it several times per session burning turns; +// - compile-only tools stay visible even on datasets without compiled +// structure: their executors return an explicit empty-with-hint so the +// model falls back to plain search; +// - RUNTIME: a compile-only tool is removed after it proves the dataset has +// no such compiled structure (DisableTool). +func (t *Toolset) ActiveToolSpecs() []ToolSpec { + spec := ResolveMode(t) + var out []ToolSpec + for _, name := range spec.ToolNames() { + if name == "web_search" && !t.HasWebSearch { + continue + } + if t.DisabledTools[name] { + continue + } + if s, ok := ToolMap[name]; ok { + out = append(out, s) + } + } + return out +} + +// DisableTool mirrors Python _disable_tool: mark a compile-only tool +// unavailable for the REST of this session, so ActiveToolSpecs stops +// advertising it and ExecuteTool short-circuits it. +func (t *Toolset) DisableTool(name string) { + if _, ok := ToolMap[name]; !ok { + return + } + if t.DisabledTools == nil { + t.DisabledTools = map[string]bool{} + } + t.DisabledTools[name] = true +} + +// IsDisabled reports whether name has been disabled this session. +func (t *Toolset) IsDisabled(name string) bool { + return t.DisabledTools[name] +} + +// ReasonStatus mirrors Python _reason_status: single source of truth for the +// cause→status mapping, so a tool cannot disagree with itself about what its +// own reason means. +// The unified tool-result contract shared by the session and the tool +// implementations (mirrors Python action_session.py's ToolOutcome and the +// OK/EMPTY/MISS/POOR/REDUNDANT/ERROR statuses — which Python also defines in +// action_session.py, so they live here in its Go mirror). + +// Tool-result statuses. Mirrors Python OK/EMPTY/MISS/POOR/REDUNDANT/ERROR. +// These are the signal the session's tool node acts on. +const ( + StatusOK = "ok" // normal hit + StatusEmpty = "empty" // dataset-level: no such compiled structure exists here + StatusMiss = "miss" // query-level: nothing matched THIS query; tool still valid + StatusPoor = "poor" // produced output, but too weak to be useful + StatusRedundant = "redundant" // ran fine, but added no NEW evidence + StatusError = "error" // infra / provider failure +) + +// Machine-readable ToolOutcome reasons. Only ReasonNoStructure is +// DATASET-level and may disable a tool; ReasonNoDoc is QUERY-level and must not. +const ( + ReasonNone = "" + ReasonNoStructure = "no_structure" + ReasonNoDoc = "no_doc" + ReasonInfra = "infra" + ReasonBadArgs = "bad_args" +) + +// ToolOutcome is the result of ONE tool call. Every executor returns one so the +// tool node can inspect WHAT happened instead of counting characters in a JSON +// string — timeout / budget / routing / disable policies hook into these fields. +type ToolOutcome struct { + Payload []any // what the model sees (passage dicts) + EvidenceIDs []string // doc/chunk ids worth tracking + Status string // one of the Status* constants + Reason string // one of the Reason* constants + Metrics map[string]any // numeric signals: hits, new_evidence, top_score, ... +} + +// NewToolOutcome builds an OK outcome with an empty metric map. +func NewToolOutcome(payload []any, evidenceIDs []string) ToolOutcome { + return ToolOutcome{ + Payload: payload, + EvidenceIDs: evidenceIDs, + Status: StatusOK, + Reason: ReasonNone, + Metrics: map[string]any{}, + } +} + +// ReasonStatus maps a ToolOutcome reason to the Status it implies, mirroring +// Python action_session._reason_status. +func ReasonStatus(reason string) string { + switch reason { + case ReasonNoStructure: + return StatusEmpty + case ReasonBadArgs, ReasonInfra: + return StatusError + } + // ReasonNoDoc: this query reached nothing; the tool itself is fine. + return StatusMiss +} + +// ===================== session.go (model seam, _SessionState, nodes, routing) ===================== +// The graph-edge action session: one bounded ReAct loop pursuing ONE direction. +// Mirrors Python harness/action_session.py. +// +// PYTHON USES LANGGRAPH; THIS FILE USES AN EXPLICIT LOOP: the graph is small and fixed +// (see sessionLoop), so three functions and a switch buy more than compiling one. The +// node bodies, routing predicates and their ordering are ported verbatim; only the +// driver differs. +// +// ONE structural difference, isolated to one seam: Python calls the provider's native +// tool-calling API (`tools=[...]`, `tool_choice="auto"`) and parses +// `message.tool_calls`; the Go chat seam (internal/agent/chat) has no tools field, so +// invocation goes through the SessionModel interface, whose default implementation asks +// the model to emit the call as a JSON block and parses it back. Downstream session +// logic is identical either way. + +const ( + // initTimeoutS bounds the slot-table decomposition call. + initTimeoutS = 45.0 + // actionTimeoutS is the default per-session wall-clock budget. + actionTimeoutS = 75.0 + // snippetsPerQuery caps snippets returned per query. + snippetsPerQuery = 4 + // maxToolResponseChars bounds ONE tool payload. + maxToolResponseChars = 12000 + // emptyStrikes is how many dataset-level empties (reason=no_structure) a + // compiled-structure tool must accumulate before being disabled for the rest + // of the session. Kept above 1: a single empty can be SCOPED — graph_explore + // over a doc_scope that has no knowledge graph says nothing about the other + // documents, and disabling on the first empty is exactly the over-eager + // behaviour this replaced. + emptyStrikes = 2 + // nearDupJaccard is the token-overlap threshold at which a retrieval query + // counts as a paraphrase of an already-run query. The model re-issues the + // SAME intent with many paraphrases (observed: 20+ variants in ONE session), + // each hitting the index even though the evidence is unchanged. + nearDupJaccard = 0.8 + // skippedDupLimit: once this many near-duplicate retrievals were skipped, + // further turns are unlikely to surface new evidence, so the session + // converges to finalize instead of burning the remaining budget on + // paraphrases (Q30/Q759 timeout root cause). + skippedDupLimit = 2 + // finalizeTimeout bounds the salvage call in the finalize node. + finalizeTimeoutS = 150.0 + // minFinalizeTimeout is the floor for the salvage call. + minFinalizeTimeoutS = 15.0 +) + +// retrievalTools: near-duplicate suppression applies to these (Python +// _RETRIEVAL_TOOLS). grep_chunks / grep_search are legacy names kept so a +// model emitting them is still deduped rather than executed. +var retrievalTools = map[string]bool{ + "search_chunks": true, + "grep_chunks": true, + "grep_search": true, +} + +var _LOG = common.StdLogger() + +var reSearchToken = regexp.MustCompile(`[a-z0-9]{2,}`) + +// searchTokens mirrors Python _search_tokens: lowercased alphanumeric tokens +// of a query, for near-duplicate detection. +func searchTokens(q string) map[string]struct{} { + out := map[string]struct{}{} + for _, t := range reSearchToken.FindAllString(strings.ToLower(q), -1) { + out[t] = struct{}{} + } + return out +} + +// IsNearDup mirrors Python _is_near_dup: true when q shares >= +// nearDupJaccard of its tokens with any query in seen. +func IsNearDup(q string, seen []string) bool { + if strings.TrimSpace(q) == "" || len(seen) == 0 { + return false + } + toks := searchTokens(q) + if len(toks) < 2 { + return false + } + for _, s := range seen { + other := searchTokens(s) + inter := 0 + for t := range toks { + if _, ok := other[t]; ok { + inter++ + } + } + union := len(toks) + for t := range other { + if _, ok := toks[t]; !ok { + union++ + } + } + if union > 0 && float64(inter)/float64(union) >= nearDupJaccard { + return true + } + } + return false +} + +// --------------------------------------------------------------------------- +// The model seam +// --------------------------------------------------------------------------- + +// CompleteWithTemperature implements TemperatureModel. +func (m *InvokerSessionModel) CompleteWithTemperature(ctx context.Context, messages []schema.Message, tools []ToolSpec, temp float64) (*ModelReply, error) { + if m == nil || m.Invoker == nil { + return nil, fmt.Errorf("harness: no chat invoker configured") + } + // Python binds the tools natively (action_session.py:_acompletion native tools / + // :1083 tool_choice="auto") and reads the result out of msg.tool_calls + // (:1101-1114). There is no prompt-based fallback: a provider that cannot + // express native tools simply has no tool capability. + req := chat.Request{Messages: messages, Temperature: &temp} + if chatTools := toChatTools(tools); chatTools != nil { + req.Tools = chatTools + req.ToolChoice = chat.ToolChoiceAuto + } + resp, err := m.Invoker.Invoke(ctx, m.DB, req) + if err != nil { + return nil, err + } + reply := &ModelReply{Content: resp.Content} + if resp != nil { + reply.Usage = resp.Usage + reply.Tokens = totalOf(resp) + reply.ToolCalls = nativeToHarnessCalls(resp.ToolCalls) + } + return reply, nil +} + +// InvokerSessionModel adapts chat.Invoker to SessionModel using the provider's +// NATIVE tool calling, mirroring Python (action_session.py:_acompletion native tools, +// :1083 tool_choice="auto", :1101-1114 reading msg.tool_calls). +// +// There is no prompt-based fallback: Python has none, so a provider that cannot +// express native tools simply has no tool capability. A reply with no tool_calls +// is a no-call turn, which the session nudges — the same path Python takes. +type InvokerSessionModel struct { + Invoker chat.Invoker + DB *gorm.DB + // MaxLength is the resolved chat model's context window in tokens + // (Python LLMBundle.max_length / tools.chat_mdl.max_length). Used by + // ContextLength to size message_fit_in. <= 0 means "unknown", in which case + // ContextLength reports chat.EffectiveContextLength's 8192 fallback. + MaxLength int +} + +// ContextLength implements ContextLengthModel. It returns the model's context +// window in tokens when known, otherwise the 8192 default that mirrors +// Python's LLM.max_length falling back when the config omits max_tokens. +func (m *InvokerSessionModel) ContextLength() int { + if m == nil { + return chat.EffectiveContextLength(0) + } + return chat.EffectiveContextLength(m.MaxLength) +} + +// Complete implements SessionModel. +func (m *InvokerSessionModel) Complete(ctx context.Context, messages []schema.Message, tools []ToolSpec) (*ModelReply, error) { + if m == nil || m.Invoker == nil { + return nil, fmt.Errorf("harness: no chat invoker configured") + } + temp := 0.3 + req := chat.Request{Messages: messages, Temperature: &temp} + if chatTools := toChatTools(tools); chatTools != nil { + req.Tools = chatTools + req.ToolChoice = chat.ToolChoiceAuto + } + resp, err := m.Invoker.Invoke(ctx, m.DB, req) + if err != nil { + return nil, err + } + reply := &ModelReply{Content: resp.Content} + if resp != nil { + reply.Usage = resp.Usage + reply.Tokens = totalOf(resp) + reply.ToolCalls = nativeToHarnessCalls(resp.ToolCalls) + } + return reply, nil +} + +// StreamComplete implements StreamingSessionModel by delegating to the +// underlying invoker when it can stream. A non-streaming invoker yields an +// error, which the caller treats as "fall back to the one-shot call" — the +// prompt is identical either way, so the answer is not affected. +func (m *InvokerSessionModel) StreamComplete(ctx context.Context, messages []schema.Message, tools []ToolSpec, onDelta func(delta string, isThink bool) error) (*ModelReply, error) { + if m == nil || m.Invoker == nil { + return nil, fmt.Errorf("harness: no chat invoker configured") + } + streamer, ok := m.Invoker.(chat.StreamingInvoker) + if !ok { + return nil, fmt.Errorf("harness: chat invoker %T does not support streaming", m.Invoker) + } + temp := 0.3 + req := chat.Request{Messages: messages, Temperature: &temp} + if chatTools := toChatTools(tools); chatTools != nil { + req.Tools = chatTools + req.ToolChoice = chat.ToolChoiceAuto + } + resp, err := streamer.Stream(ctx, m.DB, req, onDelta) + if err != nil { + return nil, err + } + if resp == nil { + return nil, fmt.Errorf("harness: streaming invoker returned no response") + } + reply := &ModelReply{ + Content: resp.Content, + Usage: resp.Usage, + Tokens: totalOf(resp), + } + reply.ToolCalls = nativeToHarnessCalls(resp.ToolCalls) + return reply, nil +} + +// totalOf returns the total token count for a chat.Response, preferring the +// Usage split and falling back to the legacy single counter. +func totalOf(resp *chat.Response) int { + if resp == nil { + return 0 + } + if resp.Usage != nil { + return resp.Usage.TotalTokens + } + return resp.Tokens +} + +// toChatTools converts the harness ToolSpec surface into the chat seam's native +// Tool declarations, mirroring Python's native tool list (action_session.py:_acompletion). +// The chat seam forwards them to the provider as native tools; Python has no +// prompt-based fallback, and neither does this port. +func toChatTools(tools []ToolSpec) []chat.Tool { + if len(tools) == 0 { + return nil + } + out := make([]chat.Tool, 0, len(tools)) + for _, t := range tools { + if t.Function.Name == "" { + continue + } + out = append(out, chat.Tool{ + Type: "function", + Function: chat.ToolFunction{ + Name: t.Function.Name, + Description: t.Function.Description, + Parameters: t.Function.Parameters, + }, + }) + } + if len(out) == 0 { + return nil + } + return out +} + +// knownTool reports whether name is a real tool, judged against the STATIC full +// set (ToolMap) — mirroring Python `if name not in _TOOL_MAP` +// (action_session.py:_parse_tool_calls). +// +// It deliberately does NOT consult the active surface. Disabled or web-hidden +// tools are real tools that this session has stopped advertising; a model that +// still calls one must get the "unavailable, use this instead" note from +// ExecuteTool, not an "unknown tool" correction. Judging against the active +// surface would turn every disabled call into Unknown and override that +// deliberately gentler degradation path. +func knownTool(name string) bool { + _, ok := ToolMap[name] + return ok +} + +// nativeToHarnessCalls maps chat-seam native tool calls into the harness ToolCall +// shape, preserving the Unknown flag for names outside the static tool map. +// +// Python synthesizes `call_{i}` when a provider omits the id +// (action_session.py:_parse_terminal, :1136) — without it the assistant message and its +// tool responses cannot be paired and the next request is rejected with +// "tool call result does not follow tool call". +func nativeToHarnessCalls(calls []chat.ToolCall) []ToolCall { + if len(calls) == 0 { + return nil + } + out := make([]ToolCall, 0, len(calls)) + for i, c := range calls { + id := c.ID + if id == "" { + id = fmt.Sprintf("call_%d", i) + } + out = append(out, ToolCall{ + ID: id, + Name: c.Name, + Args: c.Arguments, + Unknown: !knownTool(c.Name), + }) + } + return out +} + +// ensureToolCallIDs backfills synthesized ids for calls produced by a +// SessionModel that did not assign one, so the assistant message and every tool +// response reference the same id (see nativeToHarnessCalls). +func ensureToolCallIDs(calls []ToolCall) { + for i := range calls { + if calls[i].ID == "" { + calls[i].ID = fmt.Sprintf("call_%d", i) + } + } +} + +// assistantToolCalls renders harness tool calls as the schema assistant message's +// tool_calls, mirroring Python action_session.py:_run_action_node which passes the +// model's native tool_calls through verbatim so they pair with the tool +// responses. Passing nil here leaves a dangling tool_call and the next request +// is rejected. +func assistantToolCalls(calls []ToolCall) []schema.ToolCall { + if len(calls) == 0 { + return nil + } + out := make([]schema.ToolCall, 0, len(calls)) + for _, c := range calls { + raw, err := json.Marshal(c.Args) + if err != nil || c.Args == nil { + raw = []byte("{}") + } + out = append(out, schema.ToolCall{ + ID: c.ID, + Type: "function", + Function: schema.FunctionCall{Name: c.Name, Arguments: string(raw)}, + }) + } + return out +} + +// --------------------------------------------------------------------------- +// Session state +// --------------------------------------------------------------------------- + +// SessionState mirrors Python _SessionState (the LangGraph TypedDict). +type SessionState struct { + // Messages is the running conversation (system + user + assistant + tool). + Messages []schema.Message + // ParentState is the slot table being patched by this session. + ParentState State + Tools *Toolset + Model SessionModel + + // PendingCalls are tool calls awaiting execution this turn. + PendingCalls []ToolCall + Done bool + + NewStates []State + FoundAnswer *string + + RetrievedEvidenceIDs []string + Attempts int + DeadlineLeft float64 + + // CtxBudget is the cumulative tool-payload char ceiling for the session. + CtxBudget int + // ToolChars is the running total of tool-payload chars emitted so far + // (O(1) accounting; Python tracks the same counter as _tool_chars). + ToolChars int + // ToolCache avoids re-executing an identical (name, args) call. + ToolCache map[string]ToolOutcome + // SearchQueries accumulates retrieval queries for near-dup detection. + SearchQueries []string + // SkippedDup counts near-duplicate retrievals suppressed so far. + SkippedDup int + // ToolStrikes counts dataset-level empties per tool. + ToolStrikes map[string]int + // ToolOutcomes is the audit trail of (name, status, reason, metrics). + ToolOutcomes []map[string]any + + Direction string + RoutedDocs []string + // NavHint is the joined routed-doc summaries carried by the navigation + // ladder; it soft-boosts later retrieval ("nav is a hint, not a constraint") + // without restricting the corpus. + NavHint string + // NavRuleID is where the navigation ladder currently rests ("" = the ladder + // finished or was never armed). + NavRuleID string + + TerminalType *string + TerminalPayload map[string]any +} + +// appendMessages is the single place a session grows its message list. +// +// Mirrors Python's `messages: Annotated[list, add_messages]` reducer +// (action_session.py:_SessionState), which degenerates to a plain append: Python never sets a +// message id (LangChain assigns a fresh uuid per message, so ids never collide) and +// nothing in action_session.py reads one — its `.id` uses are tool-call and +// slot/nav-rule ids. +// +// Deliberately NOT a tool_call_id dedupe: fallback ids are per-turn +// (`ensureToolCallIDs` assigns call_0, call_1… to unnamed calls), so two turns can both +// carry call_0 and dropping the earlier response would orphan that turn's assistant +// tool_calls. Assistant turns are new by construction. +// +// A real message id would be needed to mirror add_messages if we ever stream partial +// assistant messages into the state or restore a session from a checkpoint; eino's +// schema.Message has no id field. +func appendMessages(dst []schema.Message, msgs ...schema.Message) []schema.Message { + return append(dst, msgs...) +} + +// --------------------------------------------------------------------------- +// Tool dispatch +// --------------------------------------------------------------------------- + +// ExecuteTool mirrors Python execute_tool: dispatch ONE tool call by name. +// +// Returns a ToolOutcome whose status/reason let the caller act on WHAT happened +// — empty payload, query miss, infra failure, or a run that added no new +// evidence — instead of only counting characters. +func ExecuteTool(ctx context.Context, tools *Toolset, name string, args map[string]any) ToolOutcome { + // Short-circuit a tool already proven unavailable this session (no compiled + // structure of its kind). We still return a note, not an error, so the model + // learns to switch to the corpus tools rather than loop. + if tools != nil && tools.IsDisabled(name) { + _LOG.Printf("[Action Session] tool %q disabled (no compiled structure); returning note", name) + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": name, + "note": fmt.Sprintf("%s is unavailable in this dataset (no compiled structure of its kind). Use search_chunks / retrieve / list_chunks instead.", name), + }}, + Status: StatusEmpty, + Reason: ReasonNoStructure, + } + } + if tools == nil || tools.Exec == nil { + return ToolOutcome{Payload: []any{}, Status: StatusError, Reason: ReasonInfra} + } + out, err := tools.Exec.Execute(ctx, name, args) + if err != nil { + return ToolOutcome{Payload: []any{}, Status: StatusError, Reason: ReasonInfra} + } + return out +} + +// --------------------------------------------------------------------------- +// Nodes +// --------------------------------------------------------------------------- + +// runActionNode mirrors Python _run_action_node: ONE model turn with tools. +// It appends the assistant message and records any tool calls as pending. +func (s *SessionState) runActionNode(ctx context.Context) error { + s.Attempts++ + // Per-turn wall budget (mirrors Python _run_action_node:1207-1210): + // max(15, min(75, deadline_left)). Without this a single turn can eat the + // entire session budget, starving the salvage/finalize steps. + wall := max(15.0, min(75.0, s.DeadlineLeft)) + callCtx, cancel := context.WithTimeout(ctx, time.Duration(wall*float64(time.Second))) + defer cancel() + reply, err := s.Model.Complete(callCtx, s.Messages, s.Tools.ActiveToolSpecs()) + if err != nil { + // Python _run_action_node:1215-1220 — a timed-out or failed turn + // CONVERGES the session empty instead of aborting it: the node returns + // {"_done": True, "new_states": [], "found_answer": None}, _route sees + // _done and ends the graph, and run_action_session hands back the + // messages/evidence gathered so far. Returning the error here aborted the + // whole eino run, which RunActionSession reports as a failed session and + // answers with an empty Result — losing the nav prefix's evidence ids and + // every tool outcome, i.e. Python's graph-level failure branch instead of + // its node-level convergence branch. + if callCtx.Err() == context.DeadlineExceeded { + _LOG.Printf("[Action Session] turn timed out after %.0fs", wall) + } else { + _LOG.Printf("[Action Session] LLM call failed (%T); converging session empty", err) + } + s.Done = true + s.NewStates = nil + s.FoundAnswer = nil + return nil + } + // Python passes the model's tool_calls through verbatim on the assistant + // message (action_session.py:_run_action_node) so the tool responses that follow can + // be paired by id. Passing nil leaves a dangling tool_call and the next + // request is rejected with "tool call result does not follow tool call". + ensureToolCallIDs(reply.ToolCalls) + s.Messages = append(s.Messages, + *schema.AssistantMessage(reply.Content, assistantToolCalls(reply.ToolCalls))) + + if len(reply.ToolCalls) > 0 { + s.PendingCalls = reply.ToolCalls + return nil + } + s.PendingCalls = nil + + // No call: try the terminal protocol ( / ). + newStates, foundAnswer, terminalType, payload := ParseTerminal(reply.Content, s.ParentState) + if foundAnswer != nil || len(newStates) > 0 { + s.NewStates = newStates + s.FoundAnswer = foundAnswer + s.TerminalType = terminalType + s.TerminalPayload = payload + s.Done = true + return nil + } + // Neither a call nor a terminal block: nudge once per turn. + s.Messages = append(s.Messages, *schema.UserMessage("Call the retrieve tool, or output a patch, or emit .")) + return nil +} + +// toolNode mirrors Python _tool_node: execute pending tool calls, append tool +// responses, and apply the per-outcome policies. +func (s *SessionState) toolNode(ctx context.Context) error { + if s.Tools == nil { + return nil + } + evidenceIDs := append([]string(nil), s.RetrievedEvidenceIDs...) + budgetChars := s.CtxBudget + if budgetChars <= 0 { + budgetChars = maxToolResponseChars * 4 + } + used := s.ToolChars + if s.ToolCache == nil { + s.ToolCache = map[string]ToolOutcome{} + } + seenQueries := append([]string(nil), s.SearchQueries...) + skipped := 0 + strikes := map[string]int{} + for k, v := range s.ToolStrikes { + strikes[k] = v + } + // Where the nav ladder currently rests. Bound BEFORE the loop so it survives + // the empty-pending case and is the input for every tool_call that comes in — + // a call only advances its own rung, and a later ladder continuation must + // continue from the SAME resting point. + // + // The continuation is ported (Python :1406-1444) but currently UNREACHABLE: + // it only runs once a rung leaves the chain in ModeLLM, and every rule in + // NavRules is ModeAuto, so the chain always runs to completion in the prefix + // and PendingRule is "" by the time control reaches here. Adding an LLM rung + // makes it live with no further change. + pendingRule := s.NavRuleID + + for _, c := range s.PendingCalls { + // Near-duplicate retrieval suppression: if the model re-issues the same + // intent as an earlier search (paraphrase), do NOT re-run the index — + // return a nudge so it patches / reframes instead of burning turns. + q, _ := c.Args["query"].(string) + q = strings.TrimSpace(q) + if retrievalTools[c.Name] && q != "" && IsNearDup(q, seenQueries) { + skipped++ + _LOG.Printf("[Action Session] skipping near-duplicate retrieval %q (already searched)", trunc(q, 80)) + s.Messages = appendMessages(s.Messages, toolMessage(c.ID, []any{map[string]any{ + "kind": c.Name, + "note": "This query is a near-duplicate of an earlier retrieval and was skipped to avoid redundant searching. Patch the slot with what you have, or issue a genuinely NEW retrieval angle.", + }})) + continue + } + // Unknown tool name — never execute it; answer with a correction so the + // model can recover. Models usually emit the XML protocol tags (state / + // answer) as tool names; they belong in the reply body as plain text. + if c.Unknown { + hint := fmt.Sprintf( + "'%s' is not a tool. State patches and final answers are plain TEXT in your reply body, wrapped in ... or ... XML tags — do not emit them as tool calls. Available tools: %s.", + c.Name, strings.Join(ToolMapNames(), ", ")) + s.Messages = appendMessages(s.Messages, toolMessage(c.ID, []any{map[string]any{"kind": "error", "note": hint}})) + continue + } + + // Same-session cache: avoid re-running an identical (name, args) call. + // The cache only avoids RE-EXECUTING; a response is still returned for + // every declared call, because the assistant message declared it. + cacheKey := callCacheKey(c) + oc, cached := s.ToolCache[cacheKey] + if !cached { + oc = ExecuteTool(ctx, s.Tools, c.Name, c.Args) + s.ToolCache[cacheKey] = oc + } + if q != "" { + seenQueries = append(seenQueries, q) + } + evidenceIDs = append(evidenceIDs, oc.EvidenceIDs...) + chunks := append([]any(nil), oc.Payload...) + + // ── Policy: act on WHAT happened, not just on payload size ────────── + switch { + case oc.Status == StatusOK: + // A real hit clears the tool's strike record: it demonstrably works. + delete(strikes, c.Name) + case oc.Status == StatusEmpty && oc.Reason == ReasonNoStructure: + // Dataset-level dead end. Strike it; disable once the strikes pile up + // so one unlucky scope cannot kill the tool. + n := strikes[c.Name] + 1 + strikes[c.Name] = n + if n >= emptyStrikes { + s.Tools.DisableTool(c.Name) + _LOG.Printf("[Action Session] %s disabled after %d dataset-level empty results", c.Name, n) + } + case oc.Status == StatusRedundant: + // Ran fine, but every hit was already in the shared evidence pool. + // Say so explicitly — otherwise the model sees a normal passage list + // and concludes the search succeeded, then re-searches the same ground. + chunks = append(chunks, map[string]any{ + "kind": c.Name, + "note": "All hits from this call were ALREADY in your evidence. Re-reading them will not add anything — issue a genuinely new angle, or output a patch with what you have.", + }) + } + + s.ToolOutcomes = append(s.ToolOutcomes, map[string]any{ + "name": c.Name, "status": oc.Status, "reason": oc.Reason, "metrics": oc.Metrics, + }) + + payload := marshalPassages(chunks) + // If the session is already heavy, cut this payload proportionally. + if used+len(payload) > budgetChars { + keep := budgetChars - used + if keep < 800 { + keep = 800 + } + payload = payload[:min(len(payload), keep)] + } + used += len(payload) + s.Messages = appendMessages(s.Messages, *schema.ToolMessage(payload, c.ID)) + + // Ladder continuation (Python action_session.py:_tool_node): when the + // model's rung came back weak, keep advancing the ladder IN CODE so one + // weak step cascades through the remaining (cheaper, wider) rungs instead + // of leaving the model to rediscover the fallback one turn at a time. + // + // Unreachable with today's NavRules (every rung is ModeAuto, so the chain + // always runs to completion in the prefix and PendingRule is ""). It is + // ported so an LLM rung resumes from the right place without another + // change here. + if pendingRule != "" { + rule, ok := navRuleByID[pendingRule] + if ok { + nxt := rule.Next[oc.Status] + if nxt != "" { + // Python rebuilds _NavContext(direction, known_docs) from + // the live state — the ladder runs against the CURRENT + // routed scope, not the one captured at prefix time. + ladderNav := &NavContext{ + Direction: s.Direction, + KnownDocs: append([]string(nil), s.RoutedDocs...), + } + ladderBudget := s.DeadlineLeft * navPrefixBudgetRatio + if ladderBudget < navPrefixMinBudgetS { + ladderBudget = navPrefixMinBudgetS + } + // Respect the session's remaining context budget: the ladder + // pairs are appended outside this node's own accounting + // (Python passes max_chars=max(800, budget_chars - used), + // action_session.py:_tool_node). + ex := RunNavChain(ctx, s.Tools, ladderNav, nxt, ladderBudget, "ladder", + max(800, budgetChars-used)) + // The ladder keeps advancing: a later tool_call in the SAME + // batch (or the next turn) resumes from where this call left + // it, not from the original resting point. "" means the + // ladder finished — also correct to record. + pendingRule = ex.PendingRule + for _, m := range ex.Messages { + if m.Role == schema.Tool { + used += len(m.Content) + } + s.Messages = appendMessages(s.Messages, m) + } + evidenceIDs = append(evidenceIDs, ex.EvidenceIDs...) + s.ToolOutcomes = append(s.ToolOutcomes, ex.Outcomes...) + if oc.Status != StatusOK { + _LOG.Printf("[Action Session] ladder %q -> %q (reason=%s)", + rule.ID, nxt, oc.Reason) + } + } + } + } + } + + // Where the ladder now rests ("" = finished). + s.NavRuleID = pendingRule + + s.PendingCalls = nil + s.RetrievedEvidenceIDs = evidenceIDs + s.ToolChars = used + s.SearchQueries = seenQueries + s.SkippedDup += skipped + s.ToolStrikes = strikes + return nil +} + +// finalizeNode mirrors Python _finalize_node: tool budget spent — ONE last call +// WITHOUT tools, demanding the terminal JSON to salvage whatever was learned. +func (s *SessionState) finalizeNode(ctx context.Context) error { + budgetPrompt := ("TOOL BUDGET EXHAUSTED. Based ONLY on the passages retrieved above, output now — no prose outside the block:\n" + + "{\"new_states\": [{\"state\": [{\"id\": , \"candidate\": \"\", " + + "\"candidate_strength\": <0..1>, \"discovered_clues\": [\"...\"]}]}]}\n" + + "If NOTHING was learned use: {\"new_states\": []}") + + // Defensive: strip any assistant.tool_calls that never got a tool response, + // else the provider rejects the history. + msgs := append([]schema.Message(nil), s.Messages...) + msgs = stripUnpairedToolCalls(msgs) + msgs = append(msgs, *schema.UserMessage(budgetPrompt)) + + tmo := s.DeadlineLeft + if tmo <= 0 { + tmo = finalizeTimeoutS + } + tmo = min(max(tmo, minFinalizeTimeoutS), finalizeTimeoutS) + + callCtx, cancel := context.WithTimeout(ctx, time.Duration(tmo*float64(time.Second))) + defer cancel() + + reply, err := s.Model.Complete(callCtx, msgs, nil) + if err != nil { + // Python _finalize_node:1494-1495 — a failed salvage call is logged and + // the node CONTINUES to the deterministic loose-clue harvest below. + // Returning early here dropped the last-narration breadcrumb exactly when + // the salvage model was unavailable, which is the case the harvest exists + // for. + _LOG.Printf("[Action Session] salvage call failed: %v", err) + } else { + newStates, foundAnswer, terminalType, payload := ParseTerminal(reply.Content, s.ParentState) + s.NewStates = newStates + s.FoundAnswer = foundAnswer + s.TerminalType = terminalType + s.TerminalPayload = payload + if foundAnswer != nil { + _LOG.Printf("[Action Session] answer salvaged from exhausted session") + } else if len(newStates) > 0 { + _LOG.Printf("[Action Session] %d branch(es) salvaged from exhausted session", len(newStates)) + } + } + + // Loose-clue harvest (deterministic, zero-LLM; mirrors Python + // action_session._finalize_node:1497-1518): when the salvage produced no + // branches AND no answer, the last AI narration often still carries a fact + // worth keeping as a breadcrumb in the first unresolved slot. + if len(s.NewStates) == 0 && s.FoundAnswer == nil { + if txt := lastNarration(s.Messages); len(txt) >= 24 { + unresolved := s.ParentState.Unresolved() + var targetID int + if len(unresolved) > 0 { + targetID = unresolved[0].ID + } else if len(s.ParentState.State) > 0 { + targetID = s.ParentState.State[0].ID + } else { + targetID = -1 + } + if targetID >= 0 { + // discovered_clues must be []any: ApplyPatch type-switches on the + // JSON-decoded shape (like Python's list), so a []string is + // silently ignored and the whole patch no-ops. + if patched := ApplyPatch(s.ParentState, []map[string]any{ + {"id": targetID, "discovered_clues": []any{"narrative: " + txt[:min(len(txt), 220)]}}, + }); patched != nil { + s.NewStates = []State{*patched} + } + } + } + } + + s.Done = true + return nil +} + +// lastNarration returns the content of the last assistant message that carries +// non-empty text, scanning newest-first (mirrors Python's reversed(message) ai +// lookup in _finalize_node). +func lastNarration(msgs []schema.Message) string { + for i := len(msgs) - 1; i >= 0; i-- { + m := msgs[i] + if m.Role != schema.Assistant { + continue + } + // Skip assistant messages that only hold tool_calls (no free text). + if strings.TrimSpace(m.Content) == "" { + continue + } + return strings.TrimSpace(m.Content) + } + return "" +} + +// --------------------------------------------------------------------------- +// Routing +// --------------------------------------------------------------------------- + +type routeTarget int + +const ( + routeEnd routeTarget = iota + routeTool + routeFinalize + routeRunAction +) + +// actionMaxTurns mirrors Python _action_max_turns: the mode's turn budget. +func (s *SessionState) actionMaxTurns() int { + spec := ResolveMode(s.Tools) + if spec.ActionMaxTurns <= 0 { + return 4 + } + return spec.ActionMaxTurns +} + +// route mirrors Python _route. +func (s *SessionState) route() routeTarget { + if s.Done { + return routeEnd + } + // Run pending tool_calls FIRST, even at the turn budget: leaving an + // assistant.tool_calls message without its tool response makes the provider + // reject the next call. The tool node clears PendingCalls, then the route + // re-checks the budget. + if len(s.PendingCalls) > 0 { + return routeTool + } + if s.Attempts >= s.actionMaxTurns() { + return routeFinalize + } + // No-progress convergence: the model keeps re-issuing near-duplicate + // retrievals, so further turns are unlikely to surface new evidence. + if s.SkippedDup >= skippedDupLimit { + _LOG.Printf("[Action Session] %d near-duplicate retrieval(s) skipped; converging session early", s.SkippedDup) + return routeFinalize + } + return routeRunAction +} + +// routeAfterTool mirrors Python _route_after_tool: the turn budget is checked +// AFTER the tool responses are appended. A pending tool_call must always +// receive its matching tool response, but once the budget is spent we must NOT +// go back to run_action — that was the Q86 infinite-loop: the model kept +// emitting tool_calls, PendingCalls stayed non-empty, so the attempts check in +// route was never reached and the session burned the whole timeout. +func (s *SessionState) routeAfterTool() routeTarget { + if s.Attempts >= s.actionMaxTurns() { + return routeFinalize + } + return routeRunAction +} + +// Session-node adapters: unlike method values (s.runActionNode) these take the +// state from the graph payload instead of capturing an instance, which is what +// lets ONE compiled graph serve every session — Python's _SESSION_GRAPH (:1936) +// is compiled the same way, with the session's tools/model arriving in the +// state (SessionState.Tools / .Model) rather than in a closure. +func runActionNodeFn(ctx context.Context, st *SessionState) (*SessionState, error) { + return st, st.runActionNode(ctx) +} + +func toolNodeFn(ctx context.Context, st *SessionState) (*SessionState, error) { + return st, st.toolNode(ctx) +} + +func finalizeNodeFn(ctx context.Context, st *SessionState) (*SessionState, error) { + return st, st.finalizeNode(ctx) +} + +var ( + sessionGraphOnce sync.Once + sessionGraphRun compose.Runnable[*SessionState, *SessionState] + sessionGraphErr error +) + +// sessionGraph declares the action-session graph and compiles it ONCE per process, +// mirroring Python's module-level _SESSION_GRAPH (:1936): every session invokes the +// same runnable with its own state, so the compile (and any structural error) happens +// once instead of once per session. +// +// RunSlotResearchPass runs sessions in parallel, so the runnable is invoked +// concurrently by design. That is safe under three preconditions — break any and the +// sharing must be revisited: +// +// 1. Nodes touch only their own *SessionState; no package-level mutable state inside +// a node. +// 2. No checkpoint store is configured (compose.WithCheckPointStore) — the +// checkPointer lives on the shared runner. Guarded by +// TestSessionGraphHasNoCheckpointStore. +// 3. Eino v0.9.14's runner keeps no per-run state: it holds only the static topology +// and every Invoke builds its own channels and task manager +// (compose/graph_run.go:129-130, :933, :948). Re-check on upgrade. +// +// See TestSessionGraphIsSharedAcrossConcurrentSessions. +func sessionGraph() (compose.Runnable[*SessionState, *SessionState], error) { + sessionGraphOnce.Do(func() { + g := compose.NewGraph[*SessionState, *SessionState]() + + var buildErr error + addNode := func(name string, fn func(context.Context, *SessionState) (*SessionState, error)) { + if buildErr != nil { + return + } + buildErr = g.AddLambdaNode(name, compose.InvokableLambda(fn)) + } + addEdge := func(from, to string) { + if buildErr != nil { + return + } + buildErr = g.AddEdge(from, to) + } + addBranch := func(from string, ends map[string]bool, cond func(*SessionState) routeTarget) { + if buildErr != nil { + return + } + buildErr = g.AddBranch(from, compose.NewGraphBranch(func(_ context.Context, st *SessionState) (string, error) { + return routeNodeName(cond(st)), nil + }, ends)) + } + + addNode("run_action", runActionNodeFn) + addNode("tool", toolNodeFn) + addNode("finalize", finalizeNodeFn) + + addEdge(compose.START, "run_action") + addEdge("finalize", compose.END) + + addBranch("run_action", map[string]bool{ + "tool": true, "finalize": true, "run_action": true, compose.END: true, + }, (*SessionState).route) + addBranch("tool", map[string]bool{"run_action": true, "finalize": true}, (*SessionState).routeAfterTool) + + if buildErr != nil { + sessionGraphErr = buildErr + return + } + sessionGraphRun, sessionGraphErr = g.Compile(context.Background(), + compose.WithGraphName("action_session"), + // The session is bounded by the turn budget (route / routeAfterTool) + // and the caller's deadline; this is only a backstop so a mis-wired + // cycle cannot spin forever. + compose.WithMaxRunSteps(maxSessionRunSteps), + ) + }) + return sessionGraphRun, sessionGraphErr +} + +// maxSessionRunSteps bounds one session's Eino steps. Python has no equivalent +// knob (LangGraph's recursion_limit is passed per invocation), so this is a +// Go-only safety net sized well above what the turn budget can reach. +const maxSessionRunSteps = 256 + +// sessionLoop invokes the compiled action-session graph, mirroring Python's +// compiled LangGraph edge for edge: +// +// START → run_action +// run_action → route → {END | tool | finalize | run_action} +// tool → route_after_tool → {run_action | finalize} +// finalize → END +func (s *SessionState) sessionLoop(ctx context.Context) error { + runnable, err := sessionGraph() + if err != nil { + return err + } + _, err = runnable.Invoke(ctx, s) + return err +} + +// routeNodeName maps the routing predicates onto the Eino graph's node keys. +func routeNodeName(t routeTarget) string { + switch t { + case routeTool: + return "tool" + case routeFinalize: + return "finalize" + case routeRunAction: + return "run_action" + default: + return compose.END + } +} + +// --------------------------------------------------------------------------- +// Terminal parsing +// --------------------------------------------------------------------------- + +// ParseTerminal mirrors Python _parse_terminal: parse the two terminal blocks +// ( patches → new-state branches; → final answer). +// +// Returns (newStates, foundAnswer, terminalType, payload) — exactly one of +// newStates / foundAnswer may be non-empty. +func ParseTerminal(content string, parent State) ([]State, *string, *string, map[string]any) { + if strings.Contains(content, "") { + block := ExtractTag(content, "state") + if block == "" { + block = "{}" + } + data, _ := ExtractJSON(block).(map[string]any) + if data == nil { + data = map[string]any{} + } + rawBranches, _ := data["new_states"].([]any) + // Tolerate a bare list of variable patches (no {"state": [...]} wrapper): + // models emit both shapes. + if len(rawBranches) > 0 { + allBare := true + for _, b := range rawBranches { + if m, ok := b.(map[string]any); ok { + if _, has := m["state"]; has { + allBare = false + break + } + } + } + if allBare { + wrapped := make([]any, 0, len(rawBranches)) + for _, b := range rawBranches { + wrapped = append(wrapped, map[string]any{"state": []any{b}}) + } + rawBranches = wrapped + } + } + var branches []State + for _, rb := range rawBranches { + br, ok := rb.(map[string]any) + if !ok { + continue + } + patches := toPatchList(br["state"]) + if ns := ApplyPatch(parent, patches); ns != nil { + branches = append(branches, *ns) + } + } + tt := "state" + return branches, nil, &tt, data + } + if strings.Contains(content, "") { + block := ExtractTag(content, "answer") + if block == "" { + block = "{}" + } + data, _ := ExtractJSON(block).(map[string]any) + if data == nil { + data = map[string]any{} + } + ans := "" + if raw, ok := data["answer"]; ok && raw != nil { + ans = fmt.Sprint(raw) + } + patches := toPatchList(data["new_state"]) + var branches []State + if ns := ApplyPatch(parent, patches); ns != nil { + branches = append(branches, *ns) + } + tt := "answer" + return branches, &ans, &tt, data + } + return nil, nil, nil, nil +} + +func toPatchList(v any) []map[string]any { + list, _ := v.([]any) + out := make([]map[string]any, 0, len(list)) + for _, item := range list { + if m, ok := item.(map[string]any); ok { + out = append(out, m) + } + } + return out +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +func toolMessage(id string, passages []any) schema.Message { + return *schema.ToolMessage(marshalPassages(passages), id) +} + +func marshalPassages(passages []any) string { + if passages == nil { + passages = []any{} + } + raw, err := json.Marshal(map[string]any{"passages": passages}) + if err != nil { + return `{"passages": []}` + } + return string(raw) +} + +// callCacheKey mirrors Python's `(name, json.dumps(args, sort_keys=True))` key. +func callCacheKey(c ToolCall) string { + raw, err := json.Marshal(c.Args) + if err != nil { + raw = []byte("{}") + } + return c.Name + "|" + string(raw) +} + +// stripUnpairedToolCalls removes assistant tool_calls that never received a +// tool response — a malformed history makes providers reject the next request +// ("tool call result does not follow tool call"). +func stripUnpairedToolCalls(msgs []schema.Message) []schema.Message { + answered := map[string]bool{} + for _, m := range msgs { + if m.Role == schema.Tool && m.ToolCallID != "" { + answered[m.ToolCallID] = true + } + } + out := make([]schema.Message, 0, len(msgs)) + for _, m := range msgs { + if m.Role == schema.Assistant && len(m.ToolCalls) > 0 { + kept := make([]schema.ToolCall, 0, len(m.ToolCalls)) + for _, tc := range m.ToolCalls { + if answered[tc.ID] { + kept = append(kept, tc) + } + } + if len(kept) != len(m.ToolCalls) { + m.ToolCalls = kept + } + } + out = append(out, m) + } + return out +} + +func trunc(s string, n int) string { + if len(s) <= n { + return s + } + return s[:n] +} + +// sortKeys is a small helper for deterministic map-key iteration in logs. +func sortKeys[V any](m map[string]V) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + sort.Strings(out) + return out +} + +// ===================== navchain.go ===================== +// Deterministic navigation prefix: a code-driven tool chain. +// +// Mirrors Python harness/action_session.py:_build_session_graph. +// +// WHY THIS EXISTS: the ReAct loop lets the MODEL decide which tool to call +// next, so ordering rules ("route with navigate_tree first, then drill with +// navigate_structure, fall back to retrieve when the drill is weak") can only +// be *suggested* in a prompt and are routinely ignored. This prefix runs those +// rules IN CODE before the loop starts and injects the resulting exchange as +// completed assistant/tool messages: the model then explores on top of a +// guaranteed-correct opening and cannot skip a step. The loop keeps its freedom +// for everything after the chain. + +// Step modes. +const ( + // ModeAuto means the orchestrator runs this step itself (no model + // round-trip). + ModeAuto = "auto" + // ModeLLM means the step needs a decision only the model can make (e.g. + // WHICH routed document to drill into), so the chain stops here and hands + // control back. + ModeLLM = "llm" +) + +// Navigation-chain constants. +const ( + // navPrefixBudgetRatio is the share of the session deadline the prefix may + // spend; the ReAct loop keeps the rest. + navPrefixBudgetRatio = 0.35 + // navPrefixCallTimeoutS is the per-call ceiling, so one slow navigation + // cannot swallow the whole prefix. + navPrefixCallTimeoutS = 25.0 + // navHintChars caps the nav-hint text fed back into retrieval as keywords. + navHintChars = 600 + // navPrefixMinBudgetS floors the prefix budget (Python: max(5.0, ...)). + navPrefixMinBudgetS = 5.0 + // navMinStepBudgetS floors a single step's budget (Python: max(5.0, + // remaining)). + navMinStepBudgetS = 5.0 +) + +// NavRulesEnabled mirrors Python _NAV_RULES_ENABLED. +const NavRulesEnabled = true + +// NavContext is the mutable state threaded through the navigation chain. +// +// KnownDocs is the routed scope (doc_ids). RoutedDocs carries each routed doc's +// OVERALL SUMMARY — the hint that feeds retrieval as a soft boost instead of a +// hard filter. NavHint is the joined summaries used as retrieval keywords so +// routed docs rank up WITHOUT excluding the rest of the corpus. +type NavContext struct { + Direction string + KnownDocs []string + RoutedDocs [][2]string // (doc_id, summary) + NavHint string +} + +// NavRule is one step of the navigation chain. +type NavRule struct { + ID string + Tool string + // Mode is ModeAuto or ModeLLM. + Mode string + // Run replaces the single-tool path for a step that composes several tools + // (drill: retrieve + navigate_structure + merge). + Run func(ctx context.Context, ts *Toolset, nav *NavContext, available map[string]bool, budgetS float64) ToolOutcome + // Args builds the tool arguments from the running context (ModeAuto only; + // also used for display when Run composes internally). + Args func(nav *NavContext) map[string]any + // When is an optional guard; the step is skipped when it returns false. + When func(nav *NavContext) bool + // Next maps status -> next rule id. "" (or a missing key) ends the chain. + // Routing on STATUS is what makes "quality poor -> fall back" a code + // decision rather than a prompt suggestion. + Next map[string]string +} + +// NavRules is the per-slot strategy ladder: "nav is a hint, not a constraint" — no +// rung filters the corpus down to the routed docs. The tree ROUTES (locate), then +// drill retrieves over the WHOLE corpus while softly boosting the routed-doc chunks, +// so an answer living outside them survives (ranked lower) instead of being dropped. +// +// locate navigate_tree route to top-n documents, exposing their summaries +// drill retrieve+merge whole-corpus retrieve (nav summaries as BM25 soft +// hint) + navigate_structure paths merged on chunk_id +// + routed-doc chunks re-ranked to the top +// global retrieve safety net only if drill itself came back empty +// +// There is deliberately NO LLM verdict on the drill evidence: retrieval is not +// scope-locked, so there is no "did the scoped search miss?" signal to grade. +var NavRules = []NavRule{ + { + ID: "locate", + Tool: "navigate_tree", + Mode: ModeAuto, + Args: func(nav *NavContext) map[string]any { return map[string]any{"query": nav.Direction} }, + // Tree missed => no routed hints to merge against; the only useful step + // is an unscoped search. + Next: map[string]string{ + StatusOK: "drill", + StatusMiss: "global", + StatusEmpty: "global", + StatusPoor: "global", + StatusError: "global", + StatusRedundant: "global", + }, + }, + { + ID: "drill", + Tool: "navigate_structure", + Mode: ModeAuto, + Run: runDrillMerge, + Args: func(nav *NavContext) map[string]any { return map[string]any{"query": nav.Direction} }, + // drill returns OK with the merged, re-ranked evidence; only an empty + // whole-corpus result (MISS) or an infra failure falls through to global. + Next: map[string]string{ + StatusOK: "", + StatusMiss: "global", + StatusEmpty: "global", + StatusError: "global", + StatusRedundant: "global", + }, + }, + { + ID: "global", + Tool: "retrieve", + Mode: ModeAuto, + Args: func(nav *NavContext) map[string]any { return map[string]any{"query": []string{nav.Direction}} }, + Next: map[string]string{}, + }, +} + +var navRuleByID = func() map[string]*NavRule { + m := make(map[string]*NavRule, len(NavRules)) + for i := range NavRules { + m[NavRules[i].ID] = &NavRules[i] + } + return m +}() + +// NavStartRule is the ladder's entry point. +const NavStartRule = "locate" + +// runDrillMerge is the `drill` rung (AUTO): corpus retrieve for REAL chunks + +// the root->chunk structure paths from navigate_structure, MERGED on chunk_id +// so every retrieved chunk carries its hierarchy context. +// +// Nav is a hint, not a constraint: retrieval runs over the WHOLE corpus (no +// doc_scope filter), but the nav-routed docs' summaries are fed back as +// retrieval keywords (soft boost), and the returned chunks are re-ranked so +// routed-doc chunks float to the top while non-routed chunks stay below. A +// multi-hop / enumeration answer living OUTSIDE the routed docs therefore +// survives — it just ranks lower — instead of being filtered out entirely. +func runDrillMerge(ctx context.Context, ts *Toolset, nav *NavContext, available map[string]bool, budgetS float64) ToolOutcome { + var merged []any + var evidenceIDs []string + seenIDs := map[string]bool{} + + // 1. Skeleton A: whole-corpus retrieval, softly boosted by the nav hints. + // Python _run_drill_merge calls _exec_retrieve(..., nav_hint=ctx.nav_hint) + // (action_session.py:_run_drill_merge): the hint is an explicit PARAMETER there, so it is + // passed explicitly here too instead of being parked on the shared executor + // (that made the model's own retrieve calls carry a hint Python never gives + // them). + retOC := ExecuteTool(ctx, ts, "retrieve", map[string]any{ + "query": []string{nav.Direction}, + "nav_hint": nav.NavHint, + }) + for _, cid := range retOC.EvidenceIDs { + if !seenIDs[cid] { + seenIDs[cid] = true + evidenceIDs = append(evidenceIDs, cid) + } + } + routedIDs := map[string]bool{} + for _, d := range nav.KnownDocs { + routedIDs[d] = true + } + + // 2. Supplement B: root->chunk paths from EVERY routed doc's structure. + paths := map[string]string{} + if available["navigate_structure"] && len(nav.KnownDocs) > 0 { + stepCtx, cancel := context.WithTimeout(ctx, stepBudget(budgetS)) + defer cancel() + for _, docID := range nav.KnownDocs { + select { + case <-stepCtx.Done(): + break + default: + } + sOC := ExecuteTool(stepCtx, ts, "navigate_structure", map[string]any{ + "doc_id": docID, "query": nav.Direction, "kind": "catalog", + }) + for _, d := range sOC.EvidenceIDs { + if !seenIDs[d] { + seenIDs[d] = true + evidenceIDs = append(evidenceIDs, d) + } + } + for cid, path := range chunkPathsFromMetrics(sOC.Metrics) { + if cid != "" { + if _, ok := paths[cid]; !ok { + paths[cid] = path + } + } + } + } + } + + // 3. Merge: skeleton A is the base; attach structure_path where ids align. + // Re-rank so routed-doc chunks float to the top WITHOUT deleting the rest. + for _, p := range retOC.Payload { + e, ok := p.(map[string]any) + if !ok { + merged = append(merged, map[string]any{"content": fmt.Sprint(p)}) + continue + } + entry := make(map[string]any, len(e)+2) + for k, v := range e { + entry[k] = v + } + if cid, ok := entry["id"].(string); ok && cid != "" { + if sp, ok := paths[cid]; ok { + entry["structure_path"] = sp + } + } + doc := "" + if v, ok := entry["doc_id"].(string); ok { + doc = v + } else if v, ok := entry["document_id"].(string); ok { + doc = v + } + rank := 1 + if routedIDs[doc] { + rank = 0 // 0 = routed (top) + } + entry["nav_rank"] = rank + merged = append(merged, entry) + } + // Stable sort: routed first, original order preserved within each group + // (Go's sort.Slice is not stable). + sort.SliceStable(merged, func(i, j int) bool { + return navRankOf(merged[i]) < navRankOf(merged[j]) + }) + + if len(merged) == 0 { + return ToolOutcome{ + Payload: []any{}, + EvidenceIDs: evidenceIDs, + Status: StatusMiss, + Reason: ReasonNoDoc, + Metrics: map[string]any{"hits": 0}, + } + } + return ToolOutcome{ + Payload: merged, + EvidenceIDs: evidenceIDs, + Status: StatusOK, + Metrics: map[string]any{"hits": len(merged), "routed": len(routedIDs)}, + } +} + +func navRankOf(v any) int { + m, ok := v.(map[string]any) + if !ok { + return 1 + } + if n, ok := m["nav_rank"].(int); ok { + return n + } + return 1 +} + +// stepBudget applies the per-step floor (Python: max(5.0, remaining)). +func stepBudget(remaining float64) time.Duration { + if remaining < navMinStepBudgetS { + remaining = navMinStepBudgetS + } + return time.Duration(remaining * float64(time.Second)) +} + +// chunkPathsFromMetrics reads metrics["chunk_paths"], tolerating the shape drift +// of model/executor-produced metrics. +func chunkPathsFromMetrics(metrics map[string]any) map[string]string { + out := map[string]string{} + raw, ok := metrics["chunk_paths"] + if !ok || raw == nil { + return out + } + switch v := raw.(type) { + case map[string]string: + return v + case map[string]any: + for k, val := range v { + out[k] = fmt.Sprint(val) + } + } + return out +} + +// navToolSurface is the set of tools this session may call. +func (t *Toolset) navToolSurface() map[string]bool { + out := map[string]bool{} + for _, s := range t.ActiveToolSpecs() { + out[s.Function.Name] = true + } + return out +} + +// NavExchange is one completed assistant/tool pair produced by the chain. +type NavExchange struct { + Messages []schema.Message + EvidenceIDs []string + Outcomes []map[string]any + // PendingRule is the rule control now rests on ("" when the ladder finished + // or was abandoned). + PendingRule string + // BudgetLeft is the unspent prefix budget in seconds. + BudgetLeft float64 +} + +// RunNavChain mirrors Python _run_nav_chain: run NavRules from startID, stopping +// at the first LLM step. +// +// AUTO steps execute here; an LLM step is returned without being run, because +// only the model can supply its arguments (e.g. which routed document to drill). +// Shared by the pre-session prefix and the in-session fallback, so both consume +// exactly the same ladder. +// idPrefix tags every tool_call id produced by a chain run so two chains sharing +// the same rule ids never collide. Python's _run_nav_chain(id_prefix="nav"|"ladder") +// does the same: the prefix case emits "nav_" and the in-session ladder +// fallback emits "ladder_", and the provider rejects a history where two +// tool_calls share an id. Go uses the same scheme. +func RunNavChain(ctx context.Context, ts *Toolset, nav *NavContext, startID string, budgetS float64, idPrefix string, maxChars int) NavExchange { + var out NavExchange + if !NavRulesEnabled { + return out + } + available := ts.navToolSurface() + + started := time.Now() + ruleID := startID + for ruleID != "" { + rule, ok := navRuleByID[ruleID] + if !ok || !available[rule.Tool] { + break + } + if rule.Mode == ModeLLM { + // Hand control back: the model must decide. + out.PendingRule = ruleID + out.BudgetLeft = budgetS - time.Since(started).Seconds() + return out + } + if rule.When != nil && !rule.When(nav) { + break + } + remaining := budgetS - time.Since(started).Seconds() + if remaining <= 1.0 { + _LOG.Printf("[Action Session] nav chain out of budget before %q", ruleID) + break + } + + var oc ToolOutcome + if rule.Run != nil { + // A composed step (e.g. drill) owns its own tool calls. + oc = rule.Run(ctx, ts, nav, available, remaining) + } else { + stepCtx, cancel := context.WithTimeout(ctx, minDuration(stepBudget(remaining), + time.Duration(navPrefixCallTimeoutS*float64(time.Second)))) + oc = ExecuteTool(stepCtx, ts, rule.Tool, rule.Args(nav)) + cancel() + } + + out.Outcomes = append(out.Outcomes, map[string]any{ + "name": rule.Tool, "status": oc.Status, "reason": oc.Reason, "metrics": oc.Metrics, + }) + if rule.Tool == "navigate_tree" && oc.Status == StatusOK { + // Routed docs become the validated scope for every later step. + nav.KnownDocs = appendUnique(nav.KnownDocs, docIDsFromPayload(oc.Payload)...) + nav.RoutedDocs = routedDocsFromMetrics(oc.Metrics) + var hints []string + for _, rd := range nav.RoutedDocs { + if rd[1] != "" { + hints = append(hints, rd[1]) + } + } + if len(hints) > 0 { + nav.NavHint = truncateRunes(strings.Join(hints, " "), navHintChars) + } + } + out.EvidenceIDs = append(out.EvidenceIDs, oc.EvidenceIDs...) + out.consumeExchange(ruleID, rule.Tool, rule.Args(nav), oc, idPrefix, maxChars) + ruleID = rule.Next[oc.Status] + } + out.PendingRule = ruleID + out.BudgetLeft = budgetS - time.Since(started).Seconds() + return out +} + +// consumeExchange appends one completed assistant/tool exchange. +// +// The pair MUST be well formed — every tool_call needs its tool response, or +// the provider rejects the history (the reason stripUnpairedToolCalls exists). +// +// maxChars caps the serialized payload, mirroring Python _emit_nav_pair +// (action_session.py:_emit_nav_pair): the in-session ladder continuation appends +// these pairs OUTSIDE the tool node's own accounting, so it passes the +// session's remaining context budget down. 0 means uncapped (the prefix path). +func (e *NavExchange) consumeExchange(ruleID, tool string, args map[string]any, oc ToolOutcome, idPrefix string, maxChars int) { + callID := fmt.Sprintf("%s_%s", idPrefix, ruleID) + rawArgs, err := json.Marshal(args) + if err != nil { + rawArgs = []byte("{}") + } + payload := marshalPassages(oc.Payload) + if maxChars > 0 && len(payload) > maxChars { + payload = payload[:max(maxChars, 800)] + } + e.Messages = append(e.Messages, + *schema.AssistantMessage("", []schema.ToolCall{{ + ID: callID, + Type: "function", + Function: schema.FunctionCall{ + Name: tool, + Arguments: string(rawArgs), + }, + }}), + *schema.ToolMessage(payload, callID), + ) +} + +// RunNavPrefix mirrors Python run_nav_prefix: run the navigation ladder up to +// the first model-driven step. +// +// The returned messages are completed assistant/tool pairs ready to seed the +// session history, so the model sees the chain as work already done and cannot +// skip a step. +// +// Returns an empty exchange when navigation is unavailable — the ladder is an +// optimisation, never a precondition for the session to run. +func RunNavPrefix(ctx context.Context, ts *Toolset, direction string, deadlineLeft float64, nav *NavContext) NavExchange { + if !NavRulesEnabled || ts == nil { + return NavExchange{} + } + available := ts.navToolSurface() + if len(available) == 0 || !available["navigate_tree"] { + return NavExchange{} + } + if nav == nil { + nav = &NavContext{Direction: direction} + } + budget := deadlineLeft * navPrefixBudgetRatio + if budget < navPrefixMinBudgetS { + budget = navPrefixMinBudgetS + } + // maxChars 0: the prefix runs before the session's context accounting starts + // (Python's run_nav_prefix also leaves _run_nav_chain's max_chars at 0). + return RunNavChain(ctx, ts, nav, NavStartRule, budget, "nav", 0) +} + +// --------------------------------------------------------------------------- +// Payload helpers +// --------------------------------------------------------------------------- + +// docIDsFromPayload reads payload[0]["doc_ids"] from a navigate_tree result. +func docIDsFromPayload(payload []any) []string { + if len(payload) == 0 { + return nil + } + first, ok := payload[0].(map[string]any) + if !ok { + return nil + } + return toStringList(first["doc_ids"]) +} + +// routedDocsFromMetrics reads metrics["routed_docs"] — a list of (doc_id, +// summary) pairs, which models/executors emit either as [doc, summary] lists or +// as {"doc_id":..., "summary":...} objects. +func routedDocsFromMetrics(metrics map[string]any) [][2]string { + raw, ok := metrics["routed_docs"] + if !ok || raw == nil { + return nil + } + list, ok := raw.([]any) + if !ok { + return nil + } + out := make([][2]string, 0, len(list)) + for _, item := range list { + switch v := item.(type) { + case []any: + if len(v) >= 2 { + out = append(out, [2]string{fmt.Sprint(v[0]), fmt.Sprint(v[1])}) + } else if len(v) == 1 { + out = append(out, [2]string{fmt.Sprint(v[0]), ""}) + } + case []string: + if len(v) >= 2 { + out = append(out, [2]string{v[0], v[1]}) + } else if len(v) == 1 { + out = append(out, [2]string{v[0], ""}) + } + case map[string]any: + id := fmt.Sprint(v["doc_id"]) + summary := "" + if s, ok := v["summary"].(string); ok { + summary = s + } + if id != "" { + out = append(out, [2]string{id, summary}) + } + } + } + return out +} + +func toStringList(v any) []string { + list, ok := v.([]any) + if !ok { + if ss, ok := v.([]string); ok { + return ss + } + return nil + } + out := make([]string, 0, len(list)) + for _, item := range list { + if item == nil { + continue + } + if s := fmt.Sprint(item); s != "" { + out = append(out, s) + } + } + return out +} + +func appendUnique(existing []string, add ...string) []string { + seen := make(map[string]bool, len(existing)) + for _, v := range existing { + seen[v] = true + } + for _, v := range add { + if !seen[v] { + seen[v] = true + existing = append(existing, v) + } + } + return existing +} + +func minDuration(a, b time.Duration) time.Duration { + if a < b { + return a + } + return b +} + +// ===================== run.go (entry points, LAST to mirror Python) ===================== +// The two public entry points of the action session — placed at the END of the +// file, mirroring Python action_session.py::run_action_session (line 1967) and +// initialize_state (line 2080) being the final definitions. +// +// Mirrors Python harness/action_session.py: +// - run_action_session (line 1967) +// - initialize_state (line 2080) + +// PromptLoader loads a named prompt template (e.g. "action_run", +// "action_initialize_state"). Python resolves these from rag/prompts/*.md via +// load_prompt; the Go harness takes the seam as an interface so the templates +// can come from the same files, from embedded assets, or from a test double. +type PromptLoader interface { + Load(name string) (string, error) +} + +// StringPromptLoader serves templates from an in-memory map. Used by tests and +// as the fallback when no filesystem loader is wired. +type StringPromptLoader map[string]string + +// Load implements PromptLoader. +func (p StringPromptLoader) Load(name string) (string, error) { + if t, ok := p[name]; ok { + return t, nil + } + return "", fmt.Errorf("harness: prompt %q not found", name) +} + +// SessionDeps are the dependencies of one action session. +type SessionDeps struct { + Tools *Toolset + Model SessionModel + // Prompts supplies the "action_run" / "action_initialize_state" templates. + // When nil, built-in fallback instructions are used. + Prompts PromptLoader + // KB is the shared evidence pool accumulated across the research so far. + // When non-nil, its chunks are injected into the seed user prompt as + // "ALREADY RETRIEVED" so the model does not re-retrieve evidence it already + // has (mirrors Python run_action_session:1982-1984). Nil skips the injection. + KB *Kbinfos +} + +// RunActionSession mirrors Python run_action_session: a bounded session +// pursuing ONE direction. +// +// Returns an empty Result (no states) when no model is configured or the +// session fails — mirroring Python, which logs and returns +// Result(messages=[], new_states=[]) rather than propagating. +func RunActionSession(ctx context.Context, deps SessionDeps, direction string, parent State, deadlineLeft float64, baseSummary string, sharedToolCache map[string]ToolOutcome, sharedSearchQueries []string) Result { + system := loadPrompt(deps.Prompts, "action_run") + seedUser := fmt.Sprintf("Direction: %s\n\nState:\n%s", direction, parent.RenderSlots()) + + // ALREADY RETRIEVED (mirrors Python run_action_session:1982-1984): + // surface the evidence already in the shared pool so the model fills slots + // from it instead of re-retrieving the same ground. Without this the ReAct + // loop repeatedly searches evidence it already holds. + if existing := extractRelevantEvidence(deps.KB, direction, 4); existing != "" { + seedUser += "\n\nALREADY RETRIEVED (do NOT re-retrieve these — use them to fill slots or identify gaps):\n" + existing + } + + if len(baseSummary) > 0 { + seedUser += fmt.Sprintf("\n\nPrior round summary:\n%s", baseSummary) + } + + if deps.Model == nil { + _LOG.Printf("[Action Session] no usable model resolved for action session") + return Result{Messages: nil, NewStates: nil} + } + + budgetLeft := deadlineLeft + if budgetLeft <= 0 { + budgetLeft = actionTimeoutS + } + + st := &SessionState{ + Messages: []schema.Message{ + *schema.SystemMessage(system), + *schema.UserMessage(seedUser), + }, + ParentState: parent, + Tools: deps.Tools, + Model: deps.Model, + PendingCalls: nil, + Done: false, + NewStates: nil, + FoundAnswer: nil, + RetrievedEvidenceIDs: nil, + Attempts: 0, + DeadlineLeft: budgetLeft, + CtxBudget: maxToolResponseChars * 4, + ToolChars: 0, + ToolCache: sharedToolCache, + SearchQueries: sharedSearchQueries, + SkippedDup: 0, + ToolStrikes: map[string]int{}, + ToolOutcomes: nil, + Direction: direction, + } + if st.ToolCache == nil { + st.ToolCache = map[string]ToolOutcome{} + } + + // The graph loop is bounded by the turn budget and the deadline; the context + // carries the wall-clock so a stalled provider cannot outlive the request. + runCtx, cancel := context.WithTimeout(ctx, deadlineToDuration(budgetLeft)) + defer cancel() + + // Deterministic navigation prefix: run the ladder IN CODE and seed the + // conversation with the completed exchanges, so the model starts on top of a + // guaranteed-correct opening instead of being merely *told* the routing rule. + // The prefix shares the ladder with the in-session fallback, and its pending + // rule becomes the session's resting point (see SessionState.NavRuleID). + nav := &NavContext{Direction: direction} + prefixStarted := time.Now() + prefix := RunNavPrefix(runCtx, deps.Tools, direction, budgetLeft, nav) + // Python run_action_session:2021/2034 — the prefix's elapsed time is charged + // to the session with a 10s floor, so prefix + loop stay inside the caller's + // deadline. Leaving DeadlineLeft at budgetLeft let one action session run a + // whole prefix longer than Python's. + st.DeadlineLeft = max(10.0, budgetLeft-time.Since(prefixStarted).Seconds()) + if len(prefix.Messages) > 0 { + st.Messages = append(st.Messages, prefix.Messages...) + st.RetrievedEvidenceIDs = append(st.RetrievedEvidenceIDs, prefix.EvidenceIDs...) + st.ToolOutcomes = append(st.ToolOutcomes, prefix.Outcomes...) + st.NavRuleID = prefix.PendingRule + st.RoutedDocs = nav.KnownDocs + st.NavHint = nav.NavHint + _LOG.Printf("[Action Session] nav prefix: %d exchange(s), %d evidence id(s), resting on %q", + len(prefix.Messages)/2, len(prefix.EvidenceIDs), prefix.PendingRule) + } + + if err := st.sessionLoop(runCtx); err != nil { + _LOG.Printf("[Action Session] session failed: %v", err) + return Result{Messages: nil, NewStates: nil} + } + return Result{ + Messages: st.Messages, + NewStates: st.NewStates, + FoundAnswer: st.FoundAnswer, + RetrievedEvidenceIDs: st.RetrievedEvidenceIDs, + TerminalType: st.TerminalType, + TerminalPayload: st.TerminalPayload, + } +} + +// InitResult mirrors Python initialize_state's tuple return: the root slot +// table plus the queries for the first round. +type InitResult struct { + Root State + FirstQueries []string +} + +// InitializeState mirrors Python initialize_state: ask the model to decompose +// the question into a slot table, with a deterministic fallback when the call +// fails. +// +// deadlineLeft bounds the decomposition call (Python: min(_INIT_TIMEOUT_S, +// deadline_left or _INIT_TIMEOUT_S)). +func InitializeState(ctx context.Context, deps SessionDeps, question string, fanoutHint []string, deadlineLeft float64) InitResult { + system := loadPrompt(deps.Prompts, "action_initialize_state") + user := "Question: " + question + if len(fanoutHint) > 0 { + user += "\n\nCandidate aspects already identified:\n" + for _, h := range fanoutHint { + user += "- " + h + "\n" + } + } + // Python :2106 — `min(_INIT_TIMEOUT_S, deadline_left or _INIT_TIMEOUT_S)`: + // 0 means "unset" (falls back to the full budget) while a NEGATIVE deadline — + // an already-exhausted round — is used as-is and times the call out at once. + tmo := initTimeoutS + if deadlineLeft != 0 && deadlineLeft < tmo { + tmo = deadlineLeft + } + + raw := initChat(ctx, deps, system, user, tmo) + data, _ := ExtractJSON(raw).(map[string]any) + if len(data) == 0 { + // One quick retry — transient provider stalls were observed (45s with + // zero bytes); a second attempt succeeded in production logs. Python + // gives the retry a LONGER budget (_init_retry_timeout, :2080-2096): on + // slow models a 45s bound times out both times and the table degrades to + // a single answer slot, losing the second hop of a multi-hop question. + raw = initChat(ctx, deps, system, user, initRetryTimeout(tmo, deadlineLeft)) + data, _ = ExtractJSON(raw).(map[string]any) + } + + // Python :2121-2129 parses the reply with int()/str()/list-comprehension + // semantics; a value it cannot convert RAISES, which _build_slot_table + // catches by discarding the whole decomposition and falling back to the + // planner fan-outs. An empty root reproduces that here. + var slots []Variable + if rawList, ok := data["slots"].([]any); ok { + for i, s := range rawList { + m, ok := s.(map[string]any) + if !ok { + // Python only builds a Variable for dict entries. + continue + } + rawID, hasID := m["id"] + if !hasID { + rawID = i + } + id, ok := pyInt(rawID) + if !ok { + _LOG.Printf("[Action Session:init] slot %d has a non-integer id (%v); discarding the decomposition", i, rawID) + return InitResult{} + } + // `str(s.get("type") or "entity")`: a falsy type is replaced, any + // other value is STRINGIFIED (never rejected). + vType := "entity" + if rawType, hasType := m["type"]; hasType && isTruthy(rawType) { + vType = PyStr(rawType) + } + clues, ok := pyStringList(m["clues"]) + if !ok { + _LOG.Printf("[Action Session:init] slot %d has non-iterable clues (%v); discarding the decomposition", i, m["clues"]) + return InitResult{} + } + if len(clues) > 4 { + clues = clues[:4] + } + slots = append(slots, Variable{ID: id, Type: vType, QuestionClues: clues}) + } + } + // Python :2130 — `[str(q).strip() for q in (data.get("first_queries") or [])][:3]`: + // the first three entries are stripped and KEPT even when they end up empty + // (the filter that used to live here made Go pick later entries instead), and + // a non-iterable value raises exactly like the slot parsing above. + rawFirst, ok := pyStringList(data["first_queries"]) + if !ok { + _LOG.Printf("[Action Session:init] first_queries is not iterable (%v); discarding the decomposition", data["first_queries"]) + return InitResult{} + } + var firstQueries []string + for j, q := range rawFirst { + if j >= 3 { + break + } + firstQueries = append(firstQueries, strings.TrimSpace(q)) + } + + if len(slots) == 0 { + // Decomposition failed (timeout/parse): build the table from planner + // fanouts so the first round still targets DISTINCT aspects instead of + // one oversized query (observed: single-slot trees answered directly and + // died, or grepped the raw question and missed). + if len(fanoutHint) > 0 { + limit := min(len(fanoutHint), 4) + for i := 0; i < limit; i++ { + h := fanoutHint[i] + if len([]rune(h)) > 120 { + h = string([]rune(h)[:120]) + } + slots = append(slots, Variable{ID: i, Type: "aspect", QuestionClues: []string{h}}) + } + if len(firstQueries) == 0 { + limit = min(len(fanoutHint), 3) + for i := 0; i < limit; i++ { + firstQueries = append(firstQueries, fanoutHint[i]) + } + } + } else { + slots = []Variable{{ID: 0, Type: "answer", QuestionClues: []string{question}}} + if len(firstQueries) == 0 { + firstQueries = []string{question} + } + } + } else if len(firstQueries) == 0 { + firstQueries = []string{question} + } + + root := NewState(slots, 0, nil) + _LOG.Printf("[Action Session:init] %s\n%s", root.Brief(), root.RenderSlots()) + return InitResult{Root: root, FirstQueries: firstQueries} +} + +// initRetryTimeout mirrors Python _init_retry_timeout (:2080-2096): the +// slot-table decomposition retry gets a longer window than the first attempt, +// because on slow models the 45s bound times out both times and the table +// degrades to a single answer slot. +// +// - floor: the first attempt's budget (never shrink below what already failed) +// - ceiling: 2x the first attempt, capped at a 90s absolute upper bound +// - deadline: leave at least 5s of the round budget for the rest of the session +func initRetryTimeout(firstTmo, deadlineLeft float64) float64 { + if deadlineLeft <= 0 { + return min(2*firstTmo, 90.0) + } + return max(firstTmo, min(min(2*firstTmo, 90.0), deadlineLeft-5.0)) +} + +// initChat mirrors Python _init_chat: ONE bounded LLM turn for the slot-table +// decomposition. Returns "" on timeout or failure — the caller falls back. +func initChat(ctx context.Context, deps SessionDeps, system, user string, tmo float64) string { + if deps.Model == nil { + return "" + } + if tmo <= 0 { + // Python :2070-2074 — `asyncio.timeout(tmo)` with a spent budget fires on + // the next tick, so the turn is abandoned before it starts. Going through + // deadlineToDuration would silently hand it the full ACTION_TIMEOUT + // instead, spending a budget the round no longer has. + _LOG.Printf("[Action Session:init] timed out (%ds)", int(tmo)) + return "" + } + callCtx, cancel := context.WithTimeout(ctx, deadlineToDuration(tmo)) + defer cancel() + reply, err := deps.Model.Complete(callCtx, []schema.Message{ + *schema.SystemMessage(system), + *schema.UserMessage(user), + }, nil) + if err != nil { + _LOG.Printf("[Action Session:init] failed: %v", err) + return "" + } + return reply.Content +} + +// --------------------------------------------------------------------------- +// Model / tool-calling seam (mirrors Python action_session.py's tool specs + +// _parse_tool_calls output + _llm_once_with_tools → _acompletion). +// --------------------------------------------------------------------------- + +// ToolFunction is the OpenAI-style function descriptor. +type ToolFunction struct { + Name string `json:"name"` + Description string `json:"description"` + Parameters map[string]any `json:"parameters"` +} + +// ToolSpec is an OpenAI-style tool schema, byte-compatible with the Python +// dicts so a provider accepting either sees the same surface. +type ToolSpec struct { + Type string `json:"type"` + Function ToolFunction `json:"function"` +} + +// ToolCall is one tool invocation requested by the model. +type ToolCall struct { + ID string + Name string + Args map[string]any + Unknown bool // name is not in ToolMap — answer with a correction, never execute +} + +// ModelReply is one model turn: either free text, or tool calls, or both. +type ModelReply struct { + Content string + ToolCalls []ToolCall + Tokens int // total tokens, for convenience (== Usage.TotalTokens when Usage != nil) + // Usage is the provider-reported prompt/completion/total split. Nil when the + // provider reported nothing. + Usage *chat.Usage +} + +// TemperatureModel is an OPTIONAL extension of SessionModel: models that can +// vary the sampling temperature per call implement it. +// +// Python sets a per-node temperature (keyword extraction uses 0.1, the answer +// composition uses the default). The Go seam originally had no temperature at +// all, so every node ran at whatever the invoker defaulted to. Callers that +// need a specific temperature type-assert to this interface and fall back to +// Complete when it is not implemented. +type TemperatureModel interface { + CompleteWithTemperature(ctx context.Context, messages []schema.Message, tools []ToolSpec, temp float64) (*ModelReply, error) +} + +// ContextLengthModel is implemented by models that can report their context +// window in tokens (Python LLMBundle.max_length), which message-fitting nodes +// use as the budget for chat.FitMessages. Callers type-assert for it and fall +// back to chat.EffectiveContextLength's 8192 default when it is absent, exactly +// mirroring Python's LLM.max_length defaulting when the model config omits +// max_tokens. This is the message_fit_in counterpart to the TemperatureModel +// seam. +type ContextLengthModel interface { + ContextLength() int +} + +// SessionModel is ONE model turn with THIS mode's tool surface. +// +// Python calls this via _llm_once_with_tools → _acompletion. The Go chat seam +// has no native tools field, so the default implementation (see +// InvokerSessionModel) asks for the call as a JSON block. Swap in a native +// implementation when the chat seam grows a tools field. +type SessionModel interface { + Complete(ctx context.Context, messages []schema.Message, tools []ToolSpec) (*ModelReply, error) +} + +// StreamingSessionModel is implemented by models that can emit the answer +// incrementally. Callers type-assert for it and fall back to the one-shot +// Complete when it is absent, so streaming is strictly an enhancement (Python +// tools.answer_sink, fed by the graph's token stream). +type StreamingSessionModel interface { + SessionModel + // StreamComplete sends the reply in pieces. onDelta receives each piece and + // isThink tells whether it belongs to a hidden reasoning block; both are + // forwarded, matching Python's answer_sink(delta, kind == "think"). + StreamComplete(ctx context.Context, messages []schema.Message, tools []ToolSpec, onDelta func(delta string, isThink bool) error) (*ModelReply, error) +} + +// Parsing of model output. +// +// Every LLM call in the harness asks for JSON, and models wrap that JSON in +// thinking preamble and Markdown fences. Python leans on json_repair for +// leniency; the Go equivalent is to strip the wrappers first and let +// encoding/json handle the rest. This mirrors Python's extract_json +// (action_session.py:extract_json), kept in the same file for parity. + +var reFence = regexp.MustCompile("```(?:json)?\\s*|\\s*```") + +// UnmarshalModelJSON mirrors Python's extract_json: strip any thinking +// preamble and Markdown fences, then parse JSON. An empty result parses as an +// empty object so callers can index into `out` without a nil check. +func UnmarshalModelJSON(text string, out any) error { + text = common.StripThinkTrailing(text) + text = reFence.ReplaceAllString(text, "") + text = strings.TrimSpace(text) + if text == "" { + return json.Unmarshal([]byte("{}"), out) + } + return json.Unmarshal([]byte(text), out) +} + +// resolveLoader returns the configured PromptLoader, or the embedded +// Markdown-backed loader when none is wired. Mirrors Python, where +// rag/prompts/template.load_prompt always reads the .md files from rag/prompts/ — +// the harness defaults to the same authoritative templates instead of the terse Go +// fallback constants. +func resolveLoader(p PromptLoader) PromptLoader { + if p != nil { + return p + } + return prompts.EmbeddedPromptLoader{} +} + +// loadPrompt resolves the prompt loader (defaulting to prompts.EmbeddedPromptLoader +// when none is wired on SessionDeps) and loads name. The canonical templates are +// the Markdown files action_run.md and action_initialize_state.md under +// internal/rag/prompts (a copy of rag/prompts/*.md on the Python side, embedded +// into the binary via //go:embed so they are never absent at runtime). This +// mirrors Python's rag/prompts/template.py::load_prompt: a missing template is an +// error, not a silent fallback to a stale string. +func loadPrompt(p PromptLoader, name string) string { + t, err := resolveLoader(p).Load(name) + if err != nil { + panic(fmt.Sprintf("loadPrompt(%q): %v", name, err)) + } + return t +} + +// deadlineToDuration converts a seconds budget to a context deadline. +// A non-positive budget falls back to the default session timeout so a caller +// that omits it does not produce an already-expired context. +func deadlineToDuration(seconds float64) time.Duration { + if seconds <= 0 { + seconds = actionTimeoutS + } + return time.Duration(seconds * float64(time.Second)) +} + +// extractRelevantEvidence mirrors Python action_session._extract_relevant_evidence +// (action_session.py:_extract_relevant_evidence — placed here, just before the entry points, to match +// Python's source order): flatten the shared evidence pool into a compact, +// line-delimited digest the model can read without re-retrieving. Chunks are +// ranked by relevance to the direction tokens (mirroring Python's token-match +// count sort), then the top maxChunks are surfaced, each truncated at 300 chars +// so the seed prompt stays bounded. +func extractRelevantEvidence(kb *Kbinfos, direction string, maxChunks int) string { + if kb == nil || maxChunks <= 0 { + return "" + } + chunks := kb.Chunks + if len(chunks) == 0 { + return "" + } + + // Build the set of direction tokens (>=2 chars, alnum or CJK) exactly as + // Python does, then rank chunks by how many tokens appear in their text. + dirTokens := tokenizeDirection(direction) + var ranked []map[string]any + if len(dirTokens) == 0 { + // No usable direction: mirror Python's chunks[-max_chunks:] fallback. + if len(chunks) > maxChunks { + ranked = chunks[len(chunks)-maxChunks:] + } else { + ranked = chunks + } + } else { + type scored struct { + chunk map[string]any + score int + } + scoredChunks := make([]scored, 0, len(chunks)) + for _, c := range chunks { + scoredChunks = append(scoredChunks, scored{chunk: c, score: directionRelevance(c, dirTokens)}) + } + sort.SliceStable(scoredChunks, func(i, j int) bool { + return scoredChunks[i].score > scoredChunks[j].score + }) + if len(scoredChunks) > maxChunks { + scoredChunks = scoredChunks[:maxChunks] + } + for _, s := range scoredChunks { + ranked = append(ranked, s.chunk) + } + } + + var b strings.Builder + for _, c := range ranked { + content := strings.TrimSpace(ChunkTextOf(c)) + if content == "" { + continue + } + // Mirror Python: hard-cut at 300 (no ellipsis) and flatten newlines so + // the digest stays single-line per chunk and matches Python output. + if len(content) > 300 { + content = content[:300] + } + content = strings.ReplaceAll(content, "\n", " ") + // Mirror Python f"[{cid}] {text}" so the model can cite the chunk id. + b.WriteString("[") + b.WriteString(ChunkIDOf(c)) + b.WriteString("] ") + b.WriteString(content) + b.WriteString("\n") + } + return strings.TrimRight(b.String(), "\n") +} + +// tokenizeDirection splits a direction string into the same >=2-char alnum/CJK +// tokens Python's re.findall(r"[a-zA-Z0-9\u4e00-\u9fff]{2,}") produces. +func tokenizeDirection(direction string) []string { + if direction == "" { + return nil + } + seen := make(map[string]struct{}) + var tokens []string + var buf strings.Builder + flush := func() { + if buf.Len() >= 2 { + tok := buf.String() + if _, dup := seen[tok]; !dup { + seen[tok] = struct{}{} + tokens = append(tokens, tok) + } + } + buf.Reset() + } + for _, r := range strings.ToLower(direction) { + switch { + case (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9') || (r >= '一' && r <= '鿿'): + buf.WriteRune(r) + default: + flush() + } + } + flush() + return tokens +} + +// directionRelevance counts how many direction tokens appear in a chunk's text, +// mirroring Python's _rel() token-match sum. +func directionRelevance(chunk map[string]any, dirTokens []string) int { + text := strings.ToLower(ChunkTextOf(chunk)) + if text == "" { + return 0 + } + score := 0 + for _, t := range dirTokens { + if strings.Contains(text, t) { + score++ + } + } + return score +} diff --git a/internal/rag/advanced_rag/harness/action_session_test.go b/internal/rag/advanced_rag/harness/action_session_test.go new file mode 100644 index 00000000000..f30a707a028 --- /dev/null +++ b/internal/rag/advanced_rag/harness/action_session_test.go @@ -0,0 +1,1091 @@ +package harness + +import ( + "context" + "errors" + "fmt" + "reflect" + "strings" + "sync" + "testing" + + "github.com/cloudwego/eino/compose" + "github.com/cloudwego/eino/schema" + "gorm.io/gorm" + "ragflow/internal/agent/chat" + "ragflow/internal/rag/prompts" +) + +// ladderExec answers the tools the navigation ladder can reach. Every call is +// recorded so the test can prove the continuation actually ran. +type ladderExec struct { + calls []string + // emptyFor makes the named tool come back empty, which is what drives a + // weak-rung continuation. + emptyFor map[string]bool +} + +func (e *ladderExec) Execute(_ context.Context, name string, _ map[string]any) (ToolOutcome, error) { + e.calls = append(e.calls, name) + if e.emptyFor[name] { + return ToolOutcome{Status: StatusEmpty, Reason: ReasonNoStructure}, nil + } + return ToolOutcome{ + Status: StatusOK, + Payload: []any{map[string]any{"kind": name, "content": "hit for " + name, "chunk_id": "c-" + name}}, + EvidenceIDs: []string{"c-" + name}, + }, nil +} + +// TestConsumeExchangeUsesIdPrefix pins Python _run_nav_chain(id_prefix=...): the +// prefix and the in-session ladder fallback share rule ids, so their tool_call +// ids must be tagged differently ("nav_" vs "ladder_") or the +// provider rejects the history as a duplicate id. +func TestConsumeExchangeUsesIdPrefix(t *testing.T) { + cases := []struct { + idPrefix string + want string + }{ + {"nav", "nav_r1"}, + {"ladder", "ladder_r1"}, + } + for _, c := range cases { + ex := &NavExchange{} + ex.consumeExchange("r1", "navigate_tree", map[string]any{"q": 1}, ToolOutcome{Payload: []any{}}, c.idPrefix, 0) + if len(ex.Messages) != 2 { + t.Fatalf("prefix %q: want 2 messages, got %d", c.idPrefix, len(ex.Messages)) + } + if got := ex.Messages[0].ToolCalls[0].ID; got != c.want { + t.Errorf("prefix %q: tool_call id = %q, want %q", c.idPrefix, got, c.want) + } + if got := ex.Messages[1].ToolCallID; got != c.want { + t.Errorf("prefix %q: tool message id = %q, want %q", c.idPrefix, got, c.want) + } + } +} + +// TestToolNodeContinuesLadderInCode pins Python action_session.py:_tool_node: +// when the rung the model just ran came back weak, the ladder keeps advancing IN +// CODE through the remaining (cheaper, wider) rungs, instead of leaving the model +// to rediscover the fallback one turn at a time. The continuation must also +// update where the ladder rests, so a later call in the SAME batch resumes from +// there rather than from the original resting point. +// +// Unreachable with the shipped NavRules (all ModeAuto), so this test installs an +// LLM rung to exercise it — the ported code is what makes a future LLM rung +// work without another change. +func TestToolNodeContinuesLadderInCode(t *testing.T) { + // Install an LLM rung that falls through to "global" (retrieve) on an empty + // result, and remove it afterwards. + const llmRung = "test-llm-rung" + navRuleByID[llmRung] = &NavRule{ + ID: llmRung, + Tool: "navigate_structure", + Mode: ModeLLM, + Next: map[string]string{StatusEmpty: "global", StatusMiss: "global"}, + } + defer delete(navRuleByID, llmRung) + + exec := &ladderExec{emptyFor: map[string]bool{"navigate_structure": true}} + ts := &Toolset{Exec: exec, ThinkingMode: "high"} + + // The model issues one call on the rung the chain handed back. + st := &SessionState{ + Tools: ts, + DeadlineLeft: 60, + Direction: "who created Culdcept", + NavRuleID: llmRung, + ToolCache: map[string]ToolOutcome{}, + PendingCalls: []ToolCall{ + {ID: "call-1", Name: "navigate_structure"}, + }, + } + + if err := st.toolNode(context.Background()); err != nil { + t.Fatalf("toolNode: %v", err) + } + + // The model's own call ran... + if len(exec.calls) == 0 || exec.calls[0] != "navigate_structure" { + t.Fatalf("calls = %v, want the model's navigate_structure call first", exec.calls) + } + // ...and the ladder then continued on its own to the "global" rung. + var sawRetrieve bool + for _, c := range exec.calls[1:] { + if c == "retrieve" { + sawRetrieve = true + } + } + if !sawRetrieve { + t.Errorf("ladder did not continue: calls = %v, want a continuation to retrieve", exec.calls) + } + // The ladder finished (the "global" rung has no Next), so the resting point + // is "" — recording "" is correct and distinct from "never advanced". + if st.NavRuleID != "" { + t.Errorf("NavRuleID = %q, want \"\" (the ladder ran to completion)", st.NavRuleID) + } + // The continuation's evidence is folded into the session, not discarded. + if len(st.RetrievedEvidenceIDs) == 0 { + t.Error("continuation evidence was dropped from RetrievedEvidenceIDs") + } + // The continuation's tool message reaches the model, so it does not repeat + // the work on its next turn. + toolMsgs := 0 + for _, m := range st.Messages { + if m.Role == schema.Tool { + toolMsgs++ + } + } + if toolMsgs < 2 { + t.Errorf("tool messages = %d, want >= 2 (the call plus the ladder's)", toolMsgs) + } +} + +// TestToolNodeLeavesLadderAloneWithNoPendingRule pins the default: with the +// shipped all-AUTO ladder there is nothing to continue, so no extra ladder work +// happens. +func TestToolNodeLeavesLadderAloneWithNoPendingRule(t *testing.T) { + exec := &ladderExec{emptyFor: map[string]bool{"retrieve": true}} + ts := &Toolset{Exec: exec, ThinkingMode: "high"} + st := &SessionState{ + Tools: ts, + DeadlineLeft: 60, + Direction: "who created Culdcept", + NavRuleID: "", // ladder finished + ToolCache: map[string]ToolOutcome{}, + PendingCalls: []ToolCall{ + {ID: "call-1", Name: "retrieve"}, + }, + } + if err := st.toolNode(context.Background()); err != nil { + t.Fatalf("toolNode: %v", err) + } + if len(exec.calls) != 1 { + t.Errorf("calls = %v, want exactly the model's one call", exec.calls) + } + if st.NavRuleID != "" { + t.Errorf("NavRuleID = %q, want \"\"", st.NavRuleID) + } +} + +// TestSessionGraphCompilesOnce pins the Python shape: _SESSION_GRAPH is built +// at import (:1936) and every session invokes THAT graph, so repeated calls must +// hand back the same runnable instead of compiling a fresh one per session. +func TestSessionGraphCompilesOnce(t *testing.T) { + first, err := sessionGraph() + if err != nil { + t.Fatalf("sessionGraph: %v", err) + } + second, err := sessionGraph() + if err != nil { + t.Fatalf("sessionGraph (second call): %v", err) + } + if first != second { + t.Error("sessionGraph compiled a new graph per call; want one shared runnable") + } +} + +// TestSessionGraphHasNoCheckpointStore guards precondition 2 of the shared +// graph: with a checkpoint store the shared runner would carry per-run +// persistence state, and concurrency would become a property of that store. +// Eino rejects a CheckPointID when no store is configured, so a successful +// invoke with one means someone wired a store in. +func TestSessionGraphHasNoCheckpointStore(t *testing.T) { + runnable, err := sessionGraph() + if err != nil { + t.Fatalf("sessionGraph: %v", err) + } + st := &SessionState{ + Tools: &Toolset{Exec: &ladderExec{}}, + Model: &fixedReplyModel{reply: &ModelReply{Content: "ok"}}, + DeadlineLeft: 30, + } + _, err = runnable.Invoke(context.Background(), st, compose.WithCheckPointID("session-1")) + if err == nil { + t.Fatal("session graph accepted a CheckPointID; it must stay checkpoint-free for shared concurrent use") + } +} + +// TestAppendMessagesKeepsRepeatToolCallIDs locks the reason appendMessages is a +// plain append and NOT a tool_call_id dedupe: fallback ids are assigned per turn +// (ensureToolCallIDs -> call_0, call_1…), so two turns can legitimately carry +// the same tool_call_id. Dropping the earlier response would orphan that turn's +// assistant tool_calls and get the next request rejected. +func TestAppendMessagesKeepsRepeatToolCallIDs(t *testing.T) { + msgs := appendMessages(nil, + *schema.ToolMessage("turn-1 answer", "call_0"), + *schema.ToolMessage("turn-2 answer", "call_0"), + ) + if len(msgs) != 2 { + t.Fatalf("len = %d, want 2 — a repeated tool_call_id must not replace", len(msgs)) + } + if msgs[0].Content != "turn-1 answer" || msgs[1].Content != "turn-2 answer" { + t.Errorf("messages = %q / %q, want both turns kept in order", msgs[0].Content, msgs[1].Content) + } +} + +// TestSessionGraphIsSharedAcrossConcurrentSessions runs many sessions through +// the shared graph at once — RunSlotResearchPass drives sessions in parallel, so +// the runnable must be safe to invoke concurrently and must keep each session's +// state separate. Each session's model echoes its own direction, so a state that +// picks up another session's reply is detectable. +func TestSessionGraphIsSharedAcrossConcurrentSessions(t *testing.T) { + const sessions = 16 + + states := make([]*SessionState, sessions) + for i := 0; i < sessions; i++ { + dir := fmt.Sprintf("direction-%02d", i) + states[i] = &SessionState{ + Direction: dir, + Tools: &Toolset{Exec: &ladderExec{}}, + Model: &fixedReplyModel{reply: &ModelReply{Content: "answer for " + dir}}, + DeadlineLeft: 60, + } + } + + var wg sync.WaitGroup + errs := make([]error, sessions) + for i := range states { + wg.Add(1) + go func(i int) { + defer wg.Done() + errs[i] = states[i].sessionLoop(context.Background()) + }(i) + } + wg.Wait() + + for i, st := range states { + if errs[i] != nil { + t.Fatalf("session %d: %v", i, errs[i]) + } + if st.Direction != fmt.Sprintf("direction-%02d", i) { + t.Errorf("session %d direction = %q; another session's state leaked in", i, st.Direction) + } + // The session must have run: attempts incremented and its own model + // echoed back into its own message list. + if st.Attempts == 0 { + t.Errorf("session %d never ran (attempts=0)", i) + } + want := "answer for " + st.Direction + sawOwn := false + for _, m := range st.Messages { + if m.Role == schema.Assistant && m.Content == want { + sawOwn = true + } + // No reply belonging to a different session may appear here. + for j := 0; j < sessions; j++ { + if j == i { + continue + } + other := fmt.Sprintf("answer for direction-%02d", j) + if m.Content == other { + t.Errorf("session %d carries session %d's reply %q", i, j, other) + } + } + } + if !sawOwn { + t.Errorf("session %d never recorded its own reply %q", i, want) + } + } +} + +// failingModel fails every Complete call, standing in for Python's +// TimeoutError / provider-exception branch of _run_action_node. +type failingModel struct{ err error } + +func (m *failingModel) Complete(_ context.Context, _ []schema.Message, _ []ToolSpec) (*ModelReply, error) { + return nil, m.err +} + +// TestRunActionNodeConvergesOnLLMError pins Python _run_action_node:1215-1220: +// a timed-out or failed turn converges the session EMPTY ({"_done": True, +// "new_states": [], "found_answer": None}) so the graph ends through _route/END +// and run_action_session still returns the messages/evidence gathered so far. +// Returning the error instead aborted the whole eino run, which RunActionSession +// reports as a failed session and answers with an empty Result. +func TestRunActionNodeConvergesOnLLMError(t *testing.T) { + s := &SessionState{ + Messages: []schema.Message{*schema.UserMessage("q")}, + Tools: &Toolset{}, + Model: &failingModel{err: errors.New("provider down")}, + DeadlineLeft: 30, + ParentState: State{State: []Variable{{ID: 0, Type: "aspect"}}}, + } + if err := s.runActionNode(context.Background()); err != nil { + t.Fatalf("runActionNode = %v; Python converges the session instead of aborting the graph", err) + } + if !s.Done { + t.Error("Done = false; the session must converge so _route returns END") + } + if len(s.NewStates) != 0 || s.FoundAnswer != nil { + t.Errorf("converged session carried states/answer: %d / %v", len(s.NewStates), s.FoundAnswer) + } + if s.Attempts != 1 { + t.Errorf("Attempts = %d, want 1 (the failed turn still counts)", s.Attempts) + } + // The session loop must terminate on the converged state rather than abort. + if err := s.sessionLoop(context.Background()); err != nil { + t.Fatalf("sessionLoop = %v; a converged session must end normally", err) + } +} + +// TestFinalizeNodeHarvestsNarrativeWhenSalvageFails pins Python +// _finalize_node:1494-1518: a failed salvage call is logged and the node still +// runs the deterministic loose-clue harvest, so the last narration survives as a +// breadcrumb on the first unresolved slot. +func TestFinalizeNodeHarvestsNarrativeWhenSalvageFails(t *testing.T) { + const narration = "The entity was founded in 1865 by a consortium of local merchants." + s := &SessionState{ + Messages: []schema.Message{ + *schema.UserMessage("q"), + *schema.AssistantMessage(narration, nil), + }, + Tools: &Toolset{}, + Model: &failingModel{err: errors.New("salvage unavailable")}, + DeadlineLeft: 30, + ParentState: State{State: []Variable{{ID: 7, Type: "aspect"}}}, + } + if err := s.finalizeNode(context.Background()); err != nil { + t.Fatalf("finalizeNode = %v", err) + } + if !s.Done { + t.Error("Done = false; finalize must mark the session done") + } + if len(s.NewStates) != 1 { + t.Fatalf("NewStates = %d, want the narrative breadcrumb patch", len(s.NewStates)) + } + clues := s.NewStates[0].State[0].DiscoveredClues + if len(clues) != 1 || !strings.HasPrefix(clues[0], "narrative: ") { + t.Errorf("discovered clues = %v, want a narrative breadcrumb", clues) + } +} + +// TestInitRetryTimeout pins Python _init_retry_timeout (:2080-2096): the slot +// table decomposition retry gets a longer window than the first attempt, floored +// at the first attempt's budget and clamped by the round deadline. +func TestInitRetryTimeout(t *testing.T) { + cases := []struct { + name string + first, deadl float64 + want float64 + }{ + {"no deadline: 2x capped at 90", 45, 0, 90}, + {"deadline leaves 5s of headroom", 45, 60, 55}, + {"floor is the first attempt's budget", 45, 40, 45}, + {"2x ceiling below 90", 30, 200, 60}, + {"deadline above the ceiling", 45, 300, 90}, + } + for _, c := range cases { + if got := initRetryTimeout(c.first, c.deadl); got != c.want { + t.Errorf("%s: initRetryTimeout(%v, %v) = %v, want %v", c.name, c.first, c.deadl, got, c.want) + } + } +} + +// TestInitializeStateKeepsEmptyFirstQueries pins Python initialize_state:2130 +// (`[str(q).strip() for q in (...)] [:3]`): the first three entries are taken +// and stripped, and an entry that strips to "" is KEPT — filtering it made Go +// pick a later entry instead. +func TestInitializeStateKeepsEmptyFirstQueries(t *testing.T) { + mdl := &fixedReplyModel{reply: &ModelReply{ + Content: `{"slots":[{"id":0,"type":"aspect","clues":["a"]}],"first_queries":[" ", "b", "c", "d"]}`, + }} + res := InitializeState(context.Background(), SessionDeps{Model: mdl}, "q", nil, 60) + want := []string{"", "b", "c"} + if len(res.FirstQueries) != len(want) { + t.Fatalf("firstQueries = %#v, want %#v", res.FirstQueries, want) + } + for i := range want { + if res.FirstQueries[i] != want[i] { + t.Errorf("firstQueries[%d] = %q, want %q", i, res.FirstQueries[i], want[i]) + } + } +} + +// TestPyIntMatchesPython pins Python's int() semantics: bool is an int subclass, +// floats truncate toward zero, strings may carry whitespace/underscores, and +// anything Python cannot convert reports failure (which discards the whole +// decomposition in initialize_state). +func TestPyIntMatchesPython(t *testing.T) { + ok := []struct { + in any + want int + }{ + {7, 7}, + {float64(7), 7}, + {float64(1.7), 1}, + {float64(-1.7), -1}, + {true, 1}, + {false, 0}, + {"5", 5}, + {" 5 ", 5}, + {"+5", 5}, + {"1_000", 1000}, + } + for _, c := range ok { + got, converted := pyInt(c.in) + if !converted || got != c.want { + t.Errorf("pyInt(%#v) = %d, %v; want %d, true", c.in, got, converted, c.want) + } + } + // Python raises for these: int("5.5") is a ValueError, int(None) a TypeError. + for _, bad := range []any{"5.5", "abc", "", nil, []any{1}, map[string]any{}} { + if _, converted := pyInt(bad); converted { + t.Errorf("pyInt(%#v) reported success; Python raises", bad) + } + } +} + +// TestPyStringListMatchesPython pins `[str(c) for c in (value or [])]`: falsy +// values yield nothing, a string yields its characters, a map its keys, and a +// non-iterable value is an error (TypeError in Python). +func TestPyStringListMatchesPython(t *testing.T) { + cases := []struct { + name string + in any + want []string + ok bool + }{ + {"nil is falsy", nil, nil, true}, + {"empty string is falsy", "", nil, true}, + {"zero is falsy", float64(0), nil, true}, + {"list items are stringified", []any{"a", 7}, []string{"a", "7"}, true}, + {"a string iterates its characters", "ab", []string{"a", "b"}, true}, + {"a map iterates its keys", map[string]any{"b": 1, "a": 2}, []string{"a", "b"}, true}, + {"a number is not iterable", float64(5), nil, false}, + {"true is not iterable", true, nil, false}, + } + for _, c := range cases { + got, converted := pyStringList(c.in) + if converted != c.ok { + t.Errorf("%s: ok = %v, want %v", c.name, converted, c.ok) + continue + } + if !converted { + continue + } + if len(got) != len(c.want) { + t.Errorf("%s: got %#v, want %#v", c.name, got, c.want) + continue + } + for i := range c.want { + if got[i] != c.want[i] { + t.Errorf("%s: got %#v, want %#v", c.name, got, c.want) + break + } + } + } +} + +// TestInitializeStateDiscardsOnUnconvertibleValues pins Python's exception path: +// int(s["id"]) and the clues comprehension raise on bad values, _build_slot_table +// catches it, and the whole decomposition is dropped in favour of the planner +// fan-outs. Go signals the same by returning an empty root. +func TestInitializeStateDiscardsOnUnconvertibleValues(t *testing.T) { + cases := []struct { + name string + body string + }{ + {"non-integer id", `{"slots":[{"id":"abc","type":"aspect","clues":["a"]}]}`}, + {"decimal id", `{"slots":[{"id":"5.5","type":"aspect"}]}`}, + {"non-iterable clues", `{"slots":[{"id":0,"type":"aspect","clues":5}]}`}, + {"non-iterable first_queries", `{"slots":[{"id":0,"type":"aspect"}],"first_queries":7}`}, + } + for _, c := range cases { + mdl := &fixedReplyModel{reply: &ModelReply{Content: c.body}} + res := InitializeState(context.Background(), SessionDeps{Model: mdl}, "q", nil, 60) + if len(res.Root.State) != 0 { + t.Errorf("%s: root has %d slot(s); Python discards the decomposition", c.name, len(res.Root.State)) + } + } +} + +// TestInitializeStateStringifiesType pins `str(s.get("type") or "entity")`: a +// falsy type becomes "entity", any other value is stringified rather than +// rejected. +func TestInitializeStateStringifiesType(t *testing.T) { + mdl := &fixedReplyModel{reply: &ModelReply{ + Content: `{"slots":[{"id":0,"type":7,"clues":["a"]},{"id":1,"type":"","clues":[]}]}`, + }} + res := InitializeState(context.Background(), SessionDeps{Model: mdl}, "q", nil, 60) + if len(res.Root.State) != 2 { + t.Fatalf("slots = %d, want 2", len(res.Root.State)) + } + if got := res.Root.State[0].Type; got != "7" { + t.Errorf("type = %q, want %q (Python str(7))", got, "7") + } + if got := res.Root.State[1].Type; got != "entity" { + t.Errorf("type = %q, want %q (falsy -> entity)", got, "entity") + } +} + +// TestInitializeStateSpentBudgetTimesOutImmediately pins Python +// initialize_state:2106 (`min(_INIT_TIMEOUT_S, deadline_left or _INIT_TIMEOUT_S)`): +// 0 means "unset", but a NEGATIVE deadline is used as-is, so asyncio.timeout fires +// on the next tick and NEITHER attempt reaches the provider — the caller then +// falls back to the planner fan-outs. +func TestInitializeStateSpentBudgetTimesOutImmediately(t *testing.T) { + mdl := &fixedReplyModel{reply: &ModelReply{ + Content: `{"slots":[{"id":0,"type":"aspect","clues":["a"]}]}`, + }} + res := InitializeState(context.Background(), SessionDeps{Model: mdl}, "q", nil, -15) + if mdl.calls != 0 { + t.Errorf("model called %d time(s); a spent budget must not reach the provider", mdl.calls) + } + // No fan-out hint → the single "answer" fallback slot, not a decomposition. + if len(res.Root.State) != 1 || res.Root.State[0].Type != "answer" { + t.Errorf("root = %+v, want the single answer fallback slot", res.Root.State) + } + if len(res.Root.State[0].QuestionClues) != 1 || res.Root.State[0].QuestionClues[0] != "q" { + t.Errorf("clues = %v, want [q]", res.Root.State[0].QuestionClues) + } +} + +// TestInitializeStateZeroDeadlineUsesFullBudget is the other half of the same +// line: an UNSET deadline (0/None) still gets the full _INIT_TIMEOUT_S budget. +func TestInitializeStateZeroDeadlineUsesFullBudget(t *testing.T) { + mdl := &fixedReplyModel{reply: &ModelReply{ + Content: `{"slots":[{"id":0,"type":"aspect","clues":["a"]}]}`, + }} + res := InitializeState(context.Background(), SessionDeps{Model: mdl}, "q", nil, 0) + if len(res.Root.State) != 1 { + t.Fatalf("root has %d slot(s), want 1", len(res.Root.State)) + } + if mdl.calls != 1 { + t.Errorf("model called %d time(s), want 1", mdl.calls) + } +} + +// TestConsumeExchangeCapsPayload pins Python _emit_nav_pair:1815-1828 — the +// in-session ladder passes its remaining context budget down, so the emitted +// tool payload is truncated; 0 keeps the prefix path uncapped. +func TestConsumeExchangeCapsPayload(t *testing.T) { + big := strings.Repeat("x", 5000) + payload := []any{map[string]any{"kind": "navigate_tree", "content": big}} + + capped := &NavExchange{} + capped.consumeExchange("r1", "navigate_tree", map[string]any{"q": 1}, ToolOutcome{Payload: payload}, "ladder", 1000) + if got := len(capped.Messages[1].Content); got > 1000 { + t.Errorf("tool payload = %d chars, want it capped at 1000", got) + } + + uncapped := &NavExchange{} + uncapped.consumeExchange("r1", "navigate_tree", map[string]any{"q": 1}, ToolOutcome{Payload: payload}, "nav", 0) + if got := len(uncapped.Messages[1].Content); got <= 1000 { + t.Errorf("tool payload = %d chars, want 0 to mean uncapped", got) + } +} + +// TestExtractJSONLenient mirrors Python action_session.extract_json's fallback +// through json.loads(strict=False) and json_repair.loads: models routinely emit +// trailing commas, single-quoted strings, bare NaN/Infinity and stray control +// characters. ExtractJSON should salvage these instead of dropping the whole +// candidate and moving to the next "{". + +func eqJSONMap(t *testing.T, got any, want map[string]any) { + t.Helper() + g, ok := got.(map[string]any) + if !ok { + t.Fatalf("got %T %v, want map %v", got, got, want) + } + if !reflect.DeepEqual(g, want) { + t.Fatalf("got %v, want %v", g, want) + } +} + +func TestExtractJSONLenient(t *testing.T) { + cases := []struct { + name string + in string + want map[string]any + }{ + {"valid passthrough", `{"a": 1}`, map[string]any{"a": float64(1)}}, + {"trailing comma", `{"a": 1,}`, map[string]any{"a": float64(1)}}, + {"single quotes", `{'a': 'b'}`, map[string]any{"a": "b"}}, + {"single quotes and trailing comma", `{'a': 1,}`, map[string]any{"a": float64(1)}}, + {"NaN literal", `{"x": NaN}`, map[string]any{"x": nil}}, + {"Infinity literal", `{"x": Infinity}`, map[string]any{"x": nil}}, + {"negative Infinity", `{"x": -Infinity}`, map[string]any{"x": nil}}, + {"control char in string", "{\"a\": \"x\x01y\"}", map[string]any{"a": "xy"}}, + {"prefixed text", `blah {"a": 1} blah`, map[string]any{"a": float64(1)}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + eqJSONMap(t, ExtractJSON(c.in), c.want) + }) + } +} + +func TestExtractJSONLenientUnrecoverable(t *testing.T) { + // The brace-matched loop tries each "{" candidate; the deep json_repair + // fallback salvages the FIRST candidate even when it is malformed (mirroring + // Python, where json_repair.loads({"a":}) yields {"a": null}). It must not + // panic, hang, or return nil for a salvageable object. + v := ExtractJSON(`{"a":} {"b": 2}`) + if v == nil { + t.Fatalf("first candidate should be salvaged, got nil") + } + // Empty input has nothing to salvage and must return nil (not panic). + if v := ExtractJSON(``); v != nil { + t.Fatalf("empty input: got %v, want nil", v) + } +} + +// TestExtractJSONWholeTextRepair mirrors Python json_repair.loads(text) on the +// WHOLE text — deformities that no single brace-matched candidate can fix. +func TestExtractJSONWholeTextRepair(t *testing.T) { + cases := []struct { + name string + in string + want map[string]any + }{ + // Unquoted object keys (Python json_repair quotes them). + {"unquoted key", `{a: 1}`, map[string]any{"a": float64(1)}}, + {"unquoted keys multiple", `{name: foo, age: 3}`, map[string]any{"name": "foo", "age": float64(3)}}, + // Dropped separator between adjacent values. + {"missing separator obj", `{"a": 1 "b": 2}`, map[string]any{"a": float64(1), "b": float64(2)}}, + {"missing separator after array", `{"a": [1,2] "b": 3}`, map[string]any{"a": []any{float64(1), float64(2)}, "b": float64(3)}}, + // Outer braces present but keys/values deformed (json_repair recovers). + {"deformed object", `{a: 1, b: 2}`, map[string]any{"a": float64(1), "b": float64(2)}}, + // Combination: unquoted key + trailing comma + missing separator. + {"combined deformity", `{name: foo, "age": 3 "city": bar,}`, map[string]any{"name": "foo", "age": float64(3), "city": "bar"}}, + // Prefixed prose with a deformed object. + {"prose plus unquoted key", `Here is the answer: {entity: "x", relation: "y"}`, map[string]any{"entity": "x", "relation": "y"}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + eqJSONMap(t, ExtractJSON(c.in), c.want) + }) + } +} + +// TestExtractJSONThinkFenceStillPreprocessed ensures the whole-text fallback +// still strips preambles and ```json fences before deep repair. +func TestExtractJSONThinkFenceStillPreprocessed(t *testing.T) { + in := "```json\n{name: foo, value: 1}\n```" + eqJSONMap(t, ExtractJSON(in), map[string]any{"name": "foo", "value": float64(1)}) + think := "reasoning{\"a\": 1,}" + eqJSONMap(t, ExtractJSON(think), map[string]any{"a": float64(1)}) +} + +// recordingInvoker captures the outgoing chat.Request so the test can assert +// what the model was actually shown. +type recordingInvoker struct{ req chat.Request } + +func (r *recordingInvoker) Invoke(_ context.Context, _ *gorm.DB, req chat.Request) (*chat.Response, error) { + r.req = req + return &chat.Response{Content: "ok"}, nil +} + +// fixedReplyModel returns a canned ModelReply so tests can drive the session +// nodes without a real model. +type fixedReplyModel struct { + reply *ModelReply + calls int +} + +func (m *fixedReplyModel) Complete(_ context.Context, _ []schema.Message, _ []ToolSpec) (*ModelReply, error) { + m.calls++ + return m.reply, nil +} + +func declaredTools() []ToolSpec { + return []ToolSpec{{ + Function: ToolFunction{ + Name: "retrieve", + Description: "run retrieval", + Parameters: map[string]any{"type": "object"}, + }, + }} +} + +// TestNoPromptBasedToolInstruction pins the alignment with Python: Python has NO +// tool-call instruction of any kind — it binds tools natively +// (action_session.py:_acompletion) and reads msg.tool_calls (:1101-1114). A prompt-based +// protocol is a Go-only addition and must not be sent, least of all one whose +// "at most one tool per reply" clause contradicts the native tool list. +func TestNoPromptBasedToolInstruction(t *testing.T) { + inv := &recordingInvoker{} + m := &InvokerSessionModel{Invoker: inv} + if _, err := m.Complete(context.Background(), + []schema.Message{*schema.UserMessage("q")}, declaredTools()); err != nil { + t.Fatalf("Complete: %v", err) + } + + if len(inv.req.Tools) == 0 { + t.Fatal("native tools were not declared") + } + // The fallback prompt must never be sent, with native tools or without. + if _, err := m.Complete(context.Background(), + []schema.Message{*schema.UserMessage("q")}, + []ToolSpec{{Function: ToolFunction{Description: "unnamed"}}}); err != nil { + t.Fatalf("Complete: %v", err) + } + for _, msg := range inv.req.Messages { + if strings.Contains(msg.Content, "at most one tool per reply") { + t.Errorf("prompt-based tool instruction sent: %q", msg.Content) + } + } +} + +// TestAssistantMessageCarriesToolCalls pins Python action_session.py:_run_action_node: +// the assistant message carries the model's tool_calls verbatim so the tool +// responses that follow can be paired by id. Passing nil leaves a dangling +// tool_call, and the next request is rejected with "tool call result does not +// follow tool call". +func TestAssistantMessageCarriesToolCalls(t *testing.T) { + st := &SessionState{ + Messages: []schema.Message{*schema.SystemMessage("s")}, + Tools: &Toolset{Exec: &ladderExec{}}, + Model: &fixedReplyModel{reply: &ModelReply{Content: "thinking", ToolCalls: []ToolCall{ + {ID: "", Name: "retrieve", Args: map[string]any{"query": "q1"}}, + {ID: "", Name: "retrieve", Args: map[string]any{"query": "q2"}}, + }}}, + } + if err := st.runActionNode(context.Background()); err != nil { + t.Fatalf("runActionNode: %v", err) + } + + var assistant *schema.Message + for i := range st.Messages { + if st.Messages[i].Role == schema.Assistant { + assistant = &st.Messages[i] + } + } + if assistant == nil { + t.Fatal("no assistant message was appended") + } + if len(assistant.ToolCalls) != 2 { + t.Fatalf("assistant tool_calls = %d, want 2 (pass-through, and both kept)", len(assistant.ToolCalls)) + } + // Python synthesizes call_{i} when the provider omits the id + // (:1134/:1136); the tool responses reference the same ids. + if assistant.ToolCalls[0].ID != "call_0" || assistant.ToolCalls[1].ID != "call_1" { + t.Errorf("ids = %q, %q; want call_0, call_1", assistant.ToolCalls[0].ID, assistant.ToolCalls[1].ID) + } + if assistant.ToolCalls[0].Function.Name != "retrieve" { + t.Errorf("name = %q, want retrieve", assistant.ToolCalls[0].Function.Name) + } + // The pending calls must carry the SAME ids the assistant message declared. + for i, c := range st.PendingCalls { + if c.ID == "" { + t.Errorf("pending call %d has no id; tool response cannot pair with the assistant message", i) + } + } +} + +// TestDisabledToolIsNotUnknown pins Python action_session.py:_parse_tool_calls — +// `if name not in _TOOL_MAP`. The check is against the STATIC full set, not the +// active surface, so a tool this session disabled (or hid for lack of a web +// provider) is still a known tool: the model must get the "unavailable, use +// this instead" note from ExecuteTool, not an "unknown tool" correction. +func TestDisabledToolIsNotUnknown(t *testing.T) { + // Sanity: the name must be a real tool for the test to mean anything. + if _, ok := ToolMap["graph_explore"]; !ok { + t.Skip("graph_explore is not a registered tool") + } + ts := &Toolset{ThinkingMode: "high"} + // Disable it: it now drops out of the active surface but stays in ToolMap. + ts.DisableTool("graph_explore") + for _, spec := range ts.ActiveToolSpecs() { + if spec.Function.Name == "graph_explore" { + t.Fatal("graph_explore must be absent from the active surface for this test") + } + } + calls := nativeToHarnessCalls([]chat.ToolCall{{Name: "graph_explore"}}) + if len(calls) != 1 { + t.Fatalf("calls = %d, want 1", len(calls)) + } + if calls[0].Unknown { + t.Error("a disabled tool must NOT be Unknown: Python judges against _TOOL_MAP, " + + "so the call gets the 'unavailable, use this instead' note") + } +} + +// TestUnknownToolStillFlagged pins the other side of :1124 — a name that is not +// a real tool at all IS flagged Unknown, so it is answered with a correction +// instead of being executed. +func TestUnknownToolStillFlagged(t *testing.T) { + calls := nativeToHarnessCalls([]chat.ToolCall{{Name: "definitely_not_a_tool"}}) + if len(calls) != 1 || !calls[0].Unknown { + t.Fatalf("calls = %+v, want one Unknown call", calls) + } +} + +// TestNativeToolCallsPreserveAll pins the execution contract: every native tool +// call is mapped, not just the first — Python executes all of them +// (action_session.py:_tool_node `for c in pending`). +func TestNativeToolCallsPreserveAll(t *testing.T) { + calls := nativeToHarnessCalls([]chat.ToolCall{ + {ID: "1", Name: "retrieve"}, + {ID: "2", Name: "retrieve"}, + {ID: "3", Name: "bogus"}, + }) + if len(calls) != 3 { + t.Fatalf("mapped %d calls, want 3 (all of them, not just the first)", len(calls)) + } + if !calls[2].Unknown { + t.Error("an undeclared name must be flagged Unknown") + } +} + +// streamingInvoker streams a fixed set of pieces. +type streamingInvoker struct { + pieces []piece + err error +} + +type piece struct { + text string + isThink bool +} + +func (s *streamingInvoker) Invoke(context.Context, *gorm.DB, chat.Request) (*chat.Response, error) { + return &chat.Response{Content: "one-shot"}, nil +} + +func (s *streamingInvoker) Stream(_ context.Context, _ *gorm.DB, _ chat.Request, onDelta func(string, bool) error) (*chat.Response, error) { + if s.err != nil { + return nil, s.err + } + var content, reasoning string + for _, p := range s.pieces { + if onDelta != nil { + if err := onDelta(p.text, p.isThink); err != nil { + return nil, err + } + } + if p.isThink { + reasoning += p.text + } else { + content += p.text + } + } + return &chat.Response{Content: content, Thinking: reasoning}, nil +} + +// plainInvoker only implements the non-streaming seam. +type plainInvoker struct{} + +func (p *plainInvoker) Invoke(context.Context, *gorm.DB, chat.Request) (*chat.Response, error) { + return &chat.Response{Content: "one-shot"}, nil +} + +func TestStreamCompleteForwardsDeltas(t *testing.T) { + m := &InvokerSessionModel{Invoker: &streamingInvoker{pieces: []piece{ + {text: "think", isThink: true}, + {text: "Hello ", isThink: false}, + {text: "world", isThink: false}, + }}} + + var got []piece + reply, err := m.StreamComplete(context.Background(), []schema.Message{*schema.UserMessage("q")}, nil, + func(delta string, isThink bool) error { + got = append(got, piece{text: delta, isThink: isThink}) + return nil + }) + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if reply.Content != "Hello world" { + t.Fatalf("Content = %q, want %q", reply.Content, "Hello world") + } + if len(got) != 3 || !got[0].isThink || got[0].text != "think" { + t.Fatalf("deltas = %+v, want reasoning flagged first", got) + } +} + +func TestStreamCompleteFailsWithoutStreamingInvoker(t *testing.T) { + // A non-streaming invoker must report failure so the caller falls back to + // the one-shot call rather than silently producing nothing. + m := &InvokerSessionModel{Invoker: &plainInvoker{}} + + if _, err := m.StreamComplete(context.Background(), nil, nil, nil); err == nil { + t.Fatal("want an error when the invoker cannot stream") + } +} + +func TestStreamCompletePropagatesError(t *testing.T) { + m := &InvokerSessionModel{Invoker: &streamingInvoker{err: errors.New("provider down")}} + + if _, err := m.StreamComplete(context.Background(), nil, nil, nil); err == nil { + t.Fatal("want the provider error") + } +} + +func TestStreamCompleteRequiresInvoker(t *testing.T) { + m := &InvokerSessionModel{} + + if _, err := m.StreamComplete(context.Background(), nil, nil, nil); err == nil { + t.Fatal("want an error when no invoker is configured") + } +} + +type capturingInvoker struct { + lastReq *chat.Request + hasTool bool + tool chat.ToolCall + content string +} + +func (c *capturingInvoker) Invoke(_ context.Context, _ *gorm.DB, req chat.Request) (*chat.Response, error) { + c.lastReq = &req + resp := &chat.Response{Content: c.content} + if c.hasTool { + resp.ToolCalls = []chat.ToolCall{c.tool} + } + return resp, nil +} + +func TestCompleteForwardsNativeToolsAndPrefersNativeCalls(t *testing.T) { + tools := []ToolSpec{{ + Type: "function", + Function: ToolFunction{ + Name: "search", + Description: "run a search", + Parameters: map[string]any{"type": "object", "properties": map[string]any{}}, + }, + }} + inv := &capturingInvoker{hasTool: true, tool: chat.ToolCall{ID: "c1", Name: "search", Arguments: map[string]any{"q": "x"}}, content: "ok"} + m := &InvokerSessionModel{Invoker: inv} + + reply, err := m.Complete(context.Background(), []schema.Message{*schema.UserMessage("q")}, tools) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if inv.lastReq == nil || len(inv.lastReq.Tools) != 1 { + t.Fatalf("tools not forwarded to invoker: req=%+v", inv.lastReq) + } + if inv.lastReq.Tools[0].Function.Name != "search" { + t.Fatalf("forwarded tool name = %q, want search", inv.lastReq.Tools[0].Function.Name) + } + if inv.lastReq.ToolChoice != chat.ToolChoiceAuto { + t.Fatalf("tool choice = %q, want auto", inv.lastReq.ToolChoice) + } + if len(reply.ToolCalls) != 1 || reply.ToolCalls[0].Name != "search" || reply.ToolCalls[0].Args["q"] != "x" { + t.Fatalf("native tool call not preferred: %+v", reply.ToolCalls) + } +} + +func TestCompleteReportsNoCallWhenModelSendsNoNativeCall(t *testing.T) { + inv := &capturingInvoker{hasTool: false, content: ""} + m := &InvokerSessionModel{Invoker: inv} + tools := []ToolSpec{{ + Type: "function", + Function: ToolFunction{Name: "search", Description: "d", Parameters: map[string]any{}}, + }} + + // No native tool_calls => the reply stays tool-less. This confirms the + // harness still declares tools on the request (verified above) but does not + // hallucinate a call, matching Python, which has no other parsing path. + reply, err := m.Complete(context.Background(), []schema.Message{*schema.UserMessage("q")}, tools) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(reply.ToolCalls) != 0 { + t.Fatalf("expected no tool calls, got %+v", reply.ToolCalls) + } +} + +// streamingCapturingInvoker implements chat.StreamingInvoker and records the +// streaming request, returning a native tool call so we can verify the harness +// reads streamed calls out of the native tool_calls field. +type streamingCapturingInvoker struct { + capturingInvoker + onDelta func(delta string, isThink bool) error +} + +func (s *streamingCapturingInvoker) Stream(_ context.Context, _ *gorm.DB, req chat.Request, onDelta func(delta string, isThink bool) error) (*chat.Response, error) { + s.lastReq = &req + if onDelta != nil { + _ = onDelta("partial", false) + } + resp := &chat.Response{Content: "streamed"} + if s.hasTool { + resp.ToolCalls = []chat.ToolCall{s.tool} + } + return resp, nil +} + +func TestStreamCompleteForwardsNativeToolsAndPrefersNativeCalls(t *testing.T) { + tools := []ToolSpec{{ + Type: "function", + Function: ToolFunction{ + Name: "search", + Description: "run a search", + Parameters: map[string]any{"type": "object", "properties": map[string]any{}}, + }, + }} + inv := &streamingCapturingInvoker{ + capturingInvoker: capturingInvoker{ + hasTool: true, + tool: chat.ToolCall{ID: "c2", Name: "search", Arguments: map[string]any{"q": "y"}}, + }, + } + m := &InvokerSessionModel{Invoker: inv} + + reply, err := m.StreamComplete(context.Background(), []schema.Message{*schema.UserMessage("q")}, tools, nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if inv.lastReq == nil || len(inv.lastReq.Tools) != 1 || inv.lastReq.Tools[0].Function.Name != "search" { + t.Fatalf("streaming tools not forwarded: req=%+v", inv.lastReq) + } + if inv.lastReq.ToolChoice != chat.ToolChoiceAuto { + t.Fatalf("streaming tool choice = %q, want auto", inv.lastReq.ToolChoice) + } + if len(reply.ToolCalls) != 1 || reply.ToolCalls[0].Name != "search" || reply.ToolCalls[0].Args["q"] != "y" { + t.Fatalf("streamed native tool call not preferred: %+v", reply.ToolCalls) + } +} + +func TestStreamCompleteIgnoresFencedBlockInContent(t *testing.T) { + tools := []ToolSpec{{ + Type: "function", + Function: ToolFunction{Name: "search", Description: "d", Parameters: map[string]any{}}, + }} + // A fenced block in the content is NOT a tool call: Python only reads + // msg.tool_calls, and this port has no prompt-based parsing path. + inv := &streamingCapturingInvoker{ + capturingInvoker: capturingInvoker{ + hasTool: false, + content: "```json\n{\"tool\": \"search\", \"args\": {\"q\": \"ignored\"}}\n```", + }, + } + m := &InvokerSessionModel{Invoker: inv} + + reply, err := m.StreamComplete(context.Background(), []schema.Message{*schema.UserMessage("q")}, tools, nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if len(reply.ToolCalls) != 0 { + t.Fatalf("fenced block must not be parsed as a tool call: %+v", reply.ToolCalls) + } +} + +func TestRenderPromptUsesLoader(t *testing.T) { + loader := StringPromptLoader{"tpl": "hello {{ name }}!"} + // Loader resolves the name: variable substituted. + if got := prompts.Render(loader, "tpl", "", map[string]string{"name": "world"}); got != "hello world!" { + t.Errorf("prompts.Render = %q", got) + } + // Unknown template with empty fallback -> empty (Python has no degraded + // constant; a missing template fails fast rather than degrading). + if got := prompts.Render(loader, "missing", "", nil); got != "" { + t.Errorf("unknown template with empty fallback = %q", got) + } + // Nil loader + known embedded name still resolves the canonical .md. + if got := prompts.Render(nil, "sca_select", "", map[string]string{"question": "Q"}); !strings.Contains(got, "Q") { + t.Errorf("nil loader did not resolve embedded sca_select: %q", got) + } + // Both {{k}} and {{ k }} are substituted (templates use the spaced form). + if got := prompts.Render(StringPromptLoader{"tpl": "a={{x}} b={{ y }}"}, "tpl", "", + map[string]string{"x": "1", "y": "2"}); got != "a=1 b=2" { + t.Errorf("spaced placeholder not substituted: %q", got) + } +} + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- diff --git a/internal/rag/advanced_rag/harness/arithmetic.go b/internal/rag/advanced_rag/harness/arithmetic.go new file mode 100644 index 00000000000..8939c7d082b --- /dev/null +++ b/internal/rag/advanced_rag/harness/arithmetic.go @@ -0,0 +1,1600 @@ +// +// 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. +// + +package harness + +import ( + "context" + "fmt" + "math" + "strconv" + "strings" + "time" + "unicode" + + "github.com/cloudwego/eino/schema" + + "ragflow/internal/agent/chat" +) + +// Deterministic arithmetic over retrieved evidence. +// +// Mirrors Python harness/arithmetic.py. +// +// Some questions ask for a number no single source states — the combined population of +// three counties, how many listed films won an award, the years between two dates. Every +// input is in the evidence by then and only the arithmetic is missing, which an LLM does +// by writing digits one at a time and gets wrong often enough to matter. So the LLM +// writes ONE expression and we evaluate it. +// +// The expression is model-written and NOT trusted: Go has no eval and the model writes +// PYTHON syntax (`**`, `x if y else z`, list literals) that go/parser cannot read, so +// this file ships a small parser for a deliberately tiny Python subset and rejects +// everything outside the whitelist BEFORE evaluation. No reflection, no name lookup, no +// property access: an unlisted construct is a parse error, not a sandbox escape. +// +// Public interface +// +// Compute(expression) -> (rendered, error) evaluate one expression safely. +// ComputeFromFacts(question, facts, fitBudget) -> *ComputedFact | nil +// ask the model whether the question asks for a derivable number; if so, +// write the expression, evaluate it, return a structured result. + +const ( + // computeMaxChars caps the whole expression; every figure is inline, none + // is long (Python: _COMPUTE_MAX_CHARS). + computeMaxChars = 400 + // maxStringLiteral caps a string literal argument (Python: 256). + maxStringLiteral = 256 + // maxPowExponent caps `**` (Python: abs(exponent) > 64 is refused). + maxPowExponent = 64 +) + +// Compute evaluates an LLM-written arithmetic expression. +// Returns (rendered, error); exactly one of the two is non-empty. Every +// rejection is a normal outcome — the caller simply carries on without the +// computed evidence. +func Compute(expression string) (string, string) { + expr := strings.TrimSpace(expression) + if expr == "" { + return "", "empty expression" + } + if len(expr) > computeMaxChars { + return "", fmt.Sprintf("expression is longer than %d characters", computeMaxChars) + } + p := &parser{src: expr} + node, err := p.parseExpression() + if err != nil { + return "", err.Error() + } + if rest := p.skipSpace(); rest < len(p.src) { + return "", fmt.Sprintf("unexpected trailing input at %d", rest) + } + if problem := checkExpression(node); problem != "" { + return "", problem + } + value, err := evalSafe(node) + if err != nil { + return "", fmt.Sprintf("failed to evaluate (%v)", err) + } + switch v := value.(type) { + case bool: + return "", "result is bool, not a number" + case int64: + return formatNumber(float64(v)), "" + case float64: + if math.IsNaN(v) || math.IsInf(v, 0) { + return "", "result is not a finite number" + } + return formatNumber(v), "" + } + return "", fmt.Sprintf("result is %T, not a number", value) +} + +// formatNumber mirrors Python _format_number: render a computed number without +// float noise ("3.0" -> "3", 0.1+0.2 -> "0.3"). +func formatNumber(value float64) string { + if value == math.Trunc(value) && math.Abs(value) < 1e15 { + return strconv.FormatInt(int64(value), 10) + } + s := strconv.FormatFloat(value, 'f', 6, 64) + s = strings.TrimRight(s, "0") + return strings.TrimRight(s, ".") +} + +// --------------------------------------------------------------------------- +// AST +// --------------------------------------------------------------------------- + +type node interface{ pos() int } + +type constNode struct { + p int + kind string // "int" | "float" | "str" | "bool" + num float64 + str string +} + +func (n *constNode) pos() int { return n.p } + +type nameNode struct { + p int + name string +} + +func (n *nameNode) pos() int { return n.p } + +type unaryNode struct { + p int + op string + operand node +} + +func (n *unaryNode) pos() int { return n.p } + +type binaryNode struct { + p int + op string + left, right node +} + +func (n *binaryNode) pos() int { return n.p } + +// chainNode mirrors Python ast.Compare, which is an N-ary node: `a < b < c` is +// `(a < b) and (b < c)`, with each operand evaluated exactly ONCE and the chain +// short-circuiting on the first false comparison. +// +// Building it as left-associative binary nodes instead — `((a < b) < c)` — +// compares the previous comparison's BOOLEAN result against the next operand, +// so `3 > 2 > 1` becomes `True > 1` = `1 > 1` = false, and `2 < 1 < 3` becomes +// `False < 3` = `0 < 3` = true. Both are wrong. +type chainNode struct { + p int + ops []string // len(operands) - 1 + operands []node +} + +func (n *chainNode) pos() int { return n.p } + +type ifExpNode struct { + p int + cond, body, orelse node +} + +func (n *ifExpNode) pos() int { return n.p } + +type callNode struct { + p int + fn string + args []node +} + +func (n *callNode) pos() int { return n.p } + +type seqNode struct { + p int + kind string // "list" | "tuple" | "set" + elts []node +} + +func (n *seqNode) pos() int { return n.p } + +// --------------------------------------------------------------------------- +// Lexer + Pratt parser for a tiny Python subset +// --------------------------------------------------------------------------- + +// Supported: numeric and string literals, True/False/None, list/tuple/set +// literals, unary + - not, binary + - * / // % ** and comparison chains, `and` +// / `or`, the ternary `a if b else c`, and calls to the whitelisted functions. +// Everything else — attributes, subscripts, comprehensions, lambdas, f-strings, +// assignments, imports — is a parse error. +type parser struct { + src string + i int +} + +func (p *parser) skipSpace() int { + for p.i < len(p.src) && (p.src[p.i] == ' ' || p.src[p.i] == '\t') { + p.i++ + } + return p.i +} + +func (p *parser) errf(format string, args ...any) error { + return fmt.Errorf("does not parse (%s)", fmt.Sprintf(format, args...)) +} + +func (p *parser) parseExpression() (node, error) { return p.parseTernary() } + +func (p *parser) parseTernary() (node, error) { + body, err := p.parseOr() + if err != nil { + return nil, err + } + p.skipSpace() + if !p.matchWord("if") { + return body, nil + } + cond, err := p.parseOr() + if err != nil { + return nil, err + } + p.skipSpace() + if !p.matchWord("else") { + return nil, p.errf("ternary needs 'else'") + } + orelse, err := p.parseExpression() + if err != nil { + return nil, err + } + return &ifExpNode{p: 0, cond: cond, body: body, orelse: orelse}, nil +} + +func (p *parser) parseOr() (node, error) { + left, err := p.parseAnd() + if err != nil { + return nil, err + } + for { + p.skipSpace() + if !p.matchWord("or") { + return left, nil + } + right, err := p.parseAnd() + if err != nil { + return nil, err + } + left = &binaryNode{op: "or", left: left, right: right} + } +} + +func (p *parser) parseAnd() (node, error) { + left, err := p.parseNot() + if err != nil { + return nil, err + } + for { + p.skipSpace() + if !p.matchWord("and") { + return left, nil + } + right, err := p.parseNot() + if err != nil { + return nil, err + } + left = &binaryNode{op: "and", left: left, right: right} + } +} + +func (p *parser) parseNot() (node, error) { + p.skipSpace() + if p.matchWord("not") { + operand, err := p.parseNot() + if err != nil { + return nil, err + } + return &unaryNode{op: "not", operand: operand}, nil + } + return p.parseComparison() +} + +var cmpOps = []string{"==", "!=", "<=", ">=", "<", ">"} + +// parseComparison collects the WHOLE comparison chain into one chainNode, +// mirroring Python's ast.Compare. Two or more operators are what make Python's +// chaining observable; a single comparison is just a one-op chain. +func (p *parser) parseComparison() (node, error) { + start := p.i + first, err := p.parseSum() + if err != nil { + return nil, err + } + operands := []node{first} + var ops []string + for { + p.skipSpace() + matched := "" + for _, op := range cmpOps { + if strings.HasPrefix(p.src[p.i:], op) { + matched = op + break + } + } + if matched == "" { + break + } + p.i += len(matched) + right, err := p.parseSum() + if err != nil { + return nil, err + } + ops = append(ops, matched) + operands = append(operands, right) + } + if len(ops) == 0 { + return first, nil + } + return &chainNode{p: start, ops: ops, operands: operands}, nil +} + +func (p *parser) parseSum() (node, error) { + left, err := p.parseProduct() + if err != nil { + return nil, err + } + for { + p.skipSpace() + if p.i >= len(p.src) { + return left, nil + } + var op string + switch p.src[p.i] { + case '+': + op = "+" + case '-': + op = "-" + default: + return left, nil + } + p.i++ + right, err := p.parseProduct() + if err != nil { + return nil, err + } + left = &binaryNode{op: op, left: left, right: right} + } +} + +func (p *parser) parseProduct() (node, error) { + left, err := p.parseUnary() + if err != nil { + return nil, err + } + for { + p.skipSpace() + if p.i >= len(p.src) { + return left, nil + } + var op string + switch { + case strings.HasPrefix(p.src[p.i:], "**"): + op = "**" + case strings.HasPrefix(p.src[p.i:], "//"): + op = "//" + case p.src[p.i] == '*': + op = "*" + case p.src[p.i] == '/': + op = "/" + case p.src[p.i] == '%': + op = "%" + default: + return left, nil + } + p.i += len(op) + right, err := p.parseUnary() + if err != nil { + return nil, err + } + left = &binaryNode{op: op, left: left, right: right} + } +} + +func (p *parser) parseUnary() (node, error) { + p.skipSpace() + if p.i < len(p.src) { + switch p.src[p.i] { + case '-': + p.i++ + operand, err := p.parseUnary() + if err != nil { + return nil, err + } + return &unaryNode{op: "-", operand: operand}, nil + case '+': + p.i++ + operand, err := p.parseUnary() + if err != nil { + return nil, err + } + return &unaryNode{op: "+", operand: operand}, nil + } + } + return p.parsePower() +} + +// parsePower binds tighter than unary on the right and is right-associative, +// matching Python: `2 ** 3 ** 2` is 512 and `-2 ** 2` is -4. +func (p *parser) parsePower() (node, error) { + base, err := p.parseAtom() + if err != nil { + return nil, err + } + p.skipSpace() + if strings.HasPrefix(p.src[p.i:], "**") { + p.i += 2 + exponent, err := p.parseUnary() + if err != nil { + return nil, err + } + return &binaryNode{op: "**", left: base, right: exponent}, nil + } + return base, nil +} + +func (p *parser) parseAtom() (node, error) { + p.skipSpace() + if p.i >= len(p.src) { + return nil, p.errf("unexpected end of expression") + } + start := p.i + c := p.src[p.i] + + switch { + case c == '(': + p.i++ + inner, err := p.parseExpression() + if err != nil { + return nil, err + } + p.skipSpace() + if p.i >= len(p.src) { + return nil, p.errf("unclosed '('") + } + // A trailing (or interior) comma turns this into a TUPLE literal, which + // Python whitelists as ast.Tuple and uses as the default sequence in + // sum((1,2,3)) / len((1,2,3)) / min((1,2,3)) / letters((...)). A single + // element with no comma is a plain parenthesised expression (not a + // one-tuple) — Python's `(1+2)` == 3 vs `(1,)` == (1,). + if p.src[p.i] == ',' { + items := []node{inner} + for { + p.i++ // consume ',' + p.skipSpace() + if p.i >= len(p.src) { + return nil, p.errf("unclosed '('") + } + if p.src[p.i] == ')' { + p.i++ + return &seqNode{kind: "tuple", elts: items}, nil + } + elem, err := p.parseExpression() + if err != nil { + return nil, err + } + items = append(items, elem) + p.skipSpace() + if p.i >= len(p.src) { + return nil, p.errf("unclosed '('") + } + if p.src[p.i] == ')' { + p.i++ + return &seqNode{kind: "tuple", elts: items}, nil + } + if p.src[p.i] != ',' { + return nil, p.errf("unclosed '('") + } + } + } + if p.src[p.i] != ')' { + return nil, p.errf("unclosed '('") + } + p.i++ + return inner, nil + case c == '[': + return p.parseSeq("[", "]", "list") + case c == '{': + return p.parseSeq("{", "}", "set") + case c == '"' || c == '\'': + return p.parseString() + case c >= '0' && c <= '9': + return p.parseNumber() + case isIdentStart(c): + return p.parseNameOrCall() + } + return nil, p.errf("unexpected character %q at %d", string(c), start) +} + +func (p *parser) parseSeq(open, close, kind string) (node, error) { + p.i++ // consume open + seq := &seqNode{kind: kind} + p.skipSpace() + if p.i < len(p.src) && p.src[p.i] == close[0] { + p.i++ + return seq, nil + } + for { + elt, err := p.parseExpression() + if err != nil { + return nil, err + } + seq.elts = append(seq.elts, elt) + p.skipSpace() + if p.i >= len(p.src) { + return nil, p.errf("unclosed %q", open) + } + if p.src[p.i] == close[0] { + p.i++ + return seq, nil + } + if p.src[p.i] != ',' { + return nil, p.errf("expected ',' or %q", close) + } + p.i++ + } +} + +func (p *parser) parseString() (node, error) { + quote := p.src[p.i] + p.i++ + var b strings.Builder + for p.i < len(p.src) && p.src[p.i] != quote { + if p.src[p.i] == '\\' && p.i+1 < len(p.src) { + b.WriteByte(p.src[p.i+1]) + p.i += 2 + continue + } + b.WriteByte(p.src[p.i]) + p.i++ + } + if p.i >= len(p.src) { + return nil, p.errf("unterminated string") + } + p.i++ // consume closing quote + return &constNode{kind: "str", str: b.String()}, nil +} + +func (p *parser) parseNumber() (node, error) { + start := p.i + for p.i < len(p.src) && (p.src[p.i] >= '0' && p.src[p.i] <= '9') { + p.i++ + } + isFloat := false + if p.i < len(p.src) && p.src[p.i] == '.' && p.i+1 < len(p.src) && + p.src[p.i+1] >= '0' && p.src[p.i+1] <= '9' { + isFloat = true + p.i++ + for p.i < len(p.src) && p.src[p.i] >= '0' && p.src[p.i] <= '9' { + p.i++ + } + } + lit := p.src[start:p.i] + if isFloat { + v, err := strconv.ParseFloat(lit, 64) + if err != nil { + return nil, p.errf("bad float %q", lit) + } + return &constNode{kind: "float", num: v}, nil + } + v, err := strconv.ParseFloat(lit, 64) + if err != nil { + return nil, p.errf("bad int %q", lit) + } + return &constNode{kind: "int", num: v}, nil +} + +func (p *parser) parseNameOrCall() (node, error) { + start := p.i + for p.i < len(p.src) && isIdentChar(p.src[p.i]) { + p.i++ + } + name := p.src[start:p.i] + switch name { + case "True": + return &constNode{kind: "bool", str: "true"}, nil + case "False": + return &constNode{kind: "bool", str: "false"}, nil + case "None": + return nil, p.errf("None is not allowed") + } + p.skipSpace() + if p.i < len(p.src) && p.src[p.i] == '(' { + p.i++ + call := &callNode{fn: name} + p.skipSpace() + if p.i < len(p.src) && p.src[p.i] == ')' { + p.i++ + return call, nil + } + for { + arg, err := p.parseExpression() + if err != nil { + return nil, err + } + call.args = append(call.args, arg) + p.skipSpace() + if p.i >= len(p.src) { + return nil, p.errf("unclosed '('") + } + if p.src[p.i] == ')' { + p.i++ + return call, nil + } + if p.src[p.i] != ',' { + return nil, p.errf("expected ',' or ')'") + } + p.i++ + } + } + return &nameNode{name: name}, nil +} + +func (p *parser) matchWord(word string) bool { + p.skipSpace() + if !strings.HasPrefix(p.src[p.i:], word) { + return false + } + end := p.i + len(word) + if end < len(p.src) && isIdentChar(p.src[end]) { + return false + } + p.i = end + return true +} + +func isIdentStart(c byte) bool { + return c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') +} + +func isIdentChar(c byte) bool { + return isIdentStart(c) || (c >= '0' && c <= '9') +} + +// --------------------------------------------------------------------------- +// Whitelist check — runs BEFORE evaluation +// --------------------------------------------------------------------------- + +// computeFunctions mirrors Python _COMPUTE_FUNCTIONS. +var computeFunctions = map[string]bool{ + "abs": true, "round": true, "min": true, "max": true, "sum": true, + "len": true, "int": true, "float": true, "sorted": true, + "letters": true, "digit_sum": true, "date_diff": true, +} + +// computeAlwaysNumeric mirrors Python _COMPUTE_ALWAYS_NUMERIC: functions whose +// result is a number whatever they are handed. `min`/`max`/`sum` are absent on +// purpose — min("b","a") is a string — and `sorted` returns a list, so neither +// may stand where a number is required. +var computeAlwaysNumeric = map[string]bool{ + "abs": true, "round": true, "int": true, "float": true, "len": true, + "letters": true, "digit_sum": true, "date_diff": true, +} + +// checkExpression mirrors Python _check_expression: reject anything outside the +// arithmetic whitelist. Returns "" when clean. +func checkExpression(n node) string { + switch t := n.(type) { + case *constNode: + return "" + case *nameNode: + if !computeFunctions[t.name] { + return fmt.Sprintf("unknown name %q", t.name) + } + return "" + case *unaryNode: + return checkExpression(t.operand) + case *binaryNode: + if problem := checkExpression(t.left); problem != "" { + return problem + } + if problem := checkExpression(t.right); problem != "" { + return problem + } + // Multiplication and exponentiation can turn a short expression into an + // arbitrarily large object ("a" * 10**9, [1] * 10**9), so both operands + // must be provably numeric. + if t.op == "*" || t.op == "**" { + if !isNumeric(t.left) || !isNumeric(t.right) { + if t.op == "*" { + return "multiplication is only allowed on numbers" + } + return "exponentiation is only allowed on numbers" + } + if t.op == "**" { + if c, ok := t.right.(*constNode); ok && + (c.kind == "int" || c.kind == "float") && math.Abs(c.num) > maxPowExponent { + return "exponent is too large" + } + } + } + return "" + case *chainNode: + for _, sub := range t.operands { + if problem := checkExpression(sub); problem != "" { + return problem + } + } + return "" + case *ifExpNode: + for _, sub := range []node{t.cond, t.body, t.orelse} { + if problem := checkExpression(sub); problem != "" { + return problem + } + } + return "" + case *seqNode: + for _, elt := range t.elts { + if problem := checkExpression(elt); problem != "" { + return problem + } + } + return "" + case *callNode: + if !computeFunctions[t.fn] { + return "only the listed functions may be called" + } + // len("Ada Lovelace") is 12 and the answer is 11 — the gap is silent, so + // the expression is refused rather than counted. + if t.fn == "len" && len(t.args) == 1 { + if c, ok := t.args[0].(*constNode); ok && c.kind == "str" { + return "len() on a string literal is ambiguous; use letters()" + } + } + for _, arg := range t.args { + if c, ok := arg.(*constNode); ok && c.kind == "str" && len(c.str) > maxStringLiteral { + return "string literal is too long" + } + if problem := checkExpression(arg); problem != "" { + return problem + } + } + return "" + } + return "unsupported expression" +} + +// isNumeric mirrors Python _is_numeric: true when the node can ONLY evaluate to +// a number. +func isNumeric(n node) bool { + switch t := n.(type) { + case *constNode: + return t.kind == "int" || t.kind == "float" || t.kind == "bool" + case *unaryNode: + return isNumeric(t.operand) + case *binaryNode: + switch t.op { + case "+", "-", "*", "/", "//", "%", "**": + return isNumeric(t.left) && isNumeric(t.right) + case "==", "!=", "<", "<=", ">", ">=", "and", "or": + return true // a comparison is a bool, and a bool is an int + } + return false + case *chainNode: + return true // Python _is_numeric: a comparison is a bool, and a bool is an int + case *ifExpNode: + return isNumeric(t.body) && isNumeric(t.orelse) + case *callNode: + if computeAlwaysNumeric[t.fn] { + return true + } + if t.fn == "sum" || t.fn == "min" || t.fn == "max" { + for _, arg := range t.args { + if !(isNumeric(arg) || isNumericSequence(arg)) { + return false + } + } + return true + } + return false + } + return false +} + +// isNumericSequence mirrors Python _is_numeric_sequence: a literal sequence whose +// every element is provably numeric. +func isNumericSequence(n node) bool { + seq, ok := n.(*seqNode) + if !ok { + return false + } + for _, elt := range seq.elts { + if !isNumeric(elt) { + return false + } + } + return true +} + +// --------------------------------------------------------------------------- +// Evaluation — no builtins, no reflection +// --------------------------------------------------------------------------- + +// evalSafe evaluates n, converting a panic into an error. +// +// The helper functions (letters / digit_sum) reject bad argument types by +// panicking, mirroring Python's TypeError. Python catches those at the top of +// `compute` (`except Exception`); without a recover here the same input would +// crash the whole request instead of being a normal, logged refusal. +func evalSafe(n node) (value any, err error) { + defer func() { + if r := recover(); r != nil { + value = nil + err = fmt.Errorf("%v", r) + } + }() + return evalNode(n) +} + +func evalNode(n node) (any, error) { + switch t := n.(type) { + case *constNode: + switch t.kind { + case "int": + return int64(t.num), nil + case "float": + return t.num, nil + case "bool": + return t.str == "true", nil + case "str": + return t.str, nil + } + case *nameNode: + return nil, fmt.Errorf("bare name %q is not a value", t.name) + case *unaryNode: + v, err := evalNode(t.operand) + if err != nil { + return nil, err + } + switch t.op { + case "-": + f, err := asNumber(v) + if err != nil { + return nil, err + } + if i, ok := v.(int64); ok { + return -i, nil + } + return -f, nil + case "+": + f, err := asNumber(v) + if err != nil { + return nil, err + } + if i, ok := v.(int64); ok { + return i, nil + } + return f, nil + case "not": + return !truthy(v), nil + } + case *ifExpNode: + cond, err := evalNode(t.cond) + if err != nil { + return nil, err + } + if truthy(cond) { + return evalNode(t.body) + } + return evalNode(t.orelse) + case *seqNode: + out := make([]any, 0, len(t.elts)) + for _, elt := range t.elts { + v, err := evalNode(elt) + if err != nil { + return nil, err + } + out = append(out, v) + } + if t.kind == "set" { + // Python set literals deduplicate members: len({1,1,2}) == 2. + // Without this, len/min/max/sorted on a set literal would count + // duplicates, diverging from Python. + out = dedupSequence(out) + } + return out, nil + case *binaryNode: + return evalBinary(t) + case *chainNode: + return evalChain(t) + case *callNode: + return evalCall(t) + } + return nil, fmt.Errorf("unsupported node") +} + +// evalChain evaluates a comparison chain the way Python's ast.Compare does: +// each comparison is applied to ADJACENT operands, results are combined with +// `and`, and each operand is evaluated exactly once. It short-circuits on the +// first false comparison. +func evalChain(t *chainNode) (any, error) { + left, err := evalNode(t.operands[0]) + if err != nil { + return nil, err + } + for i, op := range t.ops { + right, err := evalNode(t.operands[i+1]) + if err != nil { + return nil, err + } + ok, err := compareValues(op, left, right) + if err != nil { + return nil, err + } + if !ok { + return false, nil + } + // The next comparison starts from this operand, not from `true`. + left = right + } + return true, nil +} + +func evalBinary(t *binaryNode) (any, error) { + // `and` / `or` short-circuit, as in Python. + if t.op == "and" || t.op == "or" { + left, err := evalNode(t.left) + if err != nil { + return nil, err + } + if t.op == "and" && !truthy(left) { + return left, nil + } + if t.op == "or" && truthy(left) { + return left, nil + } + return evalNode(t.right) + } + left, err := evalNode(t.left) + if err != nil { + return nil, err + } + right, err := evalNode(t.right) + if err != nil { + return nil, err + } + switch t.op { + case "+": + // Numeric addition, or sequence concatenation (both bounded by literal + // length, so no amplification risk). + if li, ok := left.(int64); ok { + if ri, ok := right.(int64); ok { + return li + ri, nil + } + } + lf, err1 := asNumber(left) + rf, err2 := asNumber(right) + if err1 == nil && err2 == nil { + return lf + rf, nil + } + return concatSequences(left, right) + case "-", "*", "/", "//", "%", "**": + lf, err1 := asNumber(left) + if err1 != nil { + return nil, err1 + } + rf, err2 := asNumber(right) + if err2 != nil { + return nil, err2 + } + switch t.op { + case "-": + if li, ok := left.(int64); ok { + if ri, ok := right.(int64); ok { + return li - ri, nil + } + } + return lf - rf, nil + case "*": + if li, ok := left.(int64); ok { + if ri, ok := right.(int64); ok { + return li * ri, nil + } + } + return lf * rf, nil + case "/": + if rf == 0 { + return nil, fmt.Errorf("division by zero") + } + return lf / rf, nil + case "//": + if rf == 0 { + return nil, fmt.Errorf("floor division by zero") + } + return math.Floor(lf / rf), nil + case "%": + if rf == 0 { + return nil, fmt.Errorf("modulo by zero") + } + // Python's % returns a value with the SIGN OF THE DIVISOR + // (a - (b * floor(a / b))): -3 % 2 == 1, 3 % -2 == -1. + // math.Mod returns a value with the sign of the dividend + // (math.Mod(-3, 2) == -1), so adjust when signs disagree. + r := math.Mod(lf, rf) + if r != 0 && (r < 0) != (rf < 0) { + r += rf + } + return r, nil + case "**": + return math.Pow(lf, rf), nil + } + case "==", "!=", "<", "<=", ">", ">=": + return compareValues(t.op, left, right) + } + return nil, fmt.Errorf("unsupported operator %q", t.op) +} + +func evalCall(t *callNode) (any, error) { + args := make([]any, 0, len(t.args)) + for _, arg := range t.args { + v, err := evalNode(arg) + if err != nil { + return nil, err + } + args = append(args, v) + } + switch t.fn { + case "abs": + f, err := asNumber(single(args)) + if err != nil { + return nil, err + } + if v, ok := single(args).(int64); ok && v < 0 { + return -v, nil + } + return math.Abs(f), nil + case "round": + f, err := asNumber(single(args)) + if err != nil { + return nil, err + } + if len(args) > 1 { + nd, err := asNumber(args[1]) + if err != nil { + return nil, err + } + scale := math.Pow(10, nd) + return math.RoundToEven(f*scale) / scale, nil + } + // Python's builtin round() is round-half-to-even (banker's rounding): + // round(2.5) == 2, round(3.5) == 4. math.Round rounds half away from + // zero (round(2.5) == 3), so RoundToEven mirrors Python. + return math.RoundToEven(f), nil + case "int": + // Python's int() accepts a number (truncating toward zero) or a + // whole-number string; int("1.5") is a ValueError, so reject decimals. + v := single(args) + switch n := v.(type) { + case int64, float64, bool: + f, err := asNumber(v) + if err != nil { + return nil, err + } + return int64(f), nil + case string: + i, err := strconv.ParseInt(strings.TrimSpace(n), 10, 64) + if err != nil { + return nil, fmt.Errorf("int(%q) is not a whole number", n) + } + return i, nil + default: + return nil, fmt.Errorf("int() expects a number or numeric string, got %T", v) + } + case "float": + // Python's float() accepts a number or any numeric string. + v := single(args) + switch n := v.(type) { + case int64, float64, bool: + f, err := asNumber(v) + if err != nil { + return nil, err + } + return f, nil + case string: + f, err := strconv.ParseFloat(strings.TrimSpace(n), 64) + if err != nil { + return nil, fmt.Errorf("float(%q) is not a number", n) + } + return f, nil + default: + return nil, fmt.Errorf("float() expects a number or numeric string, got %T", v) + } + case "len": + return int64(sequenceLen(single(args))), nil + case "min", "max": + flat := flattenArgs(args) + if len(flat) == 0 { + return nil, fmt.Errorf("%s() needs at least one argument", t.fn) + } + return extrema(t.fn, flat) + case "sum": + flat := flattenArgs(args) + total := 0.0 + allInt := true + for _, v := range flat { + f, err := asNumber(v) + if err != nil { + return nil, err + } + if _, ok := v.(int64); !ok { + allInt = false + } + total += f + } + if allInt { + return int64(total), nil + } + return total, nil + case "sorted": + return sortValues(flattenArgs(args)) + case "letters": + return int64(letters(flattenArgs(args))), nil + case "digit_sum": + return int64(digitSum(flattenArgs(args))), nil + case "date_diff": + if len(args) != 2 { + return nil, fmt.Errorf("date_diff() takes exactly two ISO dates") + } + return dateDiff(args[0], args[1]) + } + return nil, fmt.Errorf("unknown function %q", t.fn) +} + +func single(args []any) any { + if len(args) == 0 { + return nil + } + return args[0] +} + +// flattenArgs mirrors Python's "any number of args, or a single list of them". +func flattenArgs(args []any) []any { + if len(args) == 1 { + if list, ok := args[0].([]any); ok { + return list + } + } + return args +} + +func asNumber(v any) (float64, error) { + switch n := v.(type) { + case int64: + return float64(n), nil + case float64: + return n, nil + case bool: + if n { + return 1, nil + } + return 0, nil + } + return 0, fmt.Errorf("%v is not a number", v) +} + +func truthy(v any) bool { + switch n := v.(type) { + case bool: + return n + case int64: + return n != 0 + case float64: + return n != 0 + case string: + return n != "" + case []any: + return len(n) > 0 + case nil: + return false + } + return true +} + +func sequenceLen(v any) int { + if list, ok := v.([]any); ok { + return len(list) + } + if s, ok := v.(string); ok { + return len([]rune(s)) + } + return 0 +} + +// dedupSequence mirrors Python set semantics for {a, b, c} literals: repeated +// members collapse to one. The key is a stable, panic-free rendering so +// unhashable elements (nested lists) never crash the evaluator; numeric +// int64/float64 compare by value, so {1, 1.0} dedups to one element, matching +// Python. +func dedupSequence(in []any) []any { + seen := make(map[string]bool, len(in)) + out := make([]any, 0, len(in)) + for _, v := range in { + key := fmt.Sprintf("%#v", v) + if !seen[key] { + seen[key] = true + out = append(out, v) + } + } + return out +} + +func concatSequences(a, b any) (any, error) { + la, aOk := a.([]any) + lb, bOk := b.([]any) + if aOk && bOk { + return append(append([]any{}, la...), lb...), nil + } + sa, aStr := a.(string) + sb, bStr := b.(string) + if aStr && bStr { + return sa + sb, nil + } + return nil, fmt.Errorf("unsupported operand types for +") +} + +func compareValues(op string, a, b any) (bool, error) { + if af, err := asNumber(a); err == nil { + if bf, err := asNumber(b); err == nil { + switch op { + case "==": + return af == bf, nil + case "!=": + return af != bf, nil + case "<": + return af < bf, nil + case "<=": + return af <= bf, nil + case ">": + return af > bf, nil + case ">=": + return af >= bf, nil + } + } + } + as, aStr := a.(string) + bs, bStr := b.(string) + if aStr && bStr { + switch op { + case "==": + return as == bs, nil + case "!=": + return as != bs, nil + case "<": + return as < bs, nil + case "<=": + return as <= bs, nil + case ">": + return as > bs, nil + case ">=": + return as >= bs, nil + } + } + return false, fmt.Errorf("unsupported comparison") +} + +func extrema(op string, values []any) (any, error) { + // Mirrors Python min()/max(): elements are ordered with the same comparison + // semantics as the rest of the evaluator (compareValues), so strings compare + // lexicographically and the result keeps its original type. The final numeric + // gate then rejects a non-numeric result, exactly as Python's + // isinstance(value, (int, float)) check does. + best := values[0] + for _, v := range values[1:] { + // Keep v when it is the smaller (min) or larger (max) element. + smaller, err := compareValues("<", v, best) + if err != nil { + return nil, err + } + if (op == "min" && smaller) || (op == "max" && !smaller) { + best = v + } + } + return best, nil +} + +func sortValues(values []any) ([]any, error) { + // Mirrors Python sorted(): order elements with the evaluator's comparison + // semantics (compareValues), so strings sort lexicographically. The result is + // a list, which the final numeric gate rejects — exactly as Python's + // isinstance(value, (int, float)) check refuses a list result. + out := append([]any{}, values...) + for i := 1; i < len(out); i++ { + for j := i; j > 0; { + lt, err := compareValues("<", out[j-1], out[j]) + if err != nil { + return nil, err + } + if !lt { + break + } + out[j-1], out[j] = out[j], out[j-1] + j-- + } + } + return out, nil +} + +// letters mirrors Python _letters: count alphabetic characters across the given +// names. Spaces, hyphens, apostrophes, digits and punctuation do NOT count; +// letters carrying diacritics DO ("José" is 4). +// +// "How many letters are in these names" is a real question, and every plain way +// to answer it needs machinery this evaluator refuses — an attribute call or a +// comprehension — so it is a function instead. +func letters(items []any) int { + total := 0 + for _, item := range items { + s, ok := item.(string) + if !ok { + panic(fmt.Sprintf("letters() takes names, not %T", item)) + } + for _, ch := range s { + if unicode.IsLetter(ch) { + total++ + } + } + } + return total +} + +// digitSum mirrors Python _digit_sum: add up the decimal digits inside the +// given values. Every digit is added SEPARATELY: digit_sum("L7 7BN") is 14 and +// digit_sum("2020") is 4. Only ASCII digits count. +func digitSum(items []any) int { + total := 0 + for _, item := range items { + switch n := item.(type) { + case bool: + panic("digit_sum() takes text or whole numbers, not bool") + case string: + for i := 0; i < len(n); i++ { + if n[i] >= '0' && n[i] <= '9' { + total += int(n[i] - '0') + } + } + case int64: + for _, ch := range strconv.FormatInt(n, 10) { + total += int(ch - '0') + } + default: + panic(fmt.Sprintf("digit_sum() takes text or whole numbers, not %T", item)) + } + } + return total +} + +// dateDiff mirrors Python _date_diff: days between two ISO dates (inclusive of +// the earlier, exclusive of the later — a calendar span). +func dateDiff(a, b any) (int64, error) { + as, okA := a.(string) + bs, okB := b.(string) + if !okA || !okB { + return 0, fmt.Errorf("date_diff() takes ISO date strings") + } + da, err := parseISODate(as) + if err != nil { + return 0, err + } + db, err := parseISODate(bs) + if err != nil { + return 0, err + } + days := db.Sub(da).Hours() / 24 + if days < 0 { + days = -days + } + return int64(days), nil +} + +func parseISODate(s string) (time.Time, error) { + parts := strings.Split(strings.TrimSpace(s), "-") + if len(parts) != 3 { + return time.Time{}, fmt.Errorf("not an ISO date: %q", s) + } + y, err1 := strconv.Atoi(parts[0]) + mo, err2 := strconv.Atoi(parts[1]) + d, err3 := strconv.Atoi(parts[2]) + if err1 != nil || err2 != nil || err3 != nil { + return time.Time{}, fmt.Errorf("not an ISO date: %q", s) + } + if mo < 1 || mo > 12 { + return time.Time{}, fmt.Errorf("month %d out of range in %q", mo, s) + } + t := time.Date(y, time.Month(mo), d, 0, 0, 0, 0, time.UTC) + // time.Date silently normalizes out-of-range days (Feb 30 -> Mar 1, month 13 + // -> next Jan). Python date() raises ValueError, so reject any date that does + // not survive the round trip unchanged. + if t.Year() != y || int(t.Month()) != mo || t.Day() != d { + return time.Time{}, fmt.Errorf("day %d out of range for %q", d, s) + } + return t, nil +} + +// --------------------------------------------------------------------------- +// ComputeFromFacts: decide whether the question asks for a derivable number and, +// if so, compute it. Mirrors Python arithmetic.compute_from_facts (line 356) and +// the _COMPUTE_SYSTEM prompt (line 267). The evaluator side of this lives above +// (Compute / the parser); the two together form the Go port of arithmetic.py. +// --------------------------------------------------------------------------- + +// ComputeSystem mirrors arithmetic.py::_COMPUTE_SYSTEM verbatim in intent. It is +// inlined (rather than loaded from rag/prompts) because the Go harness has no +// Jinja env and the template carries no variables. +// +// IMPORTANT: the prompt asks for a PYTHON expression, and the parser in +// arithmetic.go implements exactly the Python subset the prompt promises +// (`**`, `x if y else z`, list literals, the listed functions). Changing one +// without the other will silently refuse every model-written expression. +const ComputeSystem = `You are given the ORIGINAL question and every fact discovered so far. Decide whether that question asks for a NUMBER that NO fact states outright but that FOLLOWS ARITHMETICALLY from figures the facts DO state — a sum, a difference, a count, an average, a percentage, a unit conversion, an elapsed span. + +If it does, compute it by writing ONE Python expression with every figure substituted as a literal. The expression is evaluated on its own: no variables, no assignments, no imports, no attributes, no subscripts. The only functions available are abs, round, min, max, sum, len, int, float, sorted, letters, digit_sum and date_diff. + combined population of three -> 12345 + 6789 + 101112 + how many of the listed items -> len(["Alpha", "Beta", "Gamma"]) + what percentage one figure is -> 100 * 4523 / 18092 + years between two dates -> 1998 - 1954 + days between two dates -> date_diff("1941-07-28", "1959-07-17") + letters in a set of names -> letters("Ada Lovelace", "Alan Turing") + digits of a postcode added up -> digit_sum("L7 7BN") + +ADDING UP THE DIGITS of a postcode, a house number, a serial number, a year or an address: use digit_sum(...), and never read the digits out by hand. It adds each digit separately, which is what such a question means — digit_sum("L7 7BN") is 7+7 = 14, digit_sum("2020") is 2+0+2+0 = 4. Pass the identifier EXACTLY as the facts write it, letters and spaces included; they are ignored. It is the WRONG tool for whole numbers the facts state separately — two populations, two prices, two years are added as plain literals (12345 + 6789), not fed to digit_sum. + +COUNTING LETTERS: use letters(...), NEVER len(...) on a name. len counts spaces, hyphens and apostrophes as though they were letters, so it is wrong by exactly the amount nobody notices (len("Ada Lovelace") is 12; the name has 11 letters). letters(...) takes any number of names, or one list of them, and counts alphabetic characters only. Spell each name EXACTLY as the facts give it, including any middle name or accent — and if the facts do not show a name in full, that figure is missing, so return "needed": false rather than counting a partial name. + +DAYS BETWEEN TWO DATES: when the question asks "how many days after X did Y happen" / "how many days between two dates", use date_diff("YYYY-MM-DD", "YYYY-MM-DD") with the two dates EXACTLY as the facts write them. Do NOT subtract the years (1959 - 1941) — that is the wrong quantity for a days question (18 is years, not days). If either date is not a full YYYY-MM-DD in the facts, the figure is missing, so return "needed": false rather than approximating. + +AGE (an age, or an age difference, at some event): the facts almost always give a birth YEAR and an event YEAR; the age is event_year - birth_year (or birth_year - event_year, taken as the positive difference). You do NOT need the birth month or day — the year is enough. If the facts give FULL dates (YYYY-MM-DD), prefer date_diff(...) which handles the day correctly; otherwise subtract the years. Example: "elected in 2010, born 1971" -> 2010 - 1971. If the event year is BEFORE the birth year, the difference is birth_year - event_year (use abs(...)). Never refuse because the birthday is not a full date — the YEAR is sufficient. + +PERCENTAGE (what percent / what share / what proportion / what fraction): 100 * part / whole, where part and whole are the exact figures from the facts. Example: + "2.7 million Tamazight speakers out of 556 million total" -> 100 * 2.7 / 556 +Do not round to an integer unless the question asks for that; keep the source figures exact. + +UNIT CONVERSION (a speed, rate, or span in mixed units): convert inside the expression. A speed in km/h becomes m/s by dividing by 3.6. Example for a difference in m/s between a fish and a swimmer: + fish_kmh / 3.6 - 50 / swimmer_seconds -> e.g. 132 / 3.6 - 50 / 21.07 +Use the EXACT figures the facts state (do not round 21.07 to 21); if the facts give the speed already in m/s, use it directly without dividing. + +MULTIPLICATION (a rate times a count, e.g. dollars per day times days): multiply the RATE by the COUNT exactly as the facts state them. Read the rate's NUMBER from the facts. Example: "a suggested donation of $25 per day, kept up for 49 days" -> 25 * 49. If the facts state the rate as 1 but the question calls it "a suggested donation", still use the exact figure the facts give — never substitute a made-up base amount. + +Prefer computing over giving up: when the question asks for a derivable number and the facts provide the figures (even if in different units or spread across several facts), WRITE the expression and compute it. In particular, questions asking for an AGE DIFFERENCE, a PERCENTAGE, a SPEED DIFFERENCE (with unit conversion), or a MULTIPLICATION (a rate times a count) are exactly what this tool is for. + +Return "needed": false, with an empty expression, ONLY when: +- the ORIGINAL question does not ask for a number; +- a fact already states that number outright — a value you would only be restating is not a calculation; +- a figure the calculation needs is genuinely absent from the facts, or a list the count depends on is not shown to be complete. NEVER invent, estimate, recall or infer a figure. When input is missing, say so and return "needed": false — a wrong number is worse than none — but first check that the figure really is absent (e.g. the age's birth YEAR is enough; you do not need the month). + +"label" names what the number IS, as a short noun phrase ("combined population of the three counties"), so a later step can use the result without re-deriving it. +"uses" lists the INDEX NUMBERS of the facts whose figures you substituted. +Output ONLY JSON, no prose, no code fences: +{"needed": true/false, "expression": "", "label": "", "uses": [, ...]}` + +// ComputedFact mirrors Python compute_from_facts' return dict. +type ComputedFact struct { + Needed bool + Label string + Value string + Expression string + Uses []int +} + +// ComputeFromFacts asks the model whether `question` asks for a derivable +// number and, if so, writes + safely evaluates the expression over `facts`. +// +// Returns nil when no derivation is needed or possible — including when the +// model's expression is refused by the whitelist. A refusal is logged, never +// propagated: the caller simply carries on without the computed evidence. +func ComputeFromFacts(ctx context.Context, model SessionModel, question string, facts []string, fitBudget int) *ComputedFact { + if model == nil || strings.TrimSpace(question) == "" || len(facts) == 0 { + return nil + } + ctx, done := Phase(ctx, PhaseCompute) + defer done() + + user := fmt.Sprintf("Facts discovered so far:\n%s\n\nOriginal question:\n%s\n\nOutput JSON:", + renderFacts(facts), question) + + // Mirror Python compute_from_facts: budget = fit_budget or llm.max_length, + // then message_fit_in(form_message(system, user), budget). The chat seam now + // exposes llm.max_length via ContextLengthModel; when neither an explicit + // fitBudget nor a model context window is available the 8192 default (chat + // EffectiveContextLength) applies, exactly as Python's LLM.max_length + // defaults when the model config omits max_tokens. + budget := fitBudget + if budget <= 0 { + if cl, ok := model.(ContextLengthModel); ok { + budget = cl.ContextLength() + } + if budget <= 0 { + budget = chat.EffectiveContextLength(0) + } + } + fitted, fitErr := chat.FitMessages(ComputeSystem, []schema.Message{ + *schema.UserMessage(user), + }, budget) + if fitErr != "" { + _LOG.Printf("[Compute] prompt fitting failed: %s", fitErr) + return nil + } + // FitMessages may prepend/trim a system message; re-extract it so the model + // call is exactly [system, user...] as Python sends msg[0] then msg[1:]. + systemPrompt := ComputeSystem + history := fitted + if len(fitted) > 0 && fitted[0].Role == schema.System { + systemPrompt = fitted[0].Content + history = fitted[1:] + } + msgs := make([]schema.Message, 0, 1+len(history)) + msgs = append(msgs, *schema.SystemMessage(systemPrompt)) + msgs = append(msgs, history...) + // Python hardcodes {"temperature": 0.0} for this node — a mechanical rewrite, + // so it must be deterministic. When the model supports per-call temperature we + // pass 0.0 exactly; otherwise we fall back to the plain Complete (it then runs + // at the model's default), the same documented seam as ExtractWeightedKeywords + // (which uses 0.1). + var reply *ModelReply + var err error + if tm, ok := model.(TemperatureModel); ok { + reply, err = tm.CompleteWithTemperature(ctx, msgs, nil, 0.0) + } else { + reply, err = model.Complete(ctx, msgs, nil) + } + if err != nil { + _LOG.Printf("[Compute] LLM call failed: %v", err) + return nil + } + data, _ := ExtractJSON(StripThinkAndFences(reply.Content)).(map[string]any) + if data == nil { + _LOG.Printf("[Compute] could not parse LLM JSON") + return nil + } + // Python evaluates `not data.get("needed")`, i.e. builtin bool(): a truthy + // non-bool (1, "true", a non-empty list) counts as needed. A strict bool + // assertion would reject those and wrongly report "nothing derivable". + if !truthy(data["needed"]) { + return nil + } + expression := "" + if v, ok := data["expression"].(string); ok { + expression = strings.TrimSpace(v) + } + if expression == "" { + return nil + } + label := "" + if v, ok := data["label"].(string); ok { + label = strings.TrimSpace(v) + } + if label == "" { + label = "Value calculated from the facts found" + } + uses := make([]int, 0, 4) + if raw, ok := data["uses"].([]any); ok { + for _, n := range raw { + if v, ok := toIntStrict(n); ok { + uses = append(uses, v) + } + } + } + + value, problem := Compute(expression) + if problem != "" { + _LOG.Printf("[Compute] refused %q — %s", trunc(expression, 120), problem) + return nil + } + return &ComputedFact{ + Needed: true, + Label: label, + Value: value, + Expression: expression, + Uses: uses, + } +} + +// renderFacts mirrors Python _render_facts: one fact per line, prefixed with its +// index — the index is what "uses" refers back to. +func renderFacts(facts []string) string { + lines := make([]string, 0, len(facts)) + for i, f := range facts { + lines = append(lines, fmt.Sprintf("[%d] %s", i, f)) + } + return strings.Join(lines, "\n") +} diff --git a/internal/rag/advanced_rag/harness/arithmetic_test.go b/internal/rag/advanced_rag/harness/arithmetic_test.go new file mode 100644 index 00000000000..81a98bc30e8 --- /dev/null +++ b/internal/rag/advanced_rag/harness/arithmetic_test.go @@ -0,0 +1,565 @@ +// +// 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. +// + +package harness + +import ( + "context" + "strings" + "testing" + + "github.com/cloudwego/eino/schema" +) + +// --------------------------------------------------------------------------- +// The happy path: what the prompt promises the model +// --------------------------------------------------------------------------- + +func TestComputeBasicArithmetic(t *testing.T) { + cases := []struct{ expr, want string }{ + {"12345 + 6789 + 101112", "120246"}, // combined population + {"1998 - 1954", "44"}, // years between + {"100 * 4523 / 18092", "25"}, // percentage + {"25 * 49", "1225"}, // rate x count + {"(132 / 3.6) * 1", "36.666667"}, // unit conversion (float rendering) + {"2 ** 10", "1024"}, // exponent + {"7 // 2", "3"}, // floor division + {"7 % 3", "1"}, // modulo + {"abs(1954 - 1998)", "44"}, // abs + {"round(3.14159, 2)", "3.14"}, // round with digits + {"round(2.5)", "2"}, // Python banker's rounding (half-to-even) + {"round(3.5)", "4"}, // half-to-even, away from even + {"round(0.5)", "0"}, // half-to-even + {"-3 % 2", "1"}, // Python %: sign of the divisor + {"3 % -2", "-1"}, // sign of the divisor + {"min(3, 1, 2)", "1"}, + {"max(3, 1, 2)", "3"}, + {"sum([1, 2, 3, 4])", "10"}, + {"len([\"Alpha\", \"Beta\", \"Gamma\"])", "3"}, + {"0.1 + 0.2", "0.3"}, // float noise suppressed + {"(2 + 3) * 4", "20"}, // grouping + {"2 ** 3 ** 2", "512"}, // right-associative + {"-2 ** 2", "-4"}, // Python precedence + {"1 if 2 > 1 else 0", "1"}, // ternary + } + for _, c := range cases { + got, err := Compute(c.expr) + if err != "" { + t.Errorf("Compute(%q) refused: %s", c.expr, err) + continue + } + if got != c.want { + t.Errorf("Compute(%q) = %q, want %q", c.expr, got, c.want) + } + } +} + +func TestComputeHelperFunctions(t *testing.T) { + cases := []struct{ expr, want string }{ + {`letters("Ada Lovelace")`, "11"}, // 12 with len — the whole point + {`letters("Ada Lovelace", "Alan Turing")`, "21"}, // multiple names + {`letters(["José"])`, "4"}, // diacritics count + {`digit_sum("L7 7BN")`, "14"}, // 7 + 7 + {`digit_sum("2020")`, "4"}, // each digit separately + {`date_diff("1941-07-28", "1959-07-17")`, "6563"}, // calendar span (Python docstring: Q317 = 6563) + {`date_diff("1959-07-17", "1941-07-28")`, "6563"}, // order-independent + {`sorted([3, 1, 2])[0]`, ""}, // subscripts refused (see below) + } + for _, c := range cases { + got, err := Compute(c.expr) + if c.want == "" { + continue // asserted separately in the refusal tests + } + if err != "" { + t.Errorf("Compute(%q) refused: %s", c.expr, err) + continue + } + if got != c.want { + t.Errorf("Compute(%q) = %q, want %q", c.expr, got, c.want) + } + } +} + +// --------------------------------------------------------------------------- +// Security: the AST whitelist +// --------------------------------------------------------------------------- + +func TestComputeRefusesUnsafeExpressions(t *testing.T) { + cases := []struct{ expr, wantSubstr string }{ + // Attribute access — the classic sandbox escape. + {`"".__class__`, ""}, + {`(1).__class__`, ""}, + // Subscripts / indexing. + {"[1,2,3][0]", ""}, + // Comprehensions and lambdas. + {"[x for x in [1,2]]", ""}, + {"(lambda: 1)()", ""}, + // Names outside the whitelist. + {"__import__(\"os\").system(\"ls\")", ""}, + {"open(\"f\").read()", ""}, + {"eval(\"1\")", ""}, + {"exec(\"x\")", ""}, + // Assignment / statements. + {"x = 1", ""}, + {"import os", ""}, + {"1;2", ""}, + // String amplification via multiplication. + {`"a" * 100000000`, "multiplication is only allowed on numbers"}, + {"[1] * 100000000", "multiplication is only allowed on numbers"}, + // Exponentiation abuse. + {"2 ** 1000", "exponent is too large"}, + {`"a" ** 2`, "exponentiation is only allowed on numbers"}, + // len() on a string literal is ambiguous by design. + {`len("Ada Lovelace")`, "len() on a string literal is ambiguous"}, + // Keyword arguments are refused. + {"round(3.14159, ndigits=2)", "does not parse"}, + // None is not a value here. + {"None", "does not parse"}, + } + for _, c := range cases { + got, err := Compute(c.expr) + if err == "" { + t.Errorf("Compute(%q) = %q, want a refusal", c.expr, got) + continue + } + // The exact wording differs by rejection path (a parse failure vs. a + // whitelist refusal), but every case here MUST be refused. Assert the + // specific reason only where it is the point of the case. + if c.wantSubstr == "" { + continue + } + if !strings.Contains(err, c.wantSubstr) { + t.Errorf("Compute(%q) error = %q, want it to contain %q", c.expr, err, c.wantSubstr) + } + } +} + +// TestComputeRecoversFromHelperTypeErrors guards the panic→error conversion: +// letters()/digit_sum() reject bad argument types by panicking (mirroring +// Python's TypeError), and Compute must turn that into a normal refusal rather +// than crashing the request. +func TestComputeRecoversFromHelperTypeErrors(t *testing.T) { + for _, expr := range []string{`letters(123)`, `digit_sum(1.5)`} { + got, err := Compute(expr) + if err == "" { + t.Errorf("Compute(%q) = %q, want a refusal", expr, got) + } else if !strings.Contains(err, "failed to evaluate") { + t.Errorf("Compute(%q) err = %q, want an evaluation failure", expr, err) + } + } +} + +// no unsafe construct may ever produce a rendered value, whatever the wording. +func TestComputeRejectionsAreNeverValues(t *testing.T) { + unsafe := []string{ + `"".__class__`, `(1).__class__`, `[1,2,3][0]`, + `[x for x in [1,2]]`, `(lambda: 1)()`, + `__import__("os").system("ls")`, `open("f").read()`, + `eval("1")`, `exec("x")`, `globals()`, `getattr(1, "x")`, + `x = 1`, `import os`, `None`, `1;2`, + } + for _, expr := range unsafe { + got, err := Compute(expr) + if err == "" { + t.Errorf("SECURITY: Compute(%q) = %q — must be refused", expr, got) + } + } +} + +func TestComputeRefusesEmptyAndOversized(t *testing.T) { + if _, err := Compute(""); err != "empty expression" { + t.Errorf("empty: err = %q", err) + } + if _, err := Compute(" "); err != "empty expression" { + t.Errorf("blank: err = %q", err) + } + long := strings.Repeat("1+", computeMaxChars) + if _, err := Compute(long); !strings.Contains(err, "longer than") { + t.Errorf("oversized: err = %q", err) + } +} + +func TestComputeRefusesNonNumericResult(t *testing.T) { + // A call whose result is not a number must be refused, not rendered. + for _, expr := range []string{`sorted([3, 1, 2])`, `min("b", "a")`, `max("b", "a")`} { + if got, err := Compute(expr); err == "" { + t.Errorf("Compute(%q) = %q, want a refusal (result is not a number)", expr, got) + } + } +} + +// TestComputeBuiltinStringArgs pins Python's real builtin semantics: int()/float() +// accept numeric strings (mirroring the genuine Python builtins injected via +// _COMPUTE_FUNCTIONS), and min/max/sorted accept and order strings the same way +// Python does. The final result gate then rejects non-numeric results, matching +// Python's isinstance(value, (int, float)) check. +func TestComputeBuiltinStringArgs(t *testing.T) { + // int()/float() accept strings -> these produce a number and are ACCEPTED, + // exactly like Python (previously Go rejected them — a true divergence). + accept := []struct{ expr, want string }{ + {`int("12")`, "12"}, + {`int(" 12 ")`, "12"}, // Python strips surrounding whitespace + {`int(1.5)`, "1"}, // truncate toward zero + {`float("1.5")`, "1.5"}, + {`float(" 1e3 ")`, "1000"}, + } + for _, c := range accept { + if got, err := Compute(c.expr); err != "" || got != c.want { + t.Errorf("Compute(%q) = %q, err=%q; want %q", c.expr, got, err, c.want) + } + } + // These raise in Python (ValueError / TypeError) and must be refused. + for _, expr := range []string{`int("1.5")`, `float("abc")`, `int("0x10")`} { + if got, err := Compute(expr); err == "" { + t.Errorf("Compute(%q) = %q, want a refusal (Python raises)", expr, got) + } + } +} + +func TestComputeRefusesDivisionByZero(t *testing.T) { + for _, expr := range []string{"1 / 0", "1 // 0", "1 % 0"} { + if _, err := Compute(expr); err == "" || !strings.Contains(err, "zero") { + t.Errorf("Compute(%q) err = %q, want a division-by-zero refusal", expr, err) + } + } +} + +func TestComputeComparisonChains(t *testing.T) { + // Python's ast.Compare is an N-ary chain: `a < b < c` means + // (a < b) and (b < c), with each operand evaluated exactly once and + // short-circuiting on the first false comparison. A left-associative + // binary rewrite would instead compare the previous comparison's BOOLEAN + // result against the next operand, which is wrong. + // + // At the top level a comparison yields a bool, and compute() rejects + // non-numeric final results ("result is bool, not a number"), exactly as + // in Python. But a bool used numerically inside a call (int/abs/round…) + // must evaluate with the chained semantics. + rejected := []string{ + "3 > 2 > 1", "2 < 1 < 3", "1 < 2 < 3 < 4", "1 < 2 > 3", + "1 <= 1 <= 2", "3 == 3 == 3", "3 == 3 == 4", "5 > 4 > 3 > 2 > 1", "3 > 2", + } + for _, expr := range rejected { + if got, err := Compute(expr); err == "" { + t.Errorf("Compute(%q) = %q, want rejection (bool is not a number)", expr, got) + } + } + numeric := []struct { + expr string + want string + }{ + {"int(3 > 2 > 1)", "1"}, + {"int(2 < 1 < 3)", "0"}, + {"abs(1 < 2 < 3)", "1"}, + {"int(3 == 3 == 4)", "0"}, + {"round(3 > 2 > 1)", "1"}, + {"int(1 < 2 < 3 and 4 < 5)", "1"}, + } + for _, c := range numeric { + if got, err := Compute(c.expr); err != "" || got != c.want { + t.Errorf("Compute(%q) = %q, err=%q; want %q", c.expr, got, err, c.want) + } + } +} + +func TestComputeRejectsTrailingInput(t *testing.T) { + // Everything after the expression must be consumed, or `1 + 1; rm -rf` style + // smuggling would parse. + if _, err := Compute("1 + 1 2"); err == "" { + t.Error("trailing input must be refused") + } + if _, err := Compute("1 + 1)"); err == "" { + t.Error("unbalanced paren must be refused") + } +} + +// --------------------------------------------------------------------------- +// Formatting +// --------------------------------------------------------------------------- + +func TestFormatNumber(t *testing.T) { + cases := []struct { + in float64 + want string + }{ + {3.0, "3"}, + {0.1 + 0.2, "0.3"}, + {-2.5, "-2.5"}, + {0, "0"}, + {1e20, "100000000000000000000"}, + {3.14159265358979, "3.141593"}, + } + for _, c := range cases { + if got := formatNumber(c.in); got != c.want { + t.Errorf("formatNumber(%v) = %q, want %q", c.in, got, c.want) + } + } +} + +// --------------------------------------------------------------------------- +// The helper functions directly +// --------------------------------------------------------------------------- + +func TestLettersAndDigitSum(t *testing.T) { + // "José" is 4 letters — diacritics count, spaces/punctuation do not. + if got := letters([]any{"José"}); got != 4 { + t.Errorf("letters(José) = %d, want 4", got) + } + if got := letters([]any{"Ada Lovelace"}); got != 11 { + t.Errorf("letters = %d, want 11", got) + } + // "Any number of names, or one list of them" (Python _letters). + if got := letters([]any{"ab", "cde"}); got != 5 { + t.Errorf("letters multi = %d, want 5", got) + } + if got := digitSum([]any{"L7 7BN"}); got != 14 { + t.Errorf("digit_sum = %d, want 14", got) + } + if got := digitSum([]any{"2020"}); got != 4 { + t.Errorf("digit_sum(2020) = %d, want 4", got) + } + // Whole numbers are also accepted. + if got := digitSum([]any{int64(2020)}); got != 4 { + t.Errorf("digit_sum(2020 int) = %d, want 4", got) + } +} + +func TestParseISODate(t *testing.T) { + if _, err := parseISODate("1941-07-28"); err != nil { + t.Errorf("valid date rejected: %v", err) + } + for _, bad := range []string{ + "1941-07", "not-a-date", "1941-07-28-01", // malformed + "2024-13-01", "2024-00-15", // month out of range (Python ValueError) + "2024-02-30", "2023-02-29", // day out of range for month + } { + if _, err := parseISODate(bad); err == nil { + t.Errorf("parseISODate(%q) accepted, want a refusal", bad) + } + } +} + +// TestComputeSetLiteralDedups pins Python set semantics: {a, b, c} literals +// collapse duplicates (len({1,1,2}) == 2), and min/max operate on the unique +// members. Before the dedup fix, Go counted every member, diverging from Python. +func TestComputeSetLiteralDedups(t *testing.T) { + cases := []struct{ expr, want string }{ + {`len({1,1,2})`, "2"}, // three members, two unique + {`len({5,5,5,5})`, "1"}, // all duplicate + {`min({3,3,1})`, "1"}, // dedup before extremum + {`max({2,2,9})`, "9"}, + } + for _, c := range cases { + if got, err := Compute(c.expr); err != "" || got != c.want { + t.Errorf("Compute(%q) = %q, err=%q; want %q", c.expr, got, err, c.want) + } + } +} + +// --------------------------------------------------------------------------- +// Tool-outcome mapping +// --------------------------------------------------------------------------- + +func TestExecutorCalculate(t *testing.T) { + // A model that writes a derivable expression. + mdl := &fakeModel{replies: []*ModelReply{{ + Content: `{"needed": true, "expression": "1998 - 1954", "label": "years between", "uses": [0]}`, + }}} + ex := &searchExecutor{deps: SearchDeps{Model: mdl}} + oc, _ := ex.Execute(context.Background(), "calculate", map[string]any{ + "question": "How many years between them?", + "facts": []any{"born 1954", "died 1998"}, + }) + if oc.Status != StatusOK { + t.Fatalf("status = %s (%v), want ok", oc.Status, oc.Metrics) + } + entry := oc.Payload[0].(map[string]any) + // Python :961 — the success payload is exactly {"kind","expression","result"}; + // label/uses are deliberately NOT echoed. + if entry["result"] != "44" { + t.Errorf("result = %v, want 44", entry["result"]) + } + if entry["expression"] != "1998 - 1954" { + t.Errorf("expression = %v", entry["expression"]) + } + if _, ok := entry["label"]; ok { + t.Errorf("payload must not echo label: %v", entry) + } + + // A model that says no derivation is needed → POOR (not an error), so the + // model then answers from the facts it already has (mirrors Python + // action_session._exec_calculate: nothing derivable → status=POOR/no_doc). + mdl = &fakeModel{replies: []*ModelReply{{Content: `{"needed": false}`}}} + ex = &searchExecutor{deps: SearchDeps{Model: mdl}} + oc, _ = ex.Execute(context.Background(), "calculate", map[string]any{ + "question": "q", "facts": []any{"a"}, + }) + if oc.Status != StatusPoor { + t.Errorf("not needed: status = %s, want poor", oc.Status) + } + + // An unsafe expression → POOR (refused, logged), never a panic or a breach. + mdl = &fakeModel{replies: []*ModelReply{{ + Content: `{"needed": true, "expression": "__import__(\"os\").system(\"ls\")", "label": "x"}`, + }}} + ex = &searchExecutor{deps: SearchDeps{Model: mdl}} + if oc, _ = ex.Execute(context.Background(), "calculate", map[string]any{ + "question": "q", "facts": []any{"a"}, + }); oc.Status != StatusPoor { + t.Errorf("unsafe expr: status = %s, want poor (refused)", oc.Status) + } + + // No facts → POOR/no_doc, NOT bad_args: Python validates nothing and + // compute_from_facts' own `not facts` guard returns None (action_session.py:_exec_calculate). + ex = &searchExecutor{deps: SearchDeps{Model: &fakeModel{}}} + if oc, _ := ex.Execute(context.Background(), "calculate", map[string]any{"question": "q"}); oc.Status != StatusPoor || oc.Reason != ReasonNoDoc { + t.Errorf("no facts: got (%s,%s), want (poor,no_doc)", oc.Status, oc.Reason) + } +} + +// TestComputeFromFactsAcceptsNonBoolNeeded pins Python's `not data.get("needed")` +// guard: builtin bool() treats a NON-EMPTY STRING as truthy (even the literal +// "false"), so a model that emits needed as a string must still compute. A strict +// bool assertion would silently report "nothing derivable". +func TestComputeFromFactsAcceptsNonBoolNeeded(t *testing.T) { + mdl := &fakeModel{replies: []*ModelReply{{ + Content: `{"needed": "true", "expression": "2 + 2", "label": "sum"}`, + }}} + got := ComputeFromFacts(context.Background(), mdl, "q", []string{"two things"}, 0) + if got == nil { + t.Fatal("ComputeFromFacts = nil, want a result for a truthy non-bool needed") + } + if got.Value != "4" { + t.Errorf("value = %q, want 4", got.Value) + } +} + +func TestToolStringListAcceptsAllShapes(t *testing.T) { + // Models emit []any, []string, or a bare string. + if got := toolStringList(map[string]any{"facts": []any{"a", "b"}}, "facts"); len(got) != 2 { + t.Errorf("[]any = %v", got) + } + if got := toolStringList(map[string]any{"facts": []string{"a"}}, "facts"); len(got) != 1 { + t.Errorf("[]string = %v", got) + } + if got := toolStringList(map[string]any{"facts": "a"}, "facts"); len(got) != 1 { + t.Errorf("string = %v", got) + } + if got := toolStringList(map[string]any{}, "facts"); got != nil { + t.Errorf("absent = %v, want nil", got) + } +} + +// --------------------------------------------------------------------------- +// Tuple literals: Python whitelists ast.Tuple, used as the default sequence in +// sum((1,2,3)) / len((1,2,3)) / min / max / letters. +// --------------------------------------------------------------------------- + +func TestComputeTupleLiterals(t *testing.T) { + cases := []struct{ expr, want string }{ + {"sum((1, 2, 3))", "6"}, + {"len((1, 2, 3))", "3"}, + {"min((3, 1, 2))", "1"}, + {"max((3, 1, 2))", "3"}, + {"100 + sum((10, 20))", "130"}, + {`letters(("Ada", "Lovelace"))`, "11"}, + } + for _, c := range cases { + got, err := Compute(c.expr) + if err != "" { + t.Errorf("Compute(%q) refused: %s", c.expr, err) + continue + } + if got != c.want { + t.Errorf("Compute(%q) = %q, want %q", c.expr, got, c.want) + } + } + // A bare top-level tuple is not a number and must be refused (mirrors + // Python: a tuple result fails the isinstance(value, (int, float)) check). + if _, err := Compute("(1, 2, 3)"); err == "" { + t.Error("Compute(\"(1, 2, 3)\") returned a value, want a refusal") + } + // Parenthesised expressions (no comma) stay scalar, not a one-tuple. + if got, err := Compute("(1 + 2) * 4"); err != "" || got != "12" { + t.Errorf("Compute(\"(1 + 2) * 4\") = %q, %q; want \"12\"", got, err) + } +} + +// tempRecordingModel records the temperature handed to CompleteWithTemperature +// so the compute_from_facts 0.0 requirement can be asserted. +type tempRecordingModel struct { + replies []*ModelReply + temperature *float64 + contextLength int + calls int +} + +// ContextLength implements ContextLengthModel; 0 reports "unknown". +func (m *tempRecordingModel) ContextLength() int { + return m.contextLength +} + +func (m *tempRecordingModel) Complete(_ context.Context, _ []schema.Message, _ []ToolSpec) (*ModelReply, error) { + if m.calls >= len(m.replies) { + return &ModelReply{Content: "{}"}, nil + } + r := m.replies[m.calls] + m.calls++ + return r, nil +} + +func (m *tempRecordingModel) CompleteWithTemperature(_ context.Context, _ []schema.Message, _ []ToolSpec, temp float64) (*ModelReply, error) { + t := temp + m.temperature = &t + if m.calls >= len(m.replies) { + return &ModelReply{Content: "{}"}, nil + } + r := m.replies[m.calls] + m.calls++ + return r, nil +} + +func TestComputeFromFactsUsesTemperatureZero(t *testing.T) { + mdl := &tempRecordingModel{replies: []*ModelReply{{ + Content: `{"needed": true, "expression": "1998 - 1954", "label": "years", "uses": [0]}`, + }}} + cf := ComputeFromFacts(context.Background(), mdl, "How many years?", []string{"born 1954", "died 1998"}, 0) + if cf == nil { + t.Fatal("expected a ComputedFact") + } + if cf.Value != "44" { + t.Errorf("value = %q, want 44", cf.Value) + } + if mdl.temperature == nil { + t.Fatal("CompleteWithTemperature was not called") + } + if *mdl.temperature != 0.0 { + t.Errorf("temperature = %v, want 0.0", *mdl.temperature) + } +} + +func TestComputeFromFactsFitsToContextBudget(t *testing.T) { + mdl := &tempRecordingModel{contextLength: 0, replies: []*ModelReply{{ + Content: `{"needed": true, "expression": "1998 - 1954", "label": "years", "uses": [0]}`, + }}} + cf := ComputeFromFacts(context.Background(), mdl, "How many years?", []string{"born 1954", "died 1998"}, 0) + if cf == nil { + t.Fatal("expected a ComputedFact") + } + if cf.Value != "44" { + t.Errorf("value = %q, want 44", cf.Value) + } +} diff --git a/internal/rag/advanced_rag/harness/chunk_utils.go b/internal/rag/advanced_rag/harness/chunk_utils.go new file mode 100644 index 00000000000..07a2b3984df --- /dev/null +++ b/internal/rag/advanced_rag/harness/chunk_utils.go @@ -0,0 +1,180 @@ +// +// 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. +// + +package harness + +import ( + "fmt" + "strings" + "unicode" +) + +// Field accessors for chunk maps. +// +// Mirrors Python harness/chunk_utils.py. Maintenance-helper data — doc ids, +// dataset ids, titles — has historically been stored under different field +// names depending on the backend and indexer, so every read goes through a +// helper that tolerates all known aliases. +// +// NOTE: tools/ keeps its own accessors rather than importing these, mirroring +// Python, where tools/navigation.py defines its own _chunk_id. That duplication +// is what keeps the dependency graph acyclic (tools must not import the root +// package the root package imports tools from). + +// ChunkAttr returns the first non-empty value among keys. +// Mirrors Python _chunk_attr: truthiness is `v not in (None, "")`. +func ChunkAttr(c map[string]any, keys ...string) string { + for _, k := range keys { + if v, ok := c[k]; ok && v != nil { + if s := fmt.Sprint(v); s != "" { + return s + } + } + } + return "" +} + +// ChunkTextOf mirrors Python _chunk_text. The root package already provides +// chunkText with identical semantics; this exported form exists so callers +// outside the package share one implementation. +func ChunkTextOf(c map[string]any) string { return chunkText(c) } + +// DocIDOf mirrors Python _doc_id: doc_id / docid / document_id. +func DocIDOf(c map[string]any) string { + return ChunkAttr(c, "doc_id", "docid", "document_id") +} + +// DatasetIDOf mirrors Python _dataset_id: dataset_id / kb_id / knowledgebase_id. +func DatasetIDOf(c map[string]any) string { + return ChunkAttr(c, "dataset_id", "kb_id", "knowledgebase_id") +} + +// DocTitleOf mirrors Python _doc_title exactly: docnm_kwd / doc_title / title / +// document_name (the same four keys, in the same order). Go chunk retrieval +// carries the title under docnm_kwd, so no extra alias is needed. +func DocTitleOf(c map[string]any) string { + return ChunkAttr(c, "docnm_kwd", "doc_title", "title", "document_name") +} + +// ChunkIDOf mirrors Python _chunk_id: chunk_id / id. +func ChunkIDOf(c map[string]any) string { return ChunkAttr(c, "chunk_id", "id") } + +// Snippet mirrors Python _snippet: trim both ends, cut to limit, right-trim ALL +// trailing whitespace (not just spaces), then add an ellipsis marker when the +// value was actually truncated. Python's .rstrip() with no argument strips any +// Unicode whitespace (space, tab, newline, ...), so a cut that ends mid-run of +// whitespace collapses to the same trailing slice before "...". +// +// Python indexes strings by Unicode code point, so len(s) and s[:n] are +// character-based. Go's len/[:] are byte-based and would split a multibyte +// (e.g. CJK) rune and emit invalid UTF-8. We therefore convert to []rune so the +// limit and the cut operate on code points exactly like Python. +func Snippet(s string, limit int) string { + t := strings.TrimSpace(s) + r := []rune(t) + if len(r) <= limit { + return t + } + return strings.TrimRightFunc(string(r[:limit]), unicode.IsSpace) + "..." +} + +// IsTableChunk mirrors Python _is_table_chunk / _is_table_text: a corpus-neutral +// table detector — HTML table markup, or >=3 pipe rows. Exported so the +// orchestrator and the bridge share one implementation. +func IsTableChunk(c map[string]any) bool { + return isTableText(ChunkTextOf(c)) +} + +// isTableText mirrors Python _is_table_text: table detection from raw text. +func isTableText(text string) bool { + t := strings.ToLower(text) + if strings.Contains(t, "= 2 { + pipeRows++ + } + } + return pipeRows >= 3 +} + +// XMLEscape mirrors Python _xml_escape: the four XML entities (&, <, >, "). +// Python intentionally does NOT escape the apostrophe — values are only ever +// embedded inside double-quoted XML/Markdown attributes, where a literal ' +// is valid, so escaping it to ' would diverge from the Python output. +func XMLEscape(s string) string { + r := strings.NewReplacer( + "&", "&", + "<", "<", + ">", ">", + `"`, """, + ) + return r.Replace(s) +} + +// MergeChunks deduplicates incoming chunks against an existing slice by +// chunkKey, appending only unseen ones. Mirrors Python's +// `seen = {_chunk_key(c) for c in kbinfos["chunks"]}` merge pattern used by +// direct.py and compiled_expansion.py. +// +// Returns the merged slice and the global indices of the newly appended chunks. +func MergeChunks(existing, incoming []map[string]any) ([]map[string]any, []int) { + seen := make(map[string]struct{}, len(existing)) + for _, c := range existing { + seen[chunkKey(c)] = struct{}{} + } + out := existing + var idx []int + for _, c := range incoming { + if c == nil { + continue + } + k := chunkKey(c) + if _, dup := seen[k]; dup { + continue + } + seen[k] = struct{}{} + idx = append(idx, len(out)) + out = append(out, c) + } + return out, idx +} + +// MergeDocAggs deduplicates doc aggregations by doc id, mirroring +// direct.py:_merge_kbinfos. Returns the merged slice and the number added. +func MergeDocAggs(existing, incoming []map[string]any) ([]map[string]any, int) { + seen := make(map[any]struct{}, len(existing)) + for _, d := range existing { + seen[d["doc_id"]] = struct{}{} + } + out := existing + added := 0 + for _, d := range incoming { + if d == nil { + continue + } + key := d["doc_id"] + if _, dup := seen[key]; dup { + continue + } + seen[key] = struct{}{} + out = append(out, d) + added++ + } + return out, added +} diff --git a/internal/rag/advanced_rag/harness/chunk_utils_test.go b/internal/rag/advanced_rag/harness/chunk_utils_test.go new file mode 100644 index 00000000000..e707f0924f8 --- /dev/null +++ b/internal/rag/advanced_rag/harness/chunk_utils_test.go @@ -0,0 +1,57 @@ +// +// 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. +// + +package harness + +import "testing" + +// TestSnippet covers Python _snippet parity: trim both ends, cut to limit, +// right-trim ALL trailing whitespace, then add "...". +func TestSnippet(t *testing.T) { + cases := []struct { + in string + n int + want string + }{ + // Short values pass through trimmed, no ellipsis. + {" hello ", 10, "hello"}, + // No truncation needed. + {"hello", 10, "hello"}, + // Truncation that lands on a plain space boundary. + {"hello world", 5, "hello..."}, + // Cut ends mid-run of plain spaces: right-trim them. + {"hello world", 6, "hello..."}, + // Cut ends mid-run of a tab: right-trim ALL whitespace, like .rstrip(). + {"hello\t\tworld", 6, "hello..."}, + // Cut ends on a newline run. + {"hello\n\nworld", 6, "hello..."}, + // Mixed trailing whitespace after the cut. + {"hello \t\n world", 6, "hello..."}, + // CJK chars are multibyte in UTF-8; the limit is in code points + // (Python str semantics), so no rune is ever split. "中文" (2 code + // points) fits within n=2 and stays intact. + {" 中文 ", 2, "中文"}, + // Truncation lands on a code-point boundary: first 3 of 4 CJK chars. + {"中文中文", 3, "中文中..."}, + // A small byte limit must not split a 3-byte CJK rune. + {"中文abc", 2, "中文..."}, + } + for _, c := range cases { + if got := Snippet(c.in, c.n); got != c.want { + t.Errorf("Snippet(%q, %d) = %q, want %q", c.in, c.n, got, c.want) + } + } +} diff --git a/internal/rag/advanced_rag/harness/config.go b/internal/rag/advanced_rag/harness/config.go new file mode 100644 index 00000000000..f61adea46e7 --- /dev/null +++ b/internal/rag/advanced_rag/harness/config.go @@ -0,0 +1,154 @@ +// +// 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. +// + +package harness + +import "strings" + +// Thinking-mode configuration: the single authority for mode behaviour. +// +// Mirrors Python harness/config.py. Every mode-dependent decision in the +// harness reads from this file instead of re-deriving it from a thinking_mode +// string, so tuning a mode is a one-table edit. +// +// Unknown labels fall back to NAIVE rather than erroring: the label comes from +// user input at request time, and failing here would fail the whole request. + +// allTools are the tools the action session can bind, in declaration order. +// Kept here so a mode's tool set is data, not an if-chain in the runtime. +var allTools = []string{ + "retrieve", + "search_chunks", + "list_chunks", + "navigate_tree", + "navigate_structure", + "calculate", + "web_search", +} + +// GraphExploreTool is the relational exploration tool reserved for ultra. +const GraphExploreTool = "graph_explore" + +// ModeSpec mirrors Python config.ModeSpec (a frozen dataclass). Everything that +// varies between thinking modes lives here. +// +// Tools is the set of tool names visible to the model in this mode. An empty +// set means the model gets no tool loop at all. +type ModeSpec struct { + Label string + Agentic bool + EnableSCA bool + SCAMaxRounds int + UseFanout bool + ActionMaxTurns int + Tools map[string]bool +} + +// toolsOf builds the tool set from names (mirrors Python _tools()). +func toolsOf(names ...string) map[string]bool { + m := make(map[string]bool, len(names)) + for _, n := range names { + m[n] = true + } + return m +} + +// allToolSet returns the default tool surface (mirrors Python _ALL_TOOLS). +func allToolSet() map[string]bool { + return toolsOf(allTools...) +} + +// THINKING_MODES mirrors Python config.THINKING_MODES. +// +// - low: one hybrid-search pass through direct_search. No action session, +// so no tool loop — the model never sees tools in this mode. +// - medium: agentic, SCA review on, no planner decomposition. +// - high: adds planner + prefetch fan-out over the same tool surface. +// - ultra: deeper sessions, more SCA rounds, and the relational tool. +var THINKING_MODES = map[string]ModeSpec{ + "low": { + Label: "low", Agentic: false, EnableSCA: false, + SCAMaxRounds: 0, UseFanout: false, ActionMaxTurns: 4, + Tools: map[string]bool{}, + }, + "medium": { + Label: "medium", Agentic: true, EnableSCA: true, + SCAMaxRounds: 3, UseFanout: false, ActionMaxTurns: 4, + Tools: allToolSet(), + }, + "high": { + Label: "high", Agentic: true, EnableSCA: true, + SCAMaxRounds: 3, UseFanout: true, ActionMaxTurns: 4, + Tools: allToolSet(), + }, + "ultra": { + Label: "ultra", Agentic: true, EnableSCA: true, + SCAMaxRounds: 5, UseFanout: true, ActionMaxTurns: 6, + Tools: toolsOf(append(append([]string{}, allTools...), GraphExploreTool)...), + }, +} + +// NAIVE is the fallback for an unrecognised mode label. It is not agentic — the +// caller answers with plain retrieval rather than failing the request. +var NAIVE = ModeSpec{ + Label: "naive", Agentic: false, EnableSCA: false, + SCAMaxRounds: 0, UseFanout: false, ActionMaxTurns: 4, + Tools: map[string]bool{}, +} + +// HasTool reports whether the mode exposes the named tool. +func (m ModeSpec) HasTool(name string) bool { return m.Tools[name] } + +// ToolNames returns the mode's visible tool names in declaration order, so +// schema generation is deterministic (Go map iteration is randomised). +func (m ModeSpec) ToolNames() []string { + out := make([]string, 0, len(m.Tools)) + for _, n := range allTools { + if m.Tools[n] { + out = append(out, n) + } + } + if m.Tools[GraphExploreTool] { + out = append(out, GraphExploreTool) + } + return out +} + +// GetMode mirrors Python get_mode(label): unknown labels fall back to NAIVE. +// The label arrives from user input, so erroring here would fail the request. +func GetMode(label string) ModeSpec { + m, ok := THINKING_MODES[strings.ToLower(strings.TrimSpace(label))] + if !ok { + return NAIVE + } + return m +} + +// ThinkingModeCarrier is implemented by the RAGTools-like object that owns the +// request-scoped retrieval context (Python RAGTools.thinking_mode). +type ThinkingModeCarrier interface { + GetThinkingMode() string +} + +// ResolveMode mirrors Python resolve_mode(tools): reads a RAGTools-like +// object's thinking mode into its spec. Values that do not implement +// ThinkingModeCarrier fall back to NAIVE, matching Python's getattr default. +func ResolveMode(tools any) ModeSpec { + if c, ok := tools.(ThinkingModeCarrier); ok { + return GetMode(c.GetThinkingMode()) + } + return NAIVE +} diff --git a/internal/rag/advanced_rag/harness/doc_fetch.go b/internal/rag/advanced_rag/harness/doc_fetch.go new file mode 100644 index 00000000000..7d4878f7dd8 --- /dev/null +++ b/internal/rag/advanced_rag/harness/doc_fetch.go @@ -0,0 +1,183 @@ +// +// 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. +// + +package harness + +import ( + "context" + + "ragflow/internal/rag/prompts" + "ragflow/internal/tokenizer" +) + +const ( + // docFetchPageSize is Python's 128-chunk page. + docFetchPageSize = 128 + // docFetchMaxChunks is Python's hard 10000-chunk cap (max_count > 10000). + docFetchMaxChunks = 10000 + // docFetchFallbackTokens bounds the fetch when the caller supplies no model + // window. Python always passes one, so this only guards a Go-only caller. + docFetchFallbackTokens = 8192 + // estimateCharsPerToken approximates the tokenizer when no model encoder is + // loaded; estimateTokens falls back to it only when tokenizer.NumTokensFromString + // returns 0 (encoder unavailable). Python uses num_tokens_from_string directly. + estimateCharsPerToken = 4 +) + +// fetchFullDocument mirrors Python RAGTools.fetch_full_document +// (agentic_rag.py:fetch_full_document): read a document end-to-end in reading order, in pages, +// stopping before the model window would overflow. +// +// Returns (chunks, docAggs). Both are nil when the document is unavailable — +// unbound datasets, a document outside the session scope, or an empty read. +func fetchFullDocument(ctx context.Context, deps SearchDeps, docID string, maxTokens int) ([]map[string]any, []map[string]any) { + if deps.DocChunks == nil || docID == "" || len(deps.KbIDs) == 0 { + _LOG.Printf("[Fetch full document] skipped (doc_id=%q, datasets=%d)", docID, len(deps.KbIDs)) + return nil, nil + } + // Python :765 — a session-wide document scope is authoritative. + if len(deps.DocScope) > 0 && !containsStr(deps.DocScope, docID) { + _LOG.Printf("[Fetch full document] doc_id %q is outside the session document scope", docID) + return nil, nil + } + // Python :768 — never read a document that is not in the bound datasets. + if belongs, verified := docInDatasets(ctx, deps, docID); verified && !belongs { + _LOG.Printf("[Fetch full document] doc_id %q is not in any bound dataset — refusing to fetch", docID) + return nil, nil + } + + budget := maxTokens + if budget <= 0 { + budget = docFetchFallbackTokens + } + + var chunks []map[string]any + tokens := 0 + budgetHit := false + // Python :769-776 — NOTE: the budget check breaks the OUTER loop, so a page + // that overruns the window stops paging entirely. Kept as-is: the budget is + // a hard stop, and continuing would only add chunks that get dropped. + for offset := 0; offset < docFetchMaxChunks && !budgetHit; offset += docFetchPageSize { + page, err := deps.DocChunks.DocChunks(ctx, DocChunksRequest{ + DocID: docID, + DatasetIDs: deps.KbIDs, + TenantID: deps.TenantID, + Offset: offset, + Limit: docFetchPageSize, + }) + if err != nil { + _LOG.Printf("[Fetch full document] page at offset %d failed: %v", offset, err) + break + } + if len(page) == 0 { + break + } + for _, ck := range page { + n := estimateTokens(ChunkTextOf(ck)) + if tokens+n > budget { + budgetHit = true + break + } + tokens += n + chunks = append(chunks, ck) + } + if len(page) < docFetchPageSize { + break // document exhausted + } + } + if len(chunks) == 0 { + _LOG.Printf("[Fetch full document] no chunks for doc_id %q", docID) + return nil, nil + } + + docName := "" + for _, c := range chunks { + if t := DocTitleOf(c); t != "" { + docName = t + break + } + } + aggs := []map[string]any{ + {"doc_name": docName, "doc_id": docID, "count": len(chunks)}, + } + return chunks, aggs +} + +// summarizeDocument mirrors Python RAGTools.summarize_document +// (agentic_rag.py:rag): load the whole document, fold it into the evidence the +// citation rules refer to, and return the newly rendered blocks. +func summarizeDocument(ctx context.Context, deps SearchDeps, docID string, maxTokens int) []string { + chunks, aggs := fetchFullDocument(ctx, deps, docID, maxTokens) + if len(chunks) == 0 { + return nil + } + budget := maxTokens + if budget <= 0 { + budget = docFetchFallbackTokens + } + + // Python :942-948 — the document becomes part of the evidence set, so its + // [ID]s stay citable; only the blocks added here are returned. + startIdx := 0 + if deps.KB != nil { + startIdx = len(deps.KB.Chunks) + deps.KB.Merge(chunks, aggs) + } else { + deps.KB = &Kbinfos{} + deps.KB.Merge(chunks, aggs) + } + blocks := prompts.KBPrompt(deps.KB.Chunks, budget) + if startIdx >= len(blocks) { + return nil + } + fresh := blocks[startIdx:] + + // Python :952-959 — without do_refer the model is told not to cite, so the + // rules must not be handed to it. + if !deps.DoRefer { + return fresh + } + header := "# Citation rules\nApply the following rules VERBATIM to your final answer.\n\n" + + prompts.CitationPrompt(deps.CiteRules) + "\n\n----\n\n" + return append([]string{header}, fresh...) +} + +// SummarizeDocument is the exported, Python-RAGTools.summarize_document +// equivalent used by the outer react loop (rag_agent) as a non-terminal tool. +// It reads the whole document identified by docID into the evidence set and +// returns the prompt blocks to feed back to the model. do_refer is taken from +// deps.DoRefer (Python lets the RAGTools context decide whether the model may +// cite the freshly read document), so callers control citation behavior. +// Returns nil when the document has no readable chunks (deps.DocChunks unset +// or the doc is unavailable). +func SummarizeDocument(ctx context.Context, deps SearchDeps, docID string, maxTokens int) []string { + if deps.DocChunks == nil { + return nil + } + return summarizeDocument(ctx, deps, docID, maxTokens) +} + +// estimateTokens returns the token count of s. It prefers the precise +// tokenizer (tokenizer.NumTokensFromString, mirroring Python's +// num_tokens_from_string); when no encoder is loaded that returns 0, so we +// fall back to a character/estimateCharsPerToken approximation for a rough +// budget, like the previous Go-only behavior. +func estimateTokens(s string) int { + if n := tokenizer.NumTokensFromString(s); n > 0 { + return n + } + return (len([]rune(s)) + estimateCharsPerToken - 1) / estimateCharsPerToken +} diff --git a/internal/rag/advanced_rag/harness/grep_sed_narrow.go b/internal/rag/advanced_rag/harness/grep_sed_narrow.go new file mode 100644 index 00000000000..ffb6acf72c3 --- /dev/null +++ b/internal/rag/advanced_rag/harness/grep_sed_narrow.go @@ -0,0 +1,573 @@ +// +// 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. +// + +package harness + +import ( + "regexp" + "strings" + "unicode/utf8" +) + +// In-memory grep+sed narrowing engine (term-driven, zero extra LLM rounds). +// +// Mirrors Python harness/grep_sed_narrow.py. +// +// It mirrors the Claude Code / Codex ``grep`` + ``sed`` workflow over chunks held in +// memory: terms already produced by the main-analysis LLM (entities, numbers, key +// phrases) become word-boundary regexes for locating (grep), and string transforms +// narrow the text (sed), dropping boilerplate instead of crude head-truncation. +// +// Fallback chain (never drops the answer): +// +// narrow_by_terms (grep locate + sed transform) +// -> no hits / no terms +// -> _narrow_by_keywords (keyword sentence-level, zero LLM) +// -> original chunks returned as-is (caller's head-truncation as the final +// safety valve) +// +// Safety: regexp + pure string ops only, no eval; term count and context are capped. + +// Cost / safety caps. Mirrors grep_sed_narrow.py's module constants. +const ( + // maxGrepTerms caps the terms compiled (Python _MAX_GREP_TERMS). + maxGrepTerms = 16 + // maxContext is the +/- window of lines kept around a hit (Python _MAX_CONTEXT). + maxContext = 2 + // defaultOutCharsPerChunk caps output per chunk (Python _DEFAULT_OUT_CHARS_PER_CHUNK). + defaultOutCharsPerChunk = 1200 + // defaultOutTotalChars caps the total narrowed output (Python _DEFAULT_OUT_TOTAL_CHARS). + defaultOutTotalChars = 16000 + // headFallbackChars is the head kept per chunk when there is no match + // (Python _HEAD_FALLBACK_CHARS). + headFallbackChars = 400 + // contextCharBudget is the absolute per-side char budget during context + // expansion (Python _CONTEXT_CHAR_BUDGET). + contextCharBudget = 600 + // minNarrowChars: chunks at or below this length are NOT narrowed — they are + // already 1-2 lines, and answers often live in short chunks (Python _MIN_NARROW_CHARS). + minNarrowChars = 200 +) + +var ( + // reTermEdgePunct strips leading/trailing punctuation from a term (Python + // `re.sub(r"^[\s.,:;!?'\"()\[\]{}]+|...$", "", t)`). + reTermEdgePunct = regexp.MustCompile(`^[\s.,:;!?'"()\[\]{}]+|[\s.,:;!?'"()\[\]{}]+$`) + // reCJKTerm detects CJK / kana / hangul, which must NOT be wrapped in \b — + // a word boundary never matches between CJK characters. + reCJKTerm = regexp.MustCompile(`[\p{Han}\p{Hiragana}\p{Katakana}\p{Hangul}]`) +) + +// EscapeTerm escapes a plain grep term into a safe, word-boundary regex fragment. +// Mirrors Python _escape_term: numbers/entities matched literally; 3+ char terms +// with alphanumeric edges get \b; CJK terms stay bare (never wrapped in \b). +func EscapeTerm(term string) string { + t := strings.TrimSpace(term) + if t == "" { + return "" + } + t = reTermEdgePunct.ReplaceAllString(t, "") + if t == "" { + return "" + } + escaped := regexp.QuoteMeta(t) + if reCJKTerm.MatchString(t) { + return escaped + } + rs := []rune(t) + if len(rs) >= 3 && isAlphaNumRune(rs[0]) && isAlphaNumRune(rs[len(rs)-1]) { + return `\b` + escaped + `\b` + } + return escaped +} + +func isAlphaNumRune(r rune) bool { + return r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' +} + +// TermsToPatterns turns grep terms into a list of compiled regexes (one per +// term), capped at maxGrepTerms. Mirrors Python _terms_to_patterns. +func TermsToPatterns(terms []string) []*regexp.Regexp { + out := make([]*regexp.Regexp, 0, len(terms)) + for _, term := range terms { + if len(out) >= maxGrepTerms { + break + } + frag := EscapeTerm(term) + if frag == "" { + continue + } + p, err := regexp.Compile("(?i)" + frag) + if err != nil { + continue + } + out = append(out, p) + } + return out +} + +// GrepTermsMax caps the terms extracted from a query (Python _GREP_TERMS_MAX). +const GrepTermsMax = 10 + +// GrepOutCharsPerChunk is the grep narrow's per-chunk output cap (Python +// _GREP_OUT_CHARS_PER_CHUNK). +const GrepOutCharsPerChunk = 700 + +// GrepOutTotalChars is the grep narrow's total output cap (Python +// _GREP_OUT_TOTAL_CHARS). +const GrepOutTotalChars = 8000 + +// GrepTermsFromQuery mirrors Python _grep_terms_from_query: +// extract compact grep terms from a query — bare alnum words of length>=2, +// deduped (order-preserving) and capped. Numbers/ids are preserved as-is. +func GrepTermsFromQuery(query string) []string { + q := strings.TrimSpace(query) + if q == "" { + return nil + } + terms := make([]string, 0, GrepTermsMax) + seen := make(map[string]struct{}, GrepTermsMax) + re := regexp.MustCompile(`[A-Za-z0-9][A-Za-z0-9_.\-]{1,}`) + for _, m := range re.FindAllString(q, -1) { + t := strings.Trim(m, "._-") + if len(t) < 2 { + continue + } + low := strings.ToLower(t) + if _, ok := seen[low]; ok { + continue + } + seen[low] = struct{}{} + terms = append(terms, t) + if len(terms) >= GrepTermsMax { + break + } + } + return terms +} + +// lineSpans returns line (start,end) spans, boundaries at "\n" (grep semantics). +// Mirrors Python _line_spans: line boundaries are exact (unlike lossy sentence +// splitting); start of line i is after the i-th "\n". +func lineSpans(content string) [][2]int { + var spans [][2]int + start := 0 + for i := 0; i < len(content); i++ { + if content[i] == '\n' { + spans = append(spans, [2]int{start, i}) + start = i + 1 + } + } + if start <= len(content) { + spans = append(spans, [2]int{start, len(content)}) + } + if len(spans) == 0 { + spans = [][2]int{{0, len(content)}} + } + return spans +} + +// NarrowContext is the +/- line-context window greed by term-grep (Python +// narrow_by_terms' `context` dict). +type NarrowContext struct { + Before int + After int +} + +// execOnText runs term-grep + line-context expansion against one chunk's text. +// Mirrors Python _exec_on_text: +// +// - locate matches exactly (match.start()/end()); +// - merge overlapping/adjacent ranges, expand to whole lines, add before/after +// context lines, with a per-side character-budget clamp; +// - on no hit, keep fact-dense sentences (never drop everything), else head. +// +// Returns (narrowed, matched). +func execOnText(content string, patterns []*regexp.Regexp, before, after, outCharsPerChunk int) (string, bool) { + if content == "" { + return "", false + } + + // Step 1: locate matches (exact positions from the regex engine). + var hitRanges [][2]int + for _, p := range patterns { + locs := p.FindAllStringIndex(content, -1) + for _, loc := range locs { + hitRanges = append(hitRanges, [2]int{loc[0], loc[1]}) + } + } + if len(hitRanges) == 0 { + // Keep fact-dense sentences to avoid dropping numbers/entities (Python's + // no-hit path keeps dense sentences, else the raw head). + var kept []string + for _, s := range SplitSentences(content) { + if IsFactDenseSentence(s) { + kept = append(kept, s) + } + } + narrowed := strings.TrimSpace(strings.Join(kept, "")) + if narrowed != "" { + return truncHead(narrowed, headFallbackChars*4), false + } + return truncHead(content, headFallbackChars), false + } + + // Step 2: merge overlapping/adjacent matches. + sort2DRanges(hitRanges) + merged := make([][2]int, 0, len(hitRanges)) + for _, r := range hitRanges { + if n := len(merged); n > 0 && r[0] <= merged[n-1][1] { + if r[1] > merged[n-1][1] { + merged[n-1][1] = r[1] + } + } else { + merged = append(merged, r) + } + } + + lines := lineSpans(content) + var expanded [][2]int + for _, r := range merged { + lo, hi := 0, 0 + for i, ls := range lines { + if r[0] >= ls[0] && r[0] < ls[1] { + lo = i + } + if r[1] > ls[0] && r[1] <= ls[1] { + hi = i + } + } + lo = max(0, lo-before) + hi = min(len(lines)-1, hi+after) + fragS, fragE := lines[lo][0], lines[hi][1] + // Per-side character budget fallback. + if fragE-fragS > contextCharBudget*2 && (fragE-fragS) > (r[1]-r[0]) { + fragS = max(0, r[0]-contextCharBudget) + fragE = min(len(content), r[1]+contextCharBudget) + } + expanded = append(expanded, [2]int{fragS, fragE}) + } + + // Step 3: dedupe, join, truncate. + seen := map[string]bool{} + var outParts []string + for _, e := range expanded { + p := strings.TrimSpace(content[e[0]:e[1]]) + if p == "" { + continue + } + key := truncHead(p, 200) + if seen[key] { + continue + } + seen[key] = true + outParts = append(outParts, p) + } + narrowed := strings.TrimSpace(strings.Join(outParts, "\n\n")) + if charLen(narrowed) > outCharsPerChunk { + narrowed = truncHead(narrowed, outCharsPerChunk) + } + if narrowed == "" { + return truncHead(content, headFallbackChars), true + } + return narrowed, true +} + +// NarrowStats carries the accounting Python narrow_by_terms returns in its +// "stats" dict. +type NarrowStats struct { + ChunksIn int + ChunksKpt int + CharsIn int + CharsOut int + Matched bool + UsedTerms int +} + +// NarrowResult is the outcome of NarrowByTerms / GrepSedNarrow, mirroring +// Python's {"kept": [...], "stats": {...}} dict. +type NarrowResult struct { + Kept []map[string]any + Stats NarrowStats +} + +// NarrowByTerms narrows retrieval chunks by locating grep terms, mirroring +// Python narrow_by_terms: +// +// - terms are plain strings (entities / numbers / key phrases); +// - no usable terms -> keyword narrowing (zero LLM); +// - primary terms hit nothing -> fallbackTerms tried once mechanically; +// - still no hit -> narrowing abandoned, originals returned (matched=false); +// - when matched, a total-length budget is distributed across chunks. +// +// Never raises. +func NarrowByTerms(chunks []map[string]any, terms []string, fallbackTerms []string, keywords string, context NarrowContext, maxOutCharsPerChunk, maxOutTotalChars int) NarrowResult { + before := clampInt(context.Before, 0, maxContext) + after := clampInt(context.After, 0, maxContext) + + patterns := TermsToPatterns(terms) + stats := NarrowStats{ + ChunksIn: len(chunks), + UsedTerms: len(patterns), + } + for _, c := range chunks { + stats.CharsIn += len(ChunkTextOf(c)) + } + if len(chunks) == 0 { + return NarrowResult{Kept: nil, Stats: stats} + } + if len(patterns) == 0 { + narrowed := NarrowWithFallbackKeyword(chunks, keywords) + stats.ChunksKpt = len(narrowed) + for _, c := range narrowed { + stats.CharsOut += len(ChunkTextOf(c)) + } + return NarrowResult{Kept: narrowed, Stats: stats} + } + + run := func(active []*regexp.Regexp) ([]map[string]any, []bool, int) { + var kept []map[string]any + var flags []bool + matched := 0 + for _, c := range chunks { + raw := ChunkTextOf(c) + if charLen(raw) <= minNarrowChars { + // Short chunk: kept whole. Flagged as matched so it still + // participates in the total-budget distribution; Python + // overwrites with the identical text and pops "highlight". + kept = append(kept, withNarrowedText(c, raw)) + flags = append(flags, true) + continue + } + text, ok := execOnText(raw, active, before, after, maxOutCharsPerChunk) + if ok { + matched++ + kept = append(kept, withNarrowedText(c, text)) + } else { + // No match: keep the original chunk untouched (full text and any + // "highlight" preserved) — mirrors Python _apply_narrow's else. + kept = append(kept, cloneMap(c)) + } + flags = append(flags, ok) + } + return kept, flags, matched + } + + kept, matchedFlags, _ := run(patterns) + + // Gentle retry (no extra LLM): primary terms hit nothing -> fallback terms once. + if len(fallbackTerms) > 0 && !anyBool(matchedFlags) { + if fb := TermsToPatterns(fallbackTerms); len(fb) > 0 { + kept, matchedFlags, _ = run(fb) + if len(fb) > stats.UsedTerms { + stats.UsedTerms = len(fb) + } + } + } + + // Only apply the total-length cap when the grep actually matched: on a no-match + // the chunks are returned untouched so the caller's compaction decides. + if anyBool(matchedFlags) { + totalOut := 0 + for _, c := range kept { + totalOut += charLen(ChunkTextOf(c)) + } + if totalOut > maxOutTotalChars { + perChunk := max(200, min(maxOutCharsPerChunk, maxOutTotalChars/max(1, len(kept)))) + acc := 0 + var trimmed []map[string]any + for _, c := range kept { + t := ChunkTextOf(c) + room := maxOutTotalChars - acc + if room <= 0 { + break + } + take := min(charLen(t), min(perChunk, room)) + if take <= 0 { + break + } + if take < charLen(t) { + c = withNarrowedText(cloneMap(c), truncHead(t, take)) + } + trimmed = append(trimmed, c) + acc += take + } + kept = trimmed + } + } + + stats.ChunksKpt = len(kept) + for _, c := range kept { + stats.CharsOut += len(ChunkTextOf(c)) + } + stats.Matched = anyBool(matchedFlags) + logGrepSed(stats) + return NarrowResult{Kept: kept, Stats: stats} +} + +// NarrowWithFallbackKeyword applies keyword narrowing (zero LLM), returning the +// originals when keyword narrowing yields nothing (Python _fallback_narrow_by_keywords). +func NarrowWithFallbackKeyword(chunks []map[string]any, keywords string) []map[string]any { + if narrowed := NarrowByKeywords(chunks, keywords); len(narrowed) > 0 { + return narrowed + } + return chunks +} + +// fallbackStopwords mirrors Python _FALLBACK_STOPWORDS. +var fallbackStopwords = map[string]bool{ + "what": true, "which": true, "who": true, "where": true, "when": true, "how": true, + "the": true, "a": true, "an": true, "of": true, "in": true, "on": true, + "for": true, "to": true, "and": true, "or": true, "with": true, "is": true, + "are": true, "was": true, "were": true, "list": true, "name": true, "give": true, + "find": true, "tell": true, "me": true, "about": true, "from": true, "that": true, + "this": true, "it": true, "its": true, "their": true, "they": true, "have": true, + "has": true, "do": true, "does": true, "did": true, "based": true, "per": true, + "according": true, "not": true, +} + +// SplitFallbackTerms splits free text into fallback grep terms (zero LLM), +// mirroring Python split_fallback_terms: splits on sentence/comma boundaries, +// drops short/stopword tokens, keeps numbers and multi-word phrases. +func SplitFallbackTerms(texts ...string) []string { + var terms []string + seen := map[string]bool{} + for _, v := range texts { + for _, part := range reFallbackSplit.Split(strings.TrimSpace(v), -1) { + part = strings.TrimSpace(strings.Trim(part, "'\"()[]{}")) + if len(part) < 3 { + continue + } + if fallbackStopwords[strings.ToLower(part)] { + continue + } + if seen[part] { + continue + } + seen[part] = true + terms = append(terms, part) + if len(terms) >= maxGrepTerms { + return terms + } + } + } + return terms +} + +var reFallbackSplit = regexp.MustCompile(`[\n。;;,.?!?]+`) + +// GrepSedNarrow narrows chunks by grepping terms extracted directly from the +// claim (zero LLM), mirroring Python grep_sed_narrow. Terms are derived from the +// claim text via SplitFallbackTerms; no extra LLM call. Never raises. +func GrepSedNarrow(chunks []map[string]any, claimSources []string, maxOutCharsPerChunk, maxOutTotalChars int) NarrowResult { + if len(chunks) == 0 { + return NarrowResult{Kept: chunks, Stats: NarrowStats{ChunksIn: 0}} + } + terms := SplitFallbackTerms(claimSources...) + return NarrowByTerms(chunks, terms, nil, strings.Join(claimSources, " "), NarrowContext{}, maxOutCharsPerChunk, maxOutTotalChars) +} + +// GrepSummaryFromClaims mirrors Python grep_sed_narrow's public convenience: given +// claim/question texts, produce a compact narrowed evidence string (used by the +// compiled-structure grepper in search.go). Returns "" when nothing was kept. +func GrepSummaryFromClaims(chunks []map[string]any, claimSources []string) string { + res := GrepSedNarrow(chunks, claimSources, defaultOutCharsPerChunk, defaultOutTotalChars) + if len(res.Kept) == 0 { + return "" + } + var b strings.Builder + for _, c := range res.Kept { + if t := ChunkTextOf(c); t != "" { + b.WriteString(t) + b.WriteString("\n") + } + } + return b.String() +} + +func logGrepSed(s NarrowStats) { + _LOG.Printf("[grep-sed] chunks=%d->%d chars=%d->%d matched=%t terms=%d", + s.ChunksIn, s.ChunksKpt, s.CharsIn, s.CharsOut, s.Matched, s.UsedTerms) +} + +// --------------------------------------------------------------------------- +// Local helpers shared with the narrowing paths +// --------------------------------------------------------------------------- + +func cloneMap(c map[string]any) map[string]any { + cp := make(map[string]any, len(c)) + for k, v := range c { + cp[k] = v + } + return cp +} + +// withNarrowedText returns a copy of the chunk with its narrowed text applied. +// Mirrors Python _apply_narrow's matched branch: it overwrites +// "content_with_weight", mirrors "content" only when that key already exists, +// and drops "highlight" (the pre-narrow highlight spans no longer apply). +func withNarrowedText(c map[string]any, narrowed string) map[string]any { + cp := cloneMap(c) + cp["content_with_weight"] = narrowed + if _, ok := cp["content"]; ok { + cp["content"] = narrowed + } + delete(cp, "highlight") + return cp +} + +// charLen is the codepoint length, matching Python's len(str). Go's len(string) +// is bytes, which diverges for CJK; the narrowing caps are codepoint budgets. +func charLen(s string) int { return utf8.RuneCountInString(s) } + +// truncHead keeps the first n codepoints (not bytes) of s, mirroring Python's +// s[:n]. Byte slicing would corrupt multi-byte CJK and mis-size output; rune +// slicing keeps it faithful to the Python engine. +func truncHead(s string, n int) string { + if charLen(s) <= n { + return s + } + return string([]rune(s)[:n]) +} + +func sort2DRanges(ranges [][2]int) { + for i := 0; i < len(ranges); i++ { + for j := i + 1; j < len(ranges); j++ { + if ranges[j][0] < ranges[i][0] { + ranges[i], ranges[j] = ranges[j], ranges[i] + } + } + } +} + +func anyBool(flags []bool) bool { + for _, f := range flags { + if f { + return true + } + } + return false +} + +func clampInt(v, lo, hi int) int { + if v < lo { + return lo + } + if v > hi { + return hi + } + return v +} diff --git a/internal/rag/advanced_rag/harness/kbinfos.go b/internal/rag/advanced_rag/harness/kbinfos.go new file mode 100644 index 00000000000..548b56d0de3 --- /dev/null +++ b/internal/rag/advanced_rag/harness/kbinfos.go @@ -0,0 +1,235 @@ +// +// 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. +// + +package harness + +import ( + "context" + "fmt" + "sync" +) + +// The shared accumulation store and the retrieval abstraction. +// +// In Python this is not a harness module: it is the plain dict +// `self.kbinfos = {"chunks": [], "doc_aggs": [], "memory": []}` carried by the +// RAGTools instance in, threaded through retrieval, the +// action session, SCA, and the final answer via tools.kbinfos. The Go port +// reifies that dict into the typed Kbinfos struct (with the Merge helper) and +// keeps it in the harness package because chunkKey/chunkText and Merge are +// unexported helpers shared by tool_search.go, tool_exploration.go, and +// tool_compiled_expansion.go — a reification, not a 1:1 file mirror. +// +// This file also owns the chunk identity helpers (chunkKey/chunkText) that the +// merge logic depends on. + +// SearchParams mirrors Python tools/search.py::hybrid_search(tools, query, +// kb_ids, top_n, doc_scope, keywords, retrieval_query, use_compiled). +// +// Question is the search query; Keywords is used ONLY to narrow retrieved +// chunks (never to build the query) unless RetrievalQuery is empty. +type SearchParams struct { + Question string + // Keywords narrows retrieved chunks to the sentences that mention them. + // When RetrievalQuery is empty it also falls back into the query text. + Keywords string + // RetrievalQuery is the entity/qualifier-weighted query (entity x3, + // qualifier x3) appended to the bare Question: a problem-level search over + // the raw question is exactly where the entity must dominate the ranking. + RetrievalQuery string + // UseCompiled enables compiled-structure expansion (page index / tree / + // mindmap / knowledge graph / wiki synthesis pages). + UseCompiled bool + // KbIDs restricts the search to these dataset ids. Empty falls back to the + // session's bound datasets. + KbIDs []string + // DocScope restricts the search to these document ids (e.g. the doc_id + // routed by navigate_tree). + DocScope []string + // TopN is the result count. <= 0 selects the configured default. + TopN int + // Channel is retained for backward compatibility with callers that still + // poke the unified HybridSearch with an explicit channel. It is DEPRECATED: + // each Python entry point is now its own function (HybridSearch / + // VectorSearch / BM25Search / GrepSearch / RetrieveSearch) and selects its + // vector weight, similarity threshold and compiled-row exclusion + // internally. New code should call the specific function instead of setting + // Channel on HybridSearch. runSearch does NOT read this field. + Channel SearchChannel +} + +// SearchFn performs one hybrid search and returns chunks + doc aggs, so the +// harness is decoupled from the concrete retrieval backend. +// Mirrors the Python side's settings.retriever.retrieval call. +type SearchFn func(ctx context.Context, p SearchParams) ([]map[string]any, []map[string]any) + +// Kbinfos is the shared accumulation store. +type Kbinfos struct { + Chunks []map[string]any + DocAggs []map[string]any + // Memory is the lossless store of raw retrieved chunks backing the (lossy) + // Chunks list that feeds the LLM. Mirrors Python kbinfos["memory"], which + // memory.add/grep maintain. + Memory []map[string]any + // PreSummary is the merged claim-report summary produced by the action + // session; the final-answer call reads it when set. + PreSummary string + // cache is the per-request retrieval cache (Python tools.search_cache). It + // is initialised lazily via cacheOnce so a zero-value Kbinfos is usable. + cache *searchCache + cacheOnce sync.Once +} + +// HasChunks mirrors Python `bool(kbinfos.get("chunks"))`. +func (k *Kbinfos) HasChunks() bool { return len(k.Chunks) > 0 } + +// Merge appends the given chunks/aggs, deduplicating by chunkKey, and returns the +// GLOBAL index (position in k.Chunks) of every contributed chunk — deduped ones +// included. len(result) is therefore NOT the count of new evidence: callers that +// need that compare len(k.Chunks) before and after. +// +// Mirrors orchestrator/direct.py:_merge_kbinfos, including its early return on an +// empty chunk list (neither chunks nor doc_aggs are merged). +func (k *Kbinfos) Merge(chunks, aggs []map[string]any) []int { + if len(chunks) == 0 { + return nil + } + seen := make(map[string]bool, len(k.Chunks)) + for _, c := range k.Chunks { + seen[chunkKey(c)] = true + } + var added []int + for _, c := range chunks { + kk := chunkKey(c) + if !seen[kk] { + seen[kk] = true + k.Chunks = append(k.Chunks, c) + } + // Deduped chunks get an entry too: the return value is positional. + added = append(added, indexOfChunk(k.Chunks, kk)) + } + k.MergeDocAggs(aggs) + return added +} + +// MergeDocAggs appends doc aggregations, deduplicating by doc_id: the first agg +// per doc_id wins (Python _merge_kbinfos' dseen set). +// +// Separate from Merge, whose early return on an empty chunk list would skip them: +// the search tool must record a search's aggregations even when every chunk it +// returned was already pooled. +func (k *Kbinfos) MergeDocAggs(aggs []map[string]any) { + if len(aggs) == 0 { + return + } + dseen := make(map[string]bool, len(k.DocAggs)+len(aggs)) + for _, d := range k.DocAggs { + dseen[docAggKey(d)] = true + } + for _, d := range aggs { + key := docAggKey(d) + if dseen[key] { + continue + } + dseen[key] = true + k.DocAggs = append(k.DocAggs, d) + } +} + +// docAggKey mirrors Python's dedup key for doc_aggs: the raw doc_id, with a +// missing/empty doc_id mapping to "" (so only the first such agg is kept). +func docAggKey(d map[string]any) string { + if id, ok := d["doc_id"].(string); ok { + return id + } + return "" +} + +// indexOfChunk returns the global index of the chunk whose key matches kk. +func indexOfChunk(chunks []map[string]any, kk string) int { + for i, c := range chunks { + if chunkKey(c) == kk { + return i + } + } + return -1 +} + +// chunkText mirrors Python harness/chunk_utils._chunk_text: the searchable +// text of a chunk, preferring the weighted (reranked) "content_with_weight" +// over the raw "content", then falling back to "text". Python's root +// chunk_utils._chunk_text and grep_sed_narrow._chunk_text both read in this +// order; memory._chunk_text is a two-level variant (no "text") and is NOT what +// this mirrors. +func chunkText(c map[string]any) string { + if t, ok := c["content_with_weight"].(string); ok && t != "" { + return t + } + if t, ok := c["content"].(string); ok && t != "" { + return t + } + if t, ok := c["text"].(string); ok { + return t + } + return "" +} + +// chunkKey returns a stable dedup key for a chunk. Prefers chunk_id/id when +// present; otherwise falls back to a content-derived key so chunks without an +// id still dedup correctly (and never collide on a shared empty key). +// +// This diverges from Python _chunk_key (`chunk_id or id or id(ck)`): Python's +// final fallback is `id(ck)` — the dict object's memory address — which means +// two equivalent chunks returned as distinct objects never share a key, so +// deduplication silently fails for id-less chunks. Go instead keys on the chunk +// text, so identical content still merges across retrieval calls. +func chunkKey(c map[string]any) string { + if id, ok := c["chunk_id"].(string); ok && id != "" { + return "cid:" + id + } + if id, ok := c["id"].(string); ok && id != "" { + return "id:" + id + } + content := "" + if t, ok := c["content_with_weight"].(string); ok { + content = t + } else if t, ok := c["content"].(string); ok { + content = t + } + if content == "" { + // No stable identity: fall back to the doc reference so at least + // per-document grouping is preserved (rarely reached). + content = fmt.Sprintf("%s|%s", anyString(c["doc_id"]), anyString(c["docnm_kwd"])) + } + return "h:" + fnv64(content) +} + +func anyString(v any) string { + if s, ok := v.(string); ok { + return s + } + return "" +} + +// fnv64 is a deterministic non-crypto hash for dedup keys. +func fnv64(s string) string { + h := uint64(14695981039346656037) + for i := 0; i < len(s); i++ { + h ^= uint64(s[i]) + h *= 1099511628211 + } + return fmt.Sprintf("%016x", h) +} diff --git a/internal/rag/advanced_rag/harness/kbinfos_test.go b/internal/rag/advanced_rag/harness/kbinfos_test.go new file mode 100644 index 00000000000..2dc7209e5e9 --- /dev/null +++ b/internal/rag/advanced_rag/harness/kbinfos_test.go @@ -0,0 +1,51 @@ +package harness + +import "testing" + +// TestMergeSkipsAllWhenNoChunks mirrors Python _merge_kbinfos's early return: +// `if not result or not result.get("chunks"): return`. When the incoming chunk +// list is empty, neither chunks nor doc_aggs are merged, and the call returns +// nil (no global indices contributed). +func TestMergeSkipsAllWhenNoChunks(t *testing.T) { + kb := &Kbinfos{DocAggs: []map[string]any{{"doc_id": "d1"}}} + added := kb.Merge(nil, []map[string]any{{"doc_id": "d2"}}) + if added != nil { + t.Fatalf("Merge with no chunks should return nil, got %v", added) + } + if len(kb.DocAggs) != 1 { + t.Fatalf("doc_aggs must not be merged without chunks, got %d", len(kb.DocAggs)) + } + if len(kb.Chunks) != 0 { + t.Fatalf("chunks should stay empty, got %d", len(kb.Chunks)) + } +} + +// TestMergeCollapsesEmptyDocIDAggs mirrors Python's doc_agg dedup: the dseen set +// is built from the raw doc_id value, so a missing/None doc_id still enters the +// set and a second empty-doc_id agg is dropped. Only the first is kept. +func TestMergeCollapsesEmptyDocIDAggs(t *testing.T) { + kb := &Kbinfos{} + added := kb.Merge( + []map[string]any{{"id": "c1"}}, + []map[string]any{{"name": "a"}, {"name": "b"}, {"name": "c"}}, + ) + if len(added) != 1 { + t.Fatalf("added = %v, want 1 chunk index", added) + } + if len(kb.DocAggs) != 1 { + t.Fatalf("empty-doc_id aggs should collapse to 1, got %d", len(kb.DocAggs)) + } + if kb.DocAggs[0]["name"] != "a" { + t.Fatalf("first empty-doc_id agg should be kept, got %v", kb.DocAggs[0]) + } +} + +// TestMergeDedupsSameDocID mirrors Python's exact-match dedup for real doc_ids, +// independent of the empty bucket above. +func TestMergeDedupsSameDocID(t *testing.T) { + kb := &Kbinfos{} + kb.Merge([]map[string]any{{"id": "c1"}}, []map[string]any{{"doc_id": "x"}, {"doc_id": "x"}}) + if len(kb.DocAggs) != 1 { + t.Fatalf("same-doc_id aggs should dedup, got %d", len(kb.DocAggs)) + } +} diff --git a/internal/rag/advanced_rag/harness/keywords.go b/internal/rag/advanced_rag/harness/keywords.go new file mode 100644 index 00000000000..283da15aeda --- /dev/null +++ b/internal/rag/advanced_rag/harness/keywords.go @@ -0,0 +1,294 @@ +// +// 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. +// + +package harness + +import ( + "context" + "fmt" + "regexp" + "strings" + + "github.com/cloudwego/eino/schema" + + "ragflow/internal/agent/chat" +) + +// Four-aspect keyword extraction with entity weighting. +// +// Mirrors Python harness/keywords.py. +// +// A keyword search matches only the surface forms you give it, so a single flat +// bag of terms is a poor retrieval driver: the model does not know how the corpus +// phrases a fact. This extraction asks the LLM for FOUR aspects — `entity` (what +// the fact is about), `aliases` (its surface variants), `fact_type` (words the +// corpus might use for this kind of fact, including table column abbreviations) +// and `qualifiers` (year / edition / jurisdiction / revision). +// +// `entity` is what discriminates, so it is repeated in the search query to weight +// BM25 toward it; the plain deduped union of all four aspects is used to narrow +// retrieved chunks to their keyword-bearing sentences. + +const ( + // keywordEntityRepeat is copies of each entity term in the query + // (Python: _KEYWORD_ENTITY_REPEAT). + keywordEntityRepeat = 3 + // keywordQualifierRepeat is copies of each qualifier, weighted up like entity + // (Python: _KEYWORD_QUALIFIER_REPEAT). + keywordQualifierRepeat = 3 + // keywordMaxChars caps both strings (Python: _KEYWORD_MAX_CHARS). + keywordMaxChars = 400 +) + +// keywordAspects is the aspect order. Entity and qualifiers are the weighted +// pair; aliases and fact_type find/boost but must not dominate. +var keywordAspects = []string{"entity", "aliases", "fact_type", "qualifiers"} + +// KeywordsSystem mirrors keywords.py::_KEYWORDS_SYSTEM. +const KeywordsSystem = `You turn ONE question into search terms for a keyword/BM25 search engine. + +Emit the terms that would appear VERBATIM in a document that answers the question, sorted into FOUR +categories. Every term must come from the question itself or be a surface form of something in it. + +A. "entity" — the specific thing the fact is ABOUT: proper nouns, titles, identifiers. Keep a + multi-word entity whole, as ONE term ("Brown County", "Treaty of Versailles"); split across + several terms its tokens match independently and drag in noise. A bare identifier — a serial, + patent, catalogue or case number — is a complete entity on its own; never glue it to the words + around it. +B. "aliases" — the engine matches ONLY the surface forms you supply, so emit the plausible variants + of A: full vs. short name, native-language and transliterated forms, official vs. common name, + acronym and its expansion, and the qualified form ("Brown County" -> "Brown County, Kansas"). +C. "fact_type" — 3 to 6 words the corpus might use for this KIND of fact, since you cannot know how + it is phrased. Spread them across registers: + quantity of people -> population, inhabitants, residents, census, demographics, headcount + time of an event -> founded, established, opened, dated, began + role of a person -> served, appointed, elected, held, director + SOURCES TABULATE WHAT QUESTIONS SPELL OUT: a statistic named in prose is usually written in a + table as a column abbreviation, and the prose wording may not appear in the document at all. So + include the abbreviation a table would use — "points per game" -> "PPG", "PTS"; "earnings per + share" -> "EPS"; "games played" -> "GP" — and reach a superlative through its plain column too: + "leading scorer" is found by looking for "PTS" and "PPG", not for the phrase itself. +D. "qualifiers" — year, edition, jurisdiction, revision. Worth emitting even when it looks + redundant: the qualifier often sits in a table header or a document title that chunking has + severed from the value. Include EVERY alternative expression of a DATE or NUMBER in the + question — ordinals and their words ("21st" -> "twenty-first"), digits and their words + ("2000000" -> "two million", "2 million"), and each common date format ("Aug 2nd" -> "August 2", + "2 August", "08-02"). + +A and B are what FINDS the document; C and D only boost the ranking. So never withhold an entity +because you are unsure of it, and never pad C or D to reach a count. + +DROP entirely: question words ("which", "who", "when", "how many"), relational scaffolding, and +generic high-frequency nouns ("year", "number", "city", "total", "list", "information"). They cost +ranking quality and retrieve nothing. + +Output ONLY JSON, no prose, no code fences: +{"entity": ["", ...], "aliases": ["", ...], "fact_type": ["", ...], "qualifiers": ["", ...]} +Any category may be empty.` + +// normKeyword mirrors Python _norm_keyword: normalise a term for cross-category +// dedup (lowercase, whitespace-collapsed). +func normKeyword(s string) string { + return strings.Join(strings.Fields(strings.ToLower(s)), " ") +} + +// parseAspects mirrors Python _parse_aspects: parse the LLM's JSON into one +// deduped list per aspect. +// +// ONE dedup set spans all four categories: a term the model emits as both an +// entity and an alias must not collect a second share of the query's mass on the +// strength of having been named twice. +func parseAspects(raw string) map[string][]string { + data, _ := ExtractJSON(StripThinkAndFences(raw)).(map[string]any) + aspects := map[string][]string{} + seen := map[string]bool{} + for _, aspect := range keywordAspects { + var terms []string + for _, k := range asAspectList(data[aspect]) { + term := strings.TrimSpace(fmt.Sprint(k)) + key := normKeyword(term) + if term == "" || key == "" || seen[key] { + continue + } + seen[key] = true + terms = append(terms, term) + } + aspects[aspect] = terms + } + return aspects +} + +// asAspectList tolerates the shapes models emit for an aspect: a list of +// strings, a list of mixed values, or a single comma-separated string. +func asAspectList(v any) []any { + switch t := v.(type) { + case []any: + return t + case []string: + out := make([]any, 0, len(t)) + for _, s := range t { + out = append(out, s) + } + return out + case string: + out := make([]any, 0, 4) + for _, s := range strings.Split(t, ",") { + out = append(out, s) + } + return out + } + return nil +} + +// reThinkWrap matches a leading ... preamble. +var reThinkWrap = regexp.MustCompile(`(?s)^.*`) + +// StripThinkAndFences removes a leading thinking preamble and Markdown fences. +// Exported so the harness (compute.go, keywords.go) and the advanced_rag package's +// moved Formalize can share one implementation. +func StripThinkAndFences(s string) string { + s = reThinkWrap.ReplaceAllString(s, "") + s = reFencedJSON.ReplaceAllString(s, "$1") + return strings.TrimSpace(s) +} + +// ExtractWeightedKeywords mirrors Python extract_weighted_keywords: extract the +// four aspects and return (query, keywords). +// +// - query is the weighted search string: every entity term repeated x3 and +// every qualifier repeated x3, so BM25 weights both inside the same query; +// aliases and fact-type vocabulary appear once each. +// - keywords is the plain deduped union of all four aspects (one copy each), +// used to narrow retrieved chunks to their keyword-bearing sentences. +// +// Falls back to (question, question) when extraction fails — keyword extraction +// is an enhancement, never a precondition for retrieval. +func ExtractWeightedKeywords(ctx context.Context, model SessionModel, question string) (string, string) { + if question == "" { + return "", "" + } + aspects := map[string][]string{} + if model != nil { + // Mirror Python keywords.py:extract_weighted_keywords — form_message(_KEYWORDS_SYSTEM, + // question) is run through message_fit_in(..., llm.max_length) before + // the call, so an over-long question is trimmed to the model context + // window exactly as in Python. The chat seam exposes llm.max_length via + // ContextLengthModel; when no context window is available the + // chat.EffectiveContextLength(0) default (8192) applies, exactly as + // Python's LLM.max_length default. + budget := 0 + if cl, ok := model.(ContextLengthModel); ok { + budget = cl.ContextLength() + } + if budget <= 0 { + budget = chat.EffectiveContextLength(0) + } + fitted, fitErr := chat.FitMessages(KeywordsSystem, []schema.Message{ + *schema.UserMessage(question), + }, budget) + if fitErr != "" { + _LOG.Printf("[Keywords] prompt fitting failed: %s", fitErr) + } + // FitMessages may prepend/trim a system message; re-extract it so the + // model call is exactly [system, user...] as Python sends msg[0] then + // msg[1:]. + systemPrompt := KeywordsSystem + if len(fitted) > 0 && fitted[0].Role == schema.System { + systemPrompt = fitted[0].Content + } + userContent := question + for _, m := range fitted { + if m.Role == schema.User { + userContent = m.Content + break + } + } + msgs := []schema.Message{ + *schema.SystemMessage(systemPrompt), + *schema.UserMessage(userContent), + } + // Temperature (one intentional seam vs Python): Python hardcodes + // {"temperature": 0.1} — a mechanical rewrite, not a reasoning task, so + // it must be stable. Go mirrors that exactly WHEN the model implements + // TemperatureModel by calling CompleteWithTemperature(ctx, msgs, nil, 0.1). + // Models that do NOT support per-call temperature fall back to the plain + // Complete and therefore run at the model's own default temperature. We + // deliberately prefer widest compatibility over a literal 0.1: forcing + // 0.1 unconditionally would make keyword extraction error out on models + // without temperature control. (Documented seam, not a bug — see + // HARNESS.md.) + var reply *ModelReply + var err error + if tm, ok := model.(TemperatureModel); ok { + reply, err = tm.CompleteWithTemperature(ctx, msgs, nil, 0.1) + } else { + reply, err = model.Complete(ctx, msgs, nil) + } + if err == nil { + aspects = parseAspects(reply.Content) + } else { + _LOG.Printf("[Keywords] extraction failed: %v", err) + } + } + + // Plain union, one copy each — used for narrowing. + var union []string + for _, aspect := range keywordAspects { + union = append(union, aspects[aspect]...) + } + keywords := strings.Join(union, ", ") + if keywords == "" { + keywords = question + } + + // Weighted query: entity x3, qualifiers x3, then aliases + fact_type once. + var weighted []string + for _, t := range aspects["entity"] { + for i := 0; i < keywordEntityRepeat; i++ { + weighted = append(weighted, t) + } + } + for _, t := range aspects["qualifiers"] { + for i := 0; i < keywordQualifierRepeat; i++ { + weighted = append(weighted, t) + } + } + for _, aspect := range []string{"aliases", "fact_type"} { + weighted = append(weighted, aspects[aspect]...) + } + query := strings.Join(weighted, ", ") + if query == "" { + query = keywords + } + + // Python keywords.py has NO term-count cap — only the _KEYWORD_MAX_CHARS (400) + // hard cap on the final joined strings. We mirror exactly that: only the + // character cap is applied, never a per-term limit. + query = truncateRunes(query, keywordMaxChars) + keywords = truncateRunes(keywords, keywordMaxChars) + + _LOG.Printf("[Keywords] entity x%d: %s | aliases: %s | fact-type: %s | qualifiers x%d: %s", + keywordEntityRepeat, joinOrDash(aspects["entity"]), joinOrDash(aspects["aliases"]), + joinOrDash(aspects["fact_type"]), keywordQualifierRepeat, joinOrDash(aspects["qualifiers"])) + return query, keywords +} + +func joinOrDash(ss []string) string { + if len(ss) == 0 { + return "-" + } + return strings.Join(ss, "; ") +} diff --git a/internal/rag/advanced_rag/harness/keywords_test.go b/internal/rag/advanced_rag/harness/keywords_test.go new file mode 100644 index 00000000000..04c016a28f6 --- /dev/null +++ b/internal/rag/advanced_rag/harness/keywords_test.go @@ -0,0 +1,191 @@ +// +// 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. +// + +package harness + +import ( + "context" + "errors" + "strings" + "testing" + + "github.com/cloudwego/eino/schema" +) + +func TestNormKeyword(t *testing.T) { + cases := map[string]string{ + "Brown County": "brown county", + " OMIYA Soft ": "omiya soft", + "": "", + } + for in, want := range cases { + if got := normKeyword(in); got != want { + t.Errorf("normKeyword(%q) = %q, want %q", in, got, want) + } + } +} + +func TestParseAspectsDedupsAcrossCategories(t *testing.T) { + // ONE dedup set spans all four categories: a term emitted as both an entity + // and an alias must not collect a second share of the query's mass purely + // for having been named twice. + raw := `{"entity": ["Brown County", "Kansas"], "aliases": ["brown county", "Brown County, Kansas"], + "fact_type": ["population", "census"], "qualifiers": ["2020"]}` + got := parseAspects(raw) + if len(got["entity"]) != 2 { + t.Errorf("entity = %v, want 2 terms", got["entity"]) + } + // "brown county" (alias) is dropped: already seen as an entity. + if len(got["aliases"]) != 1 || got["aliases"][0] != "Brown County, Kansas" { + t.Errorf("aliases = %v, want only the qualified form", got["aliases"]) + } + if len(got["fact_type"]) != 2 || len(got["qualifiers"]) != 1 { + t.Errorf("fact_type/qualifiers = %v/%v", got["fact_type"], got["qualifiers"]) + } +} + +func TestParseAspectsToleratesShapesAndGarbage(t *testing.T) { + // A comma-separated string instead of a list. + got := parseAspects(`{"entity": "OmiyaSoft, Culdcept", "aliases": []}`) + if len(got["entity"]) != 2 { + t.Errorf("string form = %v, want 2 terms", got["entity"]) + } + // Unparseable / empty input yields empty aspects, never a panic. + for _, raw := range []string{"", "not json", "```json {broken```", "[]", "null"} { + got := parseAspects(raw) + for _, aspect := range keywordAspects { + if len(got[aspect]) != 0 { + t.Errorf("parseAspects(%q) produced %s=%v, want empty", raw, aspect, got[aspect]) + } + } + } +} + +func TestExtractWeightedKeywordsWeighting(t *testing.T) { + mdl := &fakeModel{replies: []*ModelReply{{ + Content: `{"entity": ["Brown County"], "aliases": ["Brown County, Kansas"], + "fact_type": ["population", "census"], "qualifiers": ["2020"]}`, + }}} + query, keywords := ExtractWeightedKeywords(context.Background(), mdl, "What is the population of Brown County?") + + // query: entity x3, qualifiers x3, then aliases + fact_type once each. + // NOTE: the alias "Brown County, Kansas" itself contains a comma, so a naive + // split on ", " over-counts — Python joins the same way and BM25 tokenises + // on whitespace, so this is expected. Assert by prefix/containment. + if !strings.HasPrefix(query, "Brown County, Brown County, Brown County, ") { + t.Errorf("query = %q, want the entity repeated x3 first", query) + } + if !strings.Contains(query, "2020, 2020, 2020") { + t.Errorf("query = %q, want the qualifier repeated x3", query) + } + for _, want := range []string{"Brown County, Kansas", "population", "census"} { + if !strings.Contains(query, want) { + t.Errorf("query = %q, missing %q (aliases/fact_type appear once)", query, want) + } + } + // keywords: plain union, one copy each, in aspect order. + wantKeys := "Brown County, Brown County, Kansas, population, census, 2020" + if keywords != wantKeys { + t.Errorf("keywords = %q, want %q", keywords, wantKeys) + } +} + +func TestExtractWeightedKeywordsFallsBackToQuestion(t *testing.T) { + q := "Who created Culdcept?" + // No model at all. + query, keywords := ExtractWeightedKeywords(context.Background(), nil, q) + if query != q || keywords != q { + t.Errorf("no model = (%q,%q), want the question for both", query, keywords) + } + // A model that fails. + query, keywords = ExtractWeightedKeywords(context.Background(), &errModel{}, q) + if query != q || keywords != q { + t.Errorf("failed model = (%q,%q), want the question for both", query, keywords) + } + // A model that returns nothing usable. + query, keywords = ExtractWeightedKeywords(context.Background(), + &fakeModel{replies: []*ModelReply{{Content: "garbage"}}}, q) + if query != q || keywords != q { + t.Errorf("garbage reply = (%q,%q), want the question for both", query, keywords) + } + // Empty question. + if a, b := ExtractWeightedKeywords(context.Background(), &fakeModel{}, ""); a != "" || b != "" { + t.Errorf("empty question = (%q,%q), want empty", a, b) + } +} + +func TestExtractWeightedKeywordsCapsLength(t *testing.T) { + // A pathological term set must be capped, not truncate mid-term into + // something that still pollutes the query. + var terms []string + for i := 0; i < 100; i++ { + terms = append(terms, "term"+strings.Repeat("x", 10)+string(rune('a'+i%26))) + } + list := `["` + strings.Join(terms, `", "`) + `"]` + mdl := &fakeModel{replies: []*ModelReply{{ + Content: `{"entity": ` + list + `, "aliases": [], "fact_type": [], "qualifiers": []}`, + }}} + query, keywords := ExtractWeightedKeywords(context.Background(), mdl, "q") + if len(query) > keywordMaxChars { + t.Errorf("query = %d chars, want <= %d", len(query), keywordMaxChars) + } + if len(keywords) > keywordMaxChars { + t.Errorf("keywords = %d chars, want <= %d", len(keywords), keywordMaxChars) + } +} + +func TestTemperatureModelExtension(t *testing.T) { + // Keyword extraction runs at 0.1 in Python. The Go seam exposes temperature + // through an OPTIONAL interface so existing SessionModel implementations + // keep working unchanged. + im := &InvokerSessionModel{} + var _ TemperatureModel = im // must implement the extension + + // A model that is not a TemperatureModel must still work (falls back). + mdl := &fakeModel{replies: []*ModelReply{{ + Content: `{"entity": ["Culdcept"], "aliases": [], "fact_type": [], "qualifiers": []}`, + }}} + query, _ := ExtractWeightedKeywords(context.Background(), mdl, "q") + if !strings.Contains(query, "Culdcept") { + t.Errorf("non-temperature model: query = %q, want the entity weighted in", query) + } +} + +// errModel implements SessionModel but always fails Complete, so the +// keyword-extraction fallback path (no model usable) can be exercised. +type errModel struct{} + +func (errModel) Complete(_ context.Context, _ []schema.Message, _ []ToolSpec) (*ModelReply, error) { + return nil, errors.New("simulated model failure") +} + +// fakeModel replays a scripted sequence of replies so control flow can be +// driven without a provider. Shared by the keyword and arithmetic tests. +type fakeModel struct { + replies []*ModelReply + calls int + messages []schema.Message +} + +func (f *fakeModel) Complete(_ context.Context, msgs []schema.Message, _ []ToolSpec) (*ModelReply, error) { + f.messages = msgs + if f.calls >= len(f.replies) { + return &ModelReply{Content: `{"new_states": []}`}, nil + } + r := f.replies[f.calls] + f.calls++ + return r, nil +} diff --git a/internal/rag/advanced_rag/harness/memory.go b/internal/rag/advanced_rag/harness/memory.go new file mode 100644 index 00000000000..b738af57789 --- /dev/null +++ b/internal/rag/advanced_rag/harness/memory.go @@ -0,0 +1,498 @@ +// +// 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. +// + +package harness + +import ( + "regexp" + "sort" + "strings" + "unicode" +) + +// Raw-chunk memory store. +// +// Mirrors Python harness/memory.py, which maintains the lossless store backing +// the (lossy) kbinfos.Chunks list that feeds the LLM. Retrieval narrows chunks +// to the sentences that answer the current query, so the raw text has to be +// kept somewhere: a later gap query often needs a fact the earlier narrowing +// already threw away. +// +// The store lives on Kbinfos.Memory so it travels with the request. + +const ( + // grepMaxChunks caps how many chunks one grep returns (Python + // memory._GREP_MAX_CHUNKS = 6). + grepMaxChunks = 6 + // grepMaxSentences caps sentences kept per chunk (hit + context). + grepMaxSentences = 4 + // grepContextChars is the per-side char budget when expanding context. + grepContextChars = 400 + // shortChunkChars: chunks at or below this length are kept whole, since + // answers often live in short chunks. + shortChunkChars = 200 + + // MemorySearch tuning — mirror Python memory.search defaults. + memoryDefaultTopN = 6 + // memoryMinRatio: a chunk is relevant when it shares >= 1 term AND >= this + // fraction of the query's significant terms (normalized overlap bar so CN / + // EN queries behave alike). Python's min_overlap param is declared but + // unused in search(), so only the ratio matters. + memoryMinRatio = 0.12 + // memoryMaxTerms caps how many significant terms we extract from a query. + memoryMaxTerms = 18 +) + +var ( + // reTermPunct strips leading/trailing punctuation before escaping. + reTermPunct = regexp.MustCompile(`^[\s.,:;!?'"()\[\]{}]+|[\s.,:;!?'"()\[\]{}]+$`) + // reCJK detects CJK / kana / hangul, which get no \b anchor (a word boundary + // never matches between CJK characters). + reCJK = regexp.MustCompile(`[\x{4e00}-\x{9fff}\x{3040}-\x{30ff}\x{ac00}-\x{d7af}]`) + // reCJKRun matches a maximal run of CJK/kana/hangul for 3-gram splitting. + reCJKRun = regexp.MustCompile(`[\x{4e00}-\x{9fff}\x{3040}-\x{30ff}\x{ac00}-\x{d7af}]+`) + // reLatinNum matches a maximal alphanumeric run (Latin words + numbers). + reLatinNum = regexp.MustCompile(`[A-Za-z0-9]+`) + // reDigits matches a pure digit run. + reDigits = regexp.MustCompile(`\d+`) +) + +// memoryStopwords mirrors Python memory._STOPWORDS: dropped from Latin query +// terms so "what / the / is" style words do not dominate the overlap score. +var memoryStopwords = map[string]struct{}{ + "what": {}, "which": {}, "how": {}, "many": {}, "much": {}, "does": {}, + "did": {}, "do": {}, "the": {}, "a": {}, "an": {}, "is": {}, "are": {}, + "was": {}, "were": {}, "be": {}, "been": {}, "being": {}, "of": {}, + "for": {}, "to": {}, "in": {}, "on": {}, "with": {}, "and": {}, "or": {}, + "by": {}, "from": {}, "at": {}, "it": {}, "its": {}, "this": {}, "that": {}, + "these": {}, "those": {}, "who": {}, "when": {}, "where": {}, "why": {}, + "than": {}, "then": {}, "there": {}, "their": {}, "they": {}, "them": {}, + "his": {}, "her": {}, "him": {}, "she": {}, "he": {}, "we": {}, "you": {}, + "your": {}, +} + +// MemoryAdd mirrors Python memory.add: merges raw retrieved chunks into the +// central store, losslessly, skipping chunks already present and those with no +// text. +func MemoryAdd(kb *Kbinfos, chunks []map[string]any) { + if kb == nil || len(chunks) == 0 { + return + } + seen := make(map[string]struct{}, len(kb.Memory)) + for _, c := range kb.Memory { + seen[chunkKey(c)] = struct{}{} + } + added := 0 + for _, c := range chunks { + if c == nil || chunkText(c) == "" { + continue + } + k := chunkKey(c) + if _, dup := seen[k]; dup { + continue + } + seen[k] = struct{}{} + kb.Memory = append(kb.Memory, c) + added++ + } + if added > 0 { + _LOG.Printf("[Memory] stored %d new raw chunk(s); memory now has %d.", added, len(kb.Memory)) + } +} + +// MemorySize mirrors Python memory.size. +func MemorySize(kb *Kbinfos) int { + if kb == nil { + return 0 + } + return len(kb.Memory) +} + +// MemoryClear mirrors Python memory.clear. +func MemoryClear(kb *Kbinfos) { + if kb != nil { + kb.Memory = nil + } +} + +// MemoryGrep mirrors Python memory.grep: returns memory chunks containing any of +// terms, narrowed to the matching sentence plus a small context window. +// +// terms are plain strings (entities / numbers / key phrases) as emitted by the +// analysis LLM. Each returned chunk carries a narrowed "content" so the caller +// can splice it straight into an evidence list. Empty on no-hit / no-memory. +func MemoryGrep(kb *Kbinfos, terms []string, limit int) []map[string]any { + if kb == nil || len(kb.Memory) == 0 || len(terms) == 0 { + return nil + } + if limit <= 0 { + limit = grepMaxChunks + } + patterns, prefixPatterns := compileTerms(terms) + if len(patterns) == 0 && len(prefixPatterns) == 0 { + return nil + } + match := func(text string) bool { + for _, p := range patterns { + if p.MatchString(text) { + return true + } + } + // Prefix fallback: morphological tolerance. A gap term often differs from + // the chunk's word by a suffix (gap "abbreviation" vs chunk "abbreviated"). + // Matching the leading stem at the START of a word lets a shared root hit. + for _, p := range prefixPatterns { + if p.MatchString(text) { + return true + } + } + return false + } + + var hits []map[string]any + for _, c := range kb.Memory { + text := chunkText(c) + if len(text) <= shortChunkChars { + // Short chunk: keep whole (its answer may live anywhere in it). + if match(text) { + hits = append(hits, map[string]any{ + "content": text, + "doc_id": c["doc_id"], + "chunk_id": c["chunk_id"], + }) + } + continue + } + sents := SplitSentences(text) + var kept []string + for i, s := range sents { + if match(s) { + for _, w := range sentenceSpanWindow(sents, i) { + if !containsStr(kept, w) { + kept = append(kept, w) + } + } + } + if len(kept) >= grepMaxSentences { + break + } + } + if len(kept) > 0 { + hits = append(hits, map[string]any{ + "content": strings.Join(kept, "\n"), + "doc_id": c["doc_id"], + "chunk_id": c["chunk_id"], + }) + } + if len(hits) >= limit { + break + } + } + return hits +} + +// compileTerms mirrors Python memory.grep's pattern construction: the escaped +// term (word-anchored when it is long enough and wholly alphanumeric) plus the +// leading-stem prefix pattern used as a fallback. +func compileTerms(terms []string) (patterns, prefixPatterns []*regexp.Regexp) { + for _, t := range terms { + if frag := escapeTerm(t); frag != "" { + if p, err := regexp.Compile("(?i)" + frag); err == nil { + patterns = append(patterns, p) + } + } + stripped := strings.TrimSpace(t) + prefix := "" + if len([]rune(stripped)) >= 6 { + prefix = string([]rune(stripped)[:5]) + } + if prefix != "" && !reCJK.MatchString(prefix) { + if p, err := regexp.Compile(`(?i)\b` + regexp.QuoteMeta(prefix)); err == nil { + prefixPatterns = append(prefixPatterns, p) + } + } + } + return patterns, prefixPatterns +} + +// escapeTerm mirrors Python _escape_term: strip surrounding punctuation, escape +// regex metacharacters, then anchor on word boundaries — except for CJK, where +// a \b anchor would never match. +func escapeTerm(term string) string { + t := strings.TrimSpace(term) + if t == "" { + return "" + } + t = reTermPunct.ReplaceAllString(t, "") + if t == "" { + return "" + } + escaped := regexp.QuoteMeta(t) + if reCJK.MatchString(t) { + return escaped + } + rs := []rune(t) + if len(rs) >= 3 && isAlnum(rs[0]) && isAlnum(rs[len(rs)-1]) { + return `\b` + escaped + `\b` + } + return escaped +} + +// sentenceSpanWindow mirrors Python _sentence_span_window: the hit sentence plus +// up to one neighbour on each side, clamped to a total length. +func sentenceSpanWindow(sents []string, idx int) []string { + if idx < 0 || idx >= len(sents) { + return nil + } + lo, hi := max(0, idx-1), min(len(sents), idx+2) + total := 0 + var kept []string + for _, s := range sents[lo:hi] { + total += len(s) + if total > grepContextChars*2 { + break + } + kept = append(kept, s) + } + if len(kept) == 0 { + return []string{sents[idx]} + } + return kept +} + +func isAlnum(r rune) bool { + return unicode.IsLetter(r) || unicode.IsDigit(r) +} + +func containsStr(ss []string, s string) bool { + for _, v := range ss { + if v == s { + return true + } + } + return false +} + +// MemorySearch mirrors Python memory.search: relevance-ranked retrieval over the +// raw-chunk memory store (a retrieval-reuse cache, NOT a noise-injection source). +// Unlike MemoryGrep (loose keyword hit) it keeps only chunks whose overlap with the +// query's SIGNIFICANT terms clears a normalized bar, so a fact retrieved earlier can +// be reused instead of re-querying the index. +// +// Language-agnostic term extraction (mirrors Python _significant_terms): +// - numbers kept verbatim; +// - CJK runs split into character 3-grams (no word boundaries exist); +// - Latin alphanumeric runs lowercased, stopword-filtered, len >= 3. +// +// A chunk is relevant when it shares >= 1 term AND >= minRatio of the query's +// significant terms; results are ranked by hit count then text length, capped at +// topN. Returns nil when nothing clears the bar (the caller falls back to a +// knowledge-base search). minRatio <= 0 falls back to memoryMinRatio. +func MemorySearch(kb *Kbinfos, query string, topN int, minRatio float64) []map[string]any { + if kb == nil || len(kb.Memory) == 0 { + return nil + } + if topN <= 0 { + topN = memoryDefaultTopN + } + if minRatio <= 0 { + minRatio = memoryMinRatio + } + terms := significantTerms(query) + if len(terms) == 0 { + return nil + } + matchers := buildTermMatchers(terms) + n := len(terms) + + type scoredChunk struct { + hits int + text string + c map[string]any + } + var scored []scoredChunk + for _, c := range kb.Memory { + text := chunkText(c) + if text == "" { + continue + } + hits := 0 + for _, m := range matchers { + if m.matches(text) { + hits++ + } + } + if hits < 1 { + continue + } + if float64(hits)/float64(n) < minRatio { + continue + } + scored = append(scored, scoredChunk{hits: hits, text: text, c: c}) + } + if len(scored) == 0 { + return nil + } + // Rank by hit count desc, then text length desc (Python: (-hits, -len)). + sort.SliceStable(scored, func(i, j int) bool { + if scored[i].hits != scored[j].hits { + return scored[i].hits > scored[j].hits + } + return len(scored[i].text) > len(scored[j].text) + }) + if len(scored) > topN { + scored = scored[:topN] + } + out := make([]map[string]any, 0, len(scored)) + for _, s := range scored { + out = append(out, map[string]any{ + "content": s.text, + "doc_id": s.c["doc_id"], + "chunk_id": s.c["chunk_id"], + "similarity": float64(s.hits), + }) + } + rq := []rune(query) + if len(rq) > 60 { + rq = rq[:60] + } + _LOG.Printf("[Memory.search] query=%q -> %d relevant chunk(s) (ratio>=%.2f, %d terms)", string(rq), len(out), minRatio, n) + return out +} + +// significantTerms mirrors Python memory._significant_terms: language-agnostic +// significant-term extraction, de-duplicated and capped at memoryMaxTerms. +func significantTerms(text string) []string { + var out []string + seen := make(map[string]struct{}) + push := func(tok string) { + if tok == "" { + return + } + if _, dup := seen[tok]; dup { + return + } + seen[tok] = struct{}{} + out = append(out, tok) + } + // Numbers anywhere. + for _, m := range reDigits.FindAllString(text, -1) { + push(m) + if len(out) >= memoryMaxTerms { + return out + } + } + // CJK runs -> 3-grams (and the whole run if shorter than 3). + for _, run := range reCJKRun.FindAllString(text, -1) { + rs := []rune(run) + if len(rs) < 3 { + push(run) + } else { + for i := 0; i+3 <= len(rs); i++ { + push(string(rs[i : i+3])) + } + } + if len(out) >= memoryMaxTerms { + return out + } + } + // Latin words (stopword-filtered, len >= 3); pure-digit runs already handled. + for _, m := range reLatinNum.FindAllString(text, -1) { + if isAllDigits(m) { + continue + } + low := strings.ToLower(m) + if len(low) >= 3 { + if _, stop := memoryStopwords[low]; !stop { + push(low) + } + } + if len(out) >= memoryMaxTerms { + return out + } + } + return out +} + +// termMatcher precompiles one query term's match predicate so MemorySearch +// does not recompile regexes per chunk. +type termMatcher struct { + // kind: 0 = CJK substring, 1 = digit substring, 2 = Latin word-boundary + // (with a short prefix fallback for inflectional variants). + kind int + sub string + re *regexp.Regexp + pre *regexp.Regexp +} + +func buildTermMatchers(terms []string) []termMatcher { + matchers := make([]termMatcher, 0, len(terms)) + for _, t := range terms { + if run := reCJKRun.FindString(t); run != "" && run == t { + // Pure CJK term: literal substring (no word boundary). + matchers = append(matchers, termMatcher{kind: 0, sub: t}) + continue + } + if isAllDigits(t) { + matchers = append(matchers, termMatcher{kind: 1, sub: t}) + continue + } + rs := []rune(t) + re, _ := regexp.Compile(`(?i)\b` + regexp.QuoteMeta(t) + `\b`) + var pre *regexp.Regexp + if len(rs) >= 6 { + pre, _ = regexp.Compile(`(?i)\b` + regexp.QuoteMeta(string(rs[:5]))) + } + matchers = append(matchers, termMatcher{kind: 2, re: re, pre: pre}) + } + return matchers +} + +func (m termMatcher) matches(text string) bool { + switch m.kind { + case 0, 1: + return strings.Contains(text, m.sub) + default: + if m.re != nil && m.re.MatchString(text) { + return true + } + if m.pre != nil && m.pre.MatchString(text) { + return true + } + return false + } +} + +// IsStopword reports whether w is one of Python memory._STOPWORDS. +// +// Go's fan-out needs it because Python aliases the same set as +// _FANOUT_STOPWORDS (agentic_rag_graph.py:_expand_fanouts) when filtering candidate terms. +func IsStopword(w string) bool { + _, ok := memoryStopwords[w] + return ok +} + +func isAllDigits(s string) bool { + if s == "" { + return false + } + for _, r := range s { + if r < '0' || r > '9' { + return false + } + } + return true +} diff --git a/internal/rag/advanced_rag/harness/memory_test.go b/internal/rag/advanced_rag/harness/memory_test.go new file mode 100644 index 00000000000..971df797587 --- /dev/null +++ b/internal/rag/advanced_rag/harness/memory_test.go @@ -0,0 +1,114 @@ +// +// 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. +// + +package harness + +import "testing" + +func memChunk(content, docID, chunkID string) map[string]any { + return map[string]any{"content": content, "doc_id": docID, "chunk_id": chunkID} +} + +// Python memory.search returns the chunks that share enough of the query's +// significant terms; unrelated queries return nothing. +func TestMemorySearchReturnsRelevant(t *testing.T) { + kb := &Kbinfos{Memory: []map[string]any{ + memChunk("Rifampicin is an antibiotic used to treat tuberculosis.", "d1", "c1"), + memChunk("The Eiffel Tower is a wrought-iron lattice tower in Paris.", "d2", "c2"), + }} + // "rifampicin" / "tuberculosis" both hit chunk c1 only. + hits := MemorySearch(kb, "What is rifampicin used for in tuberculosis treatment?", 0, 0) + if len(hits) != 1 { + t.Fatalf("hits = %d, want 1", len(hits)) + } + if hits[0]["chunk_id"] != "c1" { + t.Errorf("top hit chunk_id = %v, want c1", hits[0]["chunk_id"]) + } + if _, ok := hits[0]["similarity"]; !ok { + t.Errorf("hit missing similarity field") + } + + // Unrelated query clears nothing. + if got := MemorySearch(kb, "How many moons does Jupiter have?", 0, 0); got != nil { + t.Errorf("unrelated query should return nil, got %d hits", len(got)) + } +} + +// The normalized overlap bar must drop a chunk that matches too few of a long +// query's terms (mirrors Python's (hits/_n) >= min_ratio guard). +func TestMemorySearchRatioBar(t *testing.T) { + kb := &Kbinfos{Memory: []map[string]any{ + memChunk("Rifampicin is an antibiotic.", "d1", "c1"), + }} + // Query has many significant terms (9) but the chunk shares only + // "rifampicin" -> 1/9 ~= 0.111 < the 0.12 default ratio, so it clears + // nothing. + q := "rifampicin airplane bicycle coffee mountain ocean planet quarter river" + if got := MemorySearch(kb, q, 0, 0); got != nil { + t.Errorf("below-ratio query should return nil, got %d hits", len(got)) + } + + // Lowering the ratio lets the same single-term hit through. + if got := MemorySearch(kb, q, 0, 0.1); len(got) != 1 { + t.Errorf("ratio 0.1 should keep the hit, got %d", len(got)) + } +} + +// CJK queries match via character 3-grams, just like the Python implementation. +func TestMemorySearchCJKTrigram(t *testing.T) { + kb := &Kbinfos{Memory: []map[string]any{ + memChunk("利福平是一种抗生素,用于治疗结核病。", "d1", "c1"), + memChunk("巴黎的埃菲尔铁塔是著名的铁制建筑。", "d2", "c2"), + }} + hits := MemorySearch(kb, "利福平治疗什么疾病?", 0, 0) + if len(hits) != 1 || hits[0]["chunk_id"] != "c1" { + t.Errorf("CJK 3-gram search failed: got %d hits, want 1 (c1)", len(hits)) + } +} + +// Ranking: more term hits ranks higher; equal hits then prefer longer text. +func TestMemorySearchRanking(t *testing.T) { + kb := &Kbinfos{Memory: []map[string]any{ + memChunk("Rifampicin treats tuberculosis and leprosy.", "d1", "low"), + memChunk("Rifampicin is an antibiotic for tuberculosis and also used for leprosy and meningitis.", "d2", "high"), + }} + hits := MemorySearch(kb, "rifampicin tuberculosis leprosy", 0, 0) + if len(hits) != 2 { + t.Fatalf("hits = %d, want 2", len(hits)) + } + if hits[0]["chunk_id"] != "high" { + t.Errorf("top ranked chunk_id = %v, want high (more hits / longer)", hits[0]["chunk_id"]) + } +} + +// chunkText must prefer "content_with_weight" over "content", mirroring Python +// harness/chunk_utils._chunk_text (content_with_weight or content or text), so a +// chunk carrying both yields the weighted text. +func TestChunkTextPrefersWeighted(t *testing.T) { + c := map[string]any{ + "content": "primary text", + "content_with_weight": "weighted text", + } + if got := chunkText(c); got != "weighted text" { + t.Errorf("chunkText = %q, want %q (Python prefers content_with_weight)", got, "weighted text") + } + + // Falls back to content when content_with_weight is absent/empty. + c2 := map[string]any{"content": "primary only"} + if got := chunkText(c2); got != "primary only" { + t.Errorf("chunkText = %q, want %q", got, "primary only") + } +} diff --git a/internal/rag/advanced_rag/harness/orchestrator/direct.go b/internal/rag/advanced_rag/harness/orchestrator/direct.go new file mode 100644 index 00000000000..ba8041b0b74 --- /dev/null +++ b/internal/rag/advanced_rag/harness/orchestrator/direct.go @@ -0,0 +1,50 @@ +// +// 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. +// + +// Package orchestrator holds the top-level pipeline stages that sit above the +// action session: the Sufficient Context Agent (SCA) review and the gap→query +// rewriter. +// +// Mirrors Python rag/advanced_rag/harness/orchestrator/{sufficient_context, +// query_rewriter}.py. +// +// Python's orchestrator/direct.py — the low-mode direct search — deliberately +// has no counterpart in this package: its Go implementation is runDirect +// (agentic_rag.go, called from the low graph's direct_search node), the low graph +// node's body, because that step needs the full RAGTools config rather than a +// harness-level dependency bundle. One implementation only; its contract is +// pinned by TestBuildLowGraphRunsFormalizeThenDirectSearch. +package orchestrator + +import ( + "context" + "fmt" + + "ragflow/internal/common" +) + +var _LOG = common.StdLogger() + +// JSONModel generates one JSON object from a rendered prompt. +// +// Mirrors Python rag.prompts.generator.gen_json(prompt, "Output:\n", chat_mdl), +// which sends the prompt as the system turn, "Output:\n" as the user turn, and +// parses the first JSON value out of the reply. +type JSONModel interface { + GenJSON(ctx context.Context, prompt string) (any, error) +} + +func fmtClaimCount(n int) string { return fmt.Sprintf("%d claim draft(s)", n) } diff --git a/internal/rag/advanced_rag/harness/orchestrator/query_rewriter.go b/internal/rag/advanced_rag/harness/orchestrator/query_rewriter.go new file mode 100644 index 00000000000..e51c57ada5f --- /dev/null +++ b/internal/rag/advanced_rag/harness/orchestrator/query_rewriter.go @@ -0,0 +1,126 @@ +// +// 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. +// + +package orchestrator + +import ( + "context" + "fmt" + "strings" + + "ragflow/internal/rag/advanced_rag/harness" + "ragflow/internal/rag/prompts" +) + +// Query rewriter (Phase 4 of the pipeline). +// +// Mirrors Python orchestrator/query_rewriter.py::rewrite_gap_to_query. +// + +// RewriteDeps are the dependencies of RewriteGapToQuery. +type RewriteDeps struct { + // Model generates the JSON object. + Model JSONModel + // Prompts supplies the "sca_query_rewrite" template. + Prompts harness.PromptLoader + // BridgeValues are already-resolved values across the claims (e.g. the + // confirmed shows in a "which finale ran longest" question). The rewriter + // anchors the new query to these, so a missing hop is re-searched with the + // resolved upstream value instead of re-deriving it. + BridgeValues []string + // ResearchContext is the rendered block describing what previous rounds + // already tried (queries + outcomes) and what the evidence pool contains. + // It lets the rewriter aim at UNCOVERED angles instead of paraphrasing dead + // ones. + ResearchContext string +} + +// RewriteGapToQuery mirrors Python rewrite_gap_to_query. +// +// gaps are (what, search_hint) tuples — the forward gaps the SCA identified. +// +// Returns [{"query": "..."}] — targeted, retrievable queries. Empty when the +// rewrite is unavailable or fails, in which case the caller falls back to the +// original gap text. +func RewriteGapToQuery(ctx context.Context, deps RewriteDeps, question string, gaps []MissingPiece) []map[string]string { + if deps.Model == nil || len(gaps) == 0 { + return nil + } + // Python wraps the call in @in_phase("rewrite"). + ctx, done := harness.Phase(ctx, harness.PhaseRewrite) + defer done() + + var gapsLines []string + for _, g := range gaps { + gapsLines = append(gapsLines, fmt.Sprintf("- what: %s; hint: %s", g.What, g.SearchHint)) + } + gapsText := strings.Join(gapsLines, "\n") + + var bridgeLines []string + for _, b := range deps.BridgeValues { + if strings.TrimSpace(b) != "" { + bridgeLines = append(bridgeLines, "- "+b) + } + } + bridgeText := strings.Join(bridgeLines, "\n") + + prompt := prompts.Render(deps.Prompts, "sca_query_rewrite", "", map[string]string{ + "question": question, + "gaps": gapsText, + "bridge_values": bridgeText, + "research_context": deps.ResearchContext, + }) + + result, err := deps.Model.GenJSON(ctx, prompt) + if err != nil { + _LOG.Printf("[QueryRewrite] failed: %v", err) + return nil + } + data, ok := result.(map[string]any) + if !ok { + return nil + } + rawQueries, _ := data["queries"].([]any) + + var out []map[string]string + for _, q := range rawQueries { + var query string + if m, ok := q.(map[string]any); ok { + // Accept `query` (canonical) or `question` (observed drift). + if v := m["query"]; v != nil { + query = strings.TrimSpace(fmt.Sprint(v)) + } else if v := m["question"]; v != nil { + query = strings.TrimSpace(fmt.Sprint(v)) + } + } else if q != nil { + query = strings.TrimSpace(fmt.Sprint(q)) + } + if query == "" || containsQuery(out, query) { + continue + } + out = append(out, map[string]string{"query": query}) + } + return out +} + +func containsQuery(queries []map[string]string, q string) bool { + for _, item := range queries { + if item["query"] == q { + return true + } + } + return false +} diff --git a/internal/rag/advanced_rag/harness/orchestrator/query_rewriter_test.go b/internal/rag/advanced_rag/harness/orchestrator/query_rewriter_test.go new file mode 100644 index 00000000000..099de7a2099 --- /dev/null +++ b/internal/rag/advanced_rag/harness/orchestrator/query_rewriter_test.go @@ -0,0 +1,107 @@ +// +// 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. +// + +package orchestrator + +import ( + "context" + "errors" + "strings" + "testing" +) + +func TestRewriteGapToQueryNeedsModelAndGaps(t *testing.T) { + mdl := &stubJSONModel{value: map[string]any{"queries": []any{"q1"}}} + if got := RewriteGapToQuery(context.Background(), RewriteDeps{Model: mdl}, "q", nil); got != nil { + t.Error("no gaps must short-circuit") + } + if mdl.calls != 0 { + t.Error("no gaps must not call the model") + } + if got := RewriteGapToQuery(context.Background(), RewriteDeps{}, "q", + []MissingPiece{{What: "x"}}); got != nil { + t.Error("no model must return nil") + } +} + +func TestRewriteGapToQueryParsesAndDedupes(t *testing.T) { + mdl := &stubJSONModel{value: map[string]any{"queries": []any{ + map[string]any{"query": "MASH finale run time minutes"}, + map[string]any{"question": "Cheers finale run time minutes"}, // key drift + "plain string query", + map[string]any{"query": "MASH finale run time minutes"}, // duplicate + map[string]any{"query": " "}, // blank + }}} + got := RewriteGapToQuery(context.Background(), RewriteDeps{Model: mdl}, "which finale ran longest?", + []MissingPiece{{What: "runtimes", SearchHint: "finale run time"}}) + if len(got) != 3 { + t.Fatalf("queries = %d, want 3 (blank + duplicate dropped)", len(got)) + } + if got[0]["query"] != "MASH finale run time minutes" { + t.Errorf("queries[0] = %q", got[0]["query"]) + } + if got[1]["query"] != "Cheers finale run time minutes" { + t.Errorf("queries[1] = %q, want the 'question' key accepted", got[1]["query"]) + } + if got[2]["query"] != "plain string query" { + t.Errorf("queries[2] = %q", got[2]["query"]) + } +} + +func TestRewriteGapToQueryRendersAllVars(t *testing.T) { + mdl := &stubJSONModel{value: map[string]any{"queries": []any{}}} + RewriteGapToQuery(context.Background(), RewriteDeps{ + Model: mdl, + Prompts: nil, // resolves the embedded sca_query_rewrite.md + BridgeValues: []string{"M*A*S*H", "Cheers", " "}, + ResearchContext: "tried: finale runtimes (nothing new)", + }, "which finale ran longest?", + []MissingPiece{{What: "runtimes", SearchHint: "finale run time"}}) + + // The canonical template uses the spaced Jinja form, and every var must be + // substituted (an unreplaced {{ }} would corrupt the prompt). + if strings.Contains(mdl.last, "{{") { + t.Errorf("unsubstituted placeholder remains: %.200s", mdl.last) + } + for _, want := range []string{"which finale ran longest?", "- M*A*S*H", "- Cheers", + "what: runtimes; hint: finale run time", "tried: finale runtimes"} { + if !strings.Contains(mdl.last, want) { + t.Errorf("prompt missing %q", want) + } + } + // Blank bridge values are dropped. + if strings.Contains(mdl.last, "- ") { + t.Error("blank bridge value must be dropped") + } +} + +func TestRewriteGapToQueryReturnsNilOnFailure(t *testing.T) { + mdl := &stubJSONModel{err: errors.New("provider down")} + if got := RewriteGapToQuery(context.Background(), RewriteDeps{Model: mdl}, "q", + []MissingPiece{{What: "x"}}); got != nil { + t.Error("a model failure must return nil so the caller falls back") + } + // A non-dict response is also "no signal". + mdl = &stubJSONModel{value: []any{"not", "a", "dict"}} + if got := RewriteGapToQuery(context.Background(), RewriteDeps{Model: mdl}, "q", + []MissingPiece{{What: "x"}}); got != nil { + t.Error("a non-dict response must return nil") + } +} + +// --------------------------------------------------------------------------- +// Prompt rendering +// --------------------------------------------------------------------------- diff --git a/internal/rag/advanced_rag/harness/orchestrator/sufficient_context.go b/internal/rag/advanced_rag/harness/orchestrator/sufficient_context.go new file mode 100644 index 00000000000..33cbd456c5d --- /dev/null +++ b/internal/rag/advanced_rag/harness/orchestrator/sufficient_context.go @@ -0,0 +1,599 @@ +// +// 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. +// + +package orchestrator + +import ( + "context" + "fmt" + "regexp" + "strings" + + "ragflow/internal/rag/advanced_rag/harness" + "ragflow/internal/rag/prompts" +) + +// Unified Sufficient Context Agent. +// +// Mirrors Python orchestrator/sufficient_context.py. +// +// The SCA performs ONE review pass over (1) each claim's intermediate draft and +// (2) the overall draft assembled from them, and returns a unified verdict: +// is_sufficient / confidence / contradictions / reasoning / claims / sub_queries. +// It replaced an earlier two-call split (global verdict + per-claim groundedness) +// whose trigger bands were complementary, so the three-part review rarely +// happened in one shot. +// +// The SCA reviews ONLY the claims' reports, never the raw retrieved chunks. +// Each report is an evidence-backed finding already distilled from that claim's +// evidence; sending raw chunks ballooned the prompt to 20k-100k chars, which +// degraded the LLM (empty claims) or timed it out. + +const ( + // scaClaimsContextMax caps the rendered claims context (all per-claim + // reports + the overall draft). Sized to match the action session's context + // budget (maxToolResponseChars * 4) so a table-bearing evidence anchor plus + // several claim reports still fit. + scaClaimsContextMax = 48000 + // scaEvidenceAnchorChars is the max chars of each cited snippet kept as an + // evidence anchor, so the SCA can verify a draft against real retrieved text + // without a token blow-up. + scaEvidenceAnchorChars = 300 + // scaMaxAnchorsPerClaim bounds anchors per claim (Python: `if len(anchors) >= 3`). + scaMaxAnchorsPerClaim = 3 + // feedbackMax bounds the missing pieces folded into the boost feedback string. + feedbackMax = 4 +) + +var reHintToken = regexp.MustCompile(`[A-Za-z0-9_\x{4e00}-\x{9fff}]{3,}`) + +// ClaimDraft is one claim's intermediate draft plus the evidence it cited. +// +// EvidenceIDs are INDICES into Kbinfos.Chunks (see Kbinfos.Merge, which returns +// global indices) — NOT the chunk's chunk_id hash. Keying the anchor lookup by +// chunk_id would make every anchor a miss and silently disable the "SCA reviews +// the retrieved snippets" guard. +type ClaimDraft struct { + ID string + Draft string + EvidenceIDs []string +} + +// SubQuery is one step-by-step sub-question with its coverage verdict (Q-CARE). +// Unsatisfied entries carry the concrete missing fact + a search hint — the +// precise "what is missing / where to search next" signal the next round +// consumes. +type SubQuery struct { + SubQuery string + Satisfied bool + MissingFact string + SearchHint string +} + +// MissingPiece mirrors Python's {"what", "search_hint"}. +type MissingPiece struct { + What string + SearchHint string +} + +// ClaimVerdict is the SCA's per-claim verdict. +type ClaimVerdict struct { + Grounded bool + Ungrounded []string + MissingInformation []MissingPiece +} + +// SCAResult is the unified verdict. An empty result means "no new signal", +// which callers must treat as neither sufficient nor insufficient. +type SCAResult struct { + IsSufficient bool + Confidence float64 + Contradictions []string + Reasoning string + SubQueries []SubQuery + Claims map[string]ClaimVerdict +} + +// SCADeps are the dependencies of the SCA. +type SCADeps struct { + KB *harness.Kbinfos + // Model generates the JSON verdict. + Model JSONModel + // Prompts supplies the "sca_select" template. + Prompts harness.PromptLoader +} + +// SufficientContextAgent mirrors Python sufficient_context_agent. +// +// claims carries per-claim evidence (not the global union): rendering only the +// snippets each claim cited keeps the prompt small (~1-3 chunks per claim) so +// the LLM does not degrade, while the cited snippets still carry the +// answer-bearing facts. +// +// Returns an empty SCAResult when unavailable (no claims, no model, or a +// failure) — callers treat that as "no new signal". +func SufficientContextAgent(ctx context.Context, deps SCADeps, question string, claims []ClaimDraft) SCAResult { + if len(claims) == 0 || deps.Model == nil { + return SCAResult{} + } + // Python wraps the review in @in_phase("sca"). + ctx, done := harness.Phase(ctx, harness.PhaseSCA) + defer done() + + claimsContext := renderClaimContext(claims, deps.KB) + if claimsContext == "" || claimsContext == "(no claim drafts)" { + return SCAResult{} + } + overallDraft := renderOverallDraft(claims) + + prompt := prompts.Render(deps.Prompts, "sca_select", "", map[string]string{ + "question": question, + "claims_context": claimsContext, + "overall_draft": overallDraft, + }) + _LOG.Printf("[SCA] unified review of %s (reports only, %d chars; overall draft %d chars)", + fmtClaimCount(len(claims)), len(claimsContext), len(overallDraft)) + + result, err := deps.Model.GenJSON(ctx, prompt) + if err != nil { + _LOG.Printf("[SCA] unified review failed: %v", err) + return SCAResult{} + } + data := coerceDict(result) + if data == nil { + _LOG.Printf("[SCA] no usable response; treating as no signal") + return SCAResult{} + } + + // Per-claim verdicts. + claimsOut := map[string]ClaimVerdict{} + if rawClaims, ok := data["claims"].([]any); ok { + for _, item := range rawClaims { + m, ok := item.(map[string]any) + if !ok { + continue + } + cid := strings.TrimSpace(fmt.Sprint(m["claim_id"])) + if cid == "" { + continue + } + var ungrounded []string + for _, u := range asSlice(m["ungrounded_assertions"]) { + if um, ok := u.(map[string]any); ok { + if s := strings.TrimSpace(fmt.Sprint(firstNonEmpty(um["assertion"], um["reason"]))); s != "" { + ungrounded = append(ungrounded, s) + } + } else if s := strings.TrimSpace(fmt.Sprint(u)); s != "" { + ungrounded = append(ungrounded, s) + } + } + claimsOut[cid] = ClaimVerdict{ + Grounded: truthy(m["grounded"]), + Ungrounded: ungrounded, + MissingInformation: parseMissingInformation(m["missing_information"]), + } + } + } + + // Structured sub-query coverage (Q-CARE). + var subQueries []SubQuery + for _, sq := range asSlice(data["sub_queries"]) { + m, ok := sq.(map[string]any) + if !ok { + continue + } + sqText := strings.TrimSpace(fmt.Sprint(m["sub_query"])) + if sqText == "" { + continue + } + entry := SubQuery{SubQuery: sqText, Satisfied: truthy(m["satisfied"])} + if !entry.Satisfied { + entry.MissingFact = strings.TrimSpace(fmt.Sprint(m["missing_fact"])) + entry.SearchHint = strings.TrimSpace(fmt.Sprint(m["search_hint"])) + } + subQueries = append(subQueries, entry) + } + + isSufficient := truthy(data["is_sufficient"]) + + // Failsafe: the SCA judged the context insufficient but returned an EMPTY + // claims array (a known degradation on very long prompts). Without a gap, the + // orchestrator would abandon with "I don't have enough information" despite + // having retrieved useful snippets. Harvest top-level missing_information, and + // fall back to the un-verified drafts themselves as coarse gaps. + if !isSufficient && len(claimsOut) == 0 { + topMissing := parseMissingInformation(data["missing_information"]) + if len(topMissing) > 0 { + claimsOut["_global"] = ClaimVerdict{Grounded: false, MissingInformation: topMissing} + _LOG.Printf("[SCA] insufficient with empty claims; using %d top-level missing piece(s) as the re-search gap.", len(topMissing)) + } else { + var draftGaps []MissingPiece + for _, c := range claims { + if d := strings.TrimSpace(c.Draft); d != "" { + draftGaps = append(draftGaps, MissingPiece{What: d, SearchHint: d}) + } + } + if len(draftGaps) > 0 { + claimsOut["_global"] = ClaimVerdict{Grounded: false, MissingInformation: draftGaps} + _LOG.Printf("[SCA] insufficient with no structured gap; deriving %d coarse gap(s) from the drafts.", len(draftGaps)) + } + } + } + + return SCAResult{ + IsSufficient: isSufficient, + Confidence: clamp(data["confidence"]), + Contradictions: stringList(data["contradictions"]), + Reasoning: strings.TrimSpace(fmt.Sprint(data["reasoning"])), + SubQueries: subQueries, + Claims: claimsOut, + } +} + +// Boost mirrors Python to_boost: adapt the unified verdict into the +// decision-ladder boost dict, preserving the contract +// (is_sufficient / confidence / missing / contradictions / feedback / +// followups) that the existing ladder consumes unchanged. +func (s SCAResult) Boost(fallbackFollowups []string) Boost { + var missing []string + for _, g := range s.Claims { + for _, mi := range g.MissingInformation { + w := strings.TrimSpace(mi.What) + if w != "" && !containsStr(missing, w) { + missing = append(missing, w) + } + } + } + feedback := "" + if len(missing) > 0 { + n := min(len(missing), feedbackMax) + feedback = "missing: " + strings.Join(missing[:n], "; ") + } + return Boost{ + IsSufficient: s.IsSufficient, + Confidence: s.Confidence, + Missing: missing, + Contradictions: s.Contradictions, + Followups: fallbackFollowups, + Feedback: feedback, + SubQueries: s.SubQueries, + } +} + +// Boost is the decision-ladder input produced by SCAResult.Boost. +type Boost struct { + IsSufficient bool + Confidence float64 + Missing []string + Contradictions []string + Followups []string + Feedback string + // SubQueries is the structured Q-CARE coverage signal consumed by replan. + SubQueries []SubQuery +} + +// ToGrounded mirrors Python to_grounded: adapt the unified verdict into the +// `grounded` dict consumed by replan and the ungrounded-veto path +// ({claim_id: {grounded, ungrounded, missing_information}}). +func (s SCAResult) ToGrounded() map[string]ClaimVerdict { return s.Claims } + +// --------------------------------------------------------------------------- +// Rendering helpers +// --------------------------------------------------------------------------- + +// renderClaimContext mirrors Python _render_claim_context: each claim's report +// PLUS a brief evidence anchor (the first line of each cited snippet), so the +// SCA can verify the draft is grounded in real retrieved text. +func renderClaimContext(claims []ClaimDraft, kb *harness.Kbinfos) string { + if len(claims) == 0 { + return "(no claim drafts)" + } + // Key by INDEX into kbinfos chunks (see the ClaimDraft doc comment). + id2chunk := map[string]map[string]any{} + if kb != nil { + for i, c := range kb.Chunks { + id2chunk[fmt.Sprint(i)] = c + } + } + var blocks []string + used := 0 + for _, c := range claims { + if c.Draft == "" { + continue + } + block := fmt.Sprintf("Claim %s (draft):\n%s", c.ID, c.Draft) + used += len(block) + 2 + var anchors []string + for _, eid := range c.EvidenceIDs { + ck, ok := id2chunk[strings.TrimSpace(eid)] + if !ok { + continue + } + txt := strings.TrimSpace(scaChunkText(ck)) + if txt == "" { + continue + } + // Table chunks contribute their FULL text: hint-token windowing is + // unreliable for tables (the draft rarely contains the row's entity + // names) and head-truncation hides answer rows that sit mid-table. + if ex := boundedExcerpt(txt, c.Draft, scaEvidenceAnchorChars); ex != "" { + anchors = append(anchors, ex) + } + if len(anchors) >= scaMaxAnchorsPerClaim { + break + } + } + if len(anchors) > 0 { + anchorText := strings.Join(anchors, " | ") + block += "\n Evidence: " + anchorText + used += len(anchorText) + 4 + } + blocks = append(blocks, block) + if used >= scaClaimsContextMax { + break + } + } + if len(blocks) == 0 { + return "(no claim drafts)" + } + return strings.Join(blocks, "\n\n") +} + +// renderOverallDraft mirrors Python _render_overall_draft: assemble the +// problem-level "rough draft" by concatenating each claim's report, so the SCA +// can judge whether the context lets the model answer end-to-end — including +// cross-claim synthesis that per-claim review would miss. +func renderOverallDraft(claims []ClaimDraft) string { + if len(claims) == 0 { + return "(no overall draft)" + } + var parts []string + for _, c := range claims { + if d := strings.TrimSpace(c.Draft); d != "" { + parts = append(parts, fmt.Sprintf("[Claim %s] %s", c.ID, d)) + } + } + if len(parts) == 0 { + return "(no overall draft)" + } + draft := strings.Join(parts, "\n") + if len(draft) > scaClaimsContextMax { + draft = draft[:scaClaimsContextMax] + } + return draft +} + +// scaChunkText mirrors Python sufficient_context.py:_render_claim_context: prefer the reranked +// "content_with_weight" over the raw "content", then fall back to "chunk". This +// differs from harness.chunkText (which prefers content and keeps a Go-only +// "text" fallback): the SCA evidence anchor must read the SAME text Python did +// so the groundedness guard resolves the same snippets. +func scaChunkText(c map[string]any) string { + if v, ok := c["content_with_weight"]; ok && v != nil { + if s := fmt.Sprint(v); s != "" { + return s + } + } + if v, ok := c["content"]; ok && v != nil { + if s := fmt.Sprint(v); s != "" { + return s + } + } + if v, ok := c["chunk"]; ok && v != nil { + return fmt.Sprint(v) + } + return "" +} + +// boundedExcerpt mirrors Python _bounded_excerpt: a bounded window around a +// term from the draft. Table text is returned whole. +func boundedExcerpt(text, hints string, maxChars int) string { + text = strings.TrimSpace(text) + if text == "" { + return "" + } + if isTableText(text) { + return text + } + if maxChars < 80 { + maxChars = 80 + } + // Work in runes (code points), exactly like Python's str[:] / len() / find(): + // a byte-based slice would mis-count and split a multibyte (e.g. CJK) rune, + // emitting invalid UTF-8. + r := []rune(text) + lower := strings.ToLower(text) + start := -1 + for _, tok := range reHintToken.FindAllString(hints, -1) { + if pos := strings.Index(lower, strings.ToLower(tok)); pos >= 0 { + // pos is a byte offset in text; convert to a rune index. + start = len([]rune(text[:pos])) + break + } + } + n := len(r) + if start < 0 { + if n <= maxChars { + return text + } + tail := maxChars / 2 + return string(r[:maxChars-tail]) + " … " + string(r[n-tail:]) + } + half := maxChars / 2 + left := max(0, start-half) + right := min(n, left+maxChars) + left = max(0, right-maxChars) + prefix, suffix := "", "" + if left > 0 { + prefix = "…" + } + if right < n { + suffix = "…" + } + return prefix + string(r[left:right]) + suffix +} + +// isTableText mirrors Python _is_table_text: a corpus-neutral table detector — +// HTML table markup, or >=3 pipe rows. +func isTableText(text string) bool { + t := strings.ToLower(text) + if strings.Contains(t, "= 2 { + pipeRows++ + } + } + return pipeRows >= 3 +} + +// --------------------------------------------------------------------------- +// Coercion helpers +// --------------------------------------------------------------------------- + +// coerceDict mirrors Python _coerce_dict: tolerate model format drift. The +// reviewer occasionally replies with a bare array or a JSON string; previously +// any non-dict response was dropped, so the SCA produced NO signal on those +// rounds and replan/rewrite silently stopped. +func coerceDict(v any) map[string]any { + switch t := v.(type) { + case map[string]any: + return t + case []any: + for _, item := range t { + if m, ok := item.(map[string]any); ok { + return m + } + } + return nil + case string: + if parsed := harness.ExtractJSON(t); parsed != nil { + return coerceDict(parsed) + } + return nil + } + return nil +} + +// clamp mirrors Python _clamp: coerce to [0,1], defaulting to 1.0 on failure. +func clamp(v any) float64 { + f, ok := toFloat(v) + if !ok { + return 1.0 + } + if f < 0 { + return 0 + } + if f > 1 { + return 1 + } + return f +} + +// truthy mirrors Python's builtin bool() on the raw JSON value, exactly as the +// Python sufficient_context path evaluates these fields (e.g. +// bool(item.get("grounded")), bool(result.get("is_sufficient"))). Python's bool() +// treats ANY non-empty string as truthy — including the literal "false" or "0" — +// because they are non-empty. We must not string-parse booleans here, or a model +// that returns grounded:"false" as a string would wrongly collapse to False while +// Python keeps it True. Only an empty string / 0 / nil / False is falsy. +func truthy(v any) bool { + switch t := v.(type) { + case bool: + return t + case string: + return t != "" + case float64: + return t != 0 + case int: + return t != 0 + case int64: + return t != 0 + case nil: + return false + } + return true +} + +func parseMissingInformation(v any) []MissingPiece { + var out []MissingPiece + for _, m := range asSlice(v) { + if mm, ok := m.(map[string]any); ok { + what := strings.TrimSpace(fmt.Sprint(mm["what"])) + hint := strings.TrimSpace(fmt.Sprint(mm["search_hint"])) + if what != "" || hint != "" { + out = append(out, MissingPiece{What: what, SearchHint: hint}) + } + } else if s := strings.TrimSpace(fmt.Sprint(m)); s != "" { + out = append(out, MissingPiece{What: s}) + } + } + return out +} + +func stringList(v any) []string { + var out []string + for _, item := range asSlice(v) { + if s := strings.TrimSpace(fmt.Sprint(item)); s != "" { + out = append(out, s) + } + } + return out +} + +func asSlice(v any) []any { + list, _ := v.([]any) + return list +} + +func firstNonEmpty(v ...any) string { + for _, item := range v { + if item == nil { + continue + } + if s := strings.TrimSpace(fmt.Sprint(item)); s != "" { + return s + } + } + return "" +} + +func containsStr(ss []string, s string) bool { + for _, v := range ss { + if v == s { + return true + } + } + return false +} + +func toFloat(v any) (float64, bool) { + switch n := v.(type) { + case float64: + return n, true + case float32: + return float64(n), true + case int: + return float64(n), true + case int64: + return float64(n), true + case string: + return harness.ParseFloat(n) + } + return 0, false +} diff --git a/internal/rag/advanced_rag/harness/orchestrator/sufficient_context_test.go b/internal/rag/advanced_rag/harness/orchestrator/sufficient_context_test.go new file mode 100644 index 00000000000..90593a69429 --- /dev/null +++ b/internal/rag/advanced_rag/harness/orchestrator/sufficient_context_test.go @@ -0,0 +1,276 @@ +// +// 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. +// + +package orchestrator + +import ( + "context" + "strings" + "testing" + "unicode/utf8" + + "ragflow/internal/rag/advanced_rag/harness" +) + +// stubJSONModel returns a canned JSON value (or an error), and records the last +// prompt it was shown. +type stubJSONModel struct { + value any + err error + calls int + last string +} + +func (s *stubJSONModel) GenJSON(_ context.Context, prompt string) (any, error) { + s.calls++ + s.last = prompt + if s.err != nil { + return nil, s.err + } + return s.value, nil +} + +// --------------------------------------------------------------------------- +// SCA +// --------------------------------------------------------------------------- + +func TestSCAReturnsNoSignalWithoutClaims(t *testing.T) { + mdl := &stubJSONModel{value: map[string]any{"is_sufficient": true}} + got := SufficientContextAgent(context.Background(), SCADeps{ + KB: &harness.Kbinfos{}, + Model: mdl, + }, "q", nil) + if mdl.calls != 0 { + t.Error("no claims must short-circuit before any LLM call") + } + if got.IsSufficient || got.Claims != nil { + t.Error("no claims must yield an empty result (no signal)") + } +} + +func TestSCAParsesUnifiedVerdict(t *testing.T) { + mdl := &stubJSONModel{value: map[string]any{ + "is_sufficient": false, + "confidence": 0.42, + "contradictions": []any{"X says 1999, Y says 2001"}, + "reasoning": "missing the release year", + "sub_queries": []any{ + map[string]any{"sub_query": "release year", "satisfied": false, + "missing_fact": "the year", "search_hint": "Culdcept release date"}, + map[string]any{"sub_query": "developer", "satisfied": true}, + }, + "claims": []any{ + map[string]any{"claim_id": "c1", "grounded": false, + "missing_information": []any{map[string]any{"what": "release year", "search_hint": "Culdcept 1999"}}}, + }, + }} + got := SufficientContextAgent(context.Background(), SCADeps{ + KB: &harness.Kbinfos{}, + Model: mdl, + }, "q", []ClaimDraft{{ID: "c1", Draft: "OmiyaSoft made it"}}) + + if got.IsSufficient { + t.Error("is_sufficient must be false") + } + if got.Confidence != 0.42 { + t.Errorf("confidence = %v, want 0.42", got.Confidence) + } + if len(got.Contradictions) != 1 || got.Contradictions[0] != "X says 1999, Y says 2001" { + t.Errorf("contradictions = %v", got.Contradictions) + } + if len(got.SubQueries) != 2 { + t.Fatalf("sub_queries = %d, want 2", len(got.SubQueries)) + } + if got.SubQueries[0].Satisfied || got.SubQueries[0].MissingFact != "the year" { + t.Errorf("sub_query[0] = %+v", got.SubQueries[0]) + } + if !got.SubQueries[1].Satisfied { + t.Error("sub_query[1] must be satisfied") + } + cv, ok := got.Claims["c1"] + if !ok { + t.Fatal("claim c1 missing from verdicts") + } + if cv.Grounded { + t.Error("claim c1 must be ungrounded") + } + if len(cv.MissingInformation) != 1 || cv.MissingInformation[0].What != "release year" { + t.Errorf("missing_information = %+v", cv.MissingInformation) + } +} + +func TestSCACoercesArrayAndStringDrift(t *testing.T) { + // Model drift: a bare array, or a JSON string, must still yield a verdict + // instead of being dropped (which would silently stop replan/rewrite). + for name, value := range map[string]any{ + "array": []any{map[string]any{"is_sufficient": true, "confidence": 0.9}}, + "string": `{"is_sufficient": true, "confidence": 0.7}`, + } { + mdl := &stubJSONModel{value: value} + got := SufficientContextAgent(context.Background(), SCADeps{ + KB: &harness.Kbinfos{}, + Model: mdl, + }, "q", []ClaimDraft{{ID: "c1", Draft: "d"}}) + if !got.IsSufficient { + t.Errorf("%s drift: verdict lost", name) + } + } +} + +func TestSCADerivesGapWhenInsufficientWithEmptyClaims(t *testing.T) { + // Failsafe: insufficient + empty claims array (a known degradation on long + // prompts) must still produce a gap, else the orchestrator abandons despite + // having usable evidence. + mdl := &stubJSONModel{value: map[string]any{ + "is_sufficient": false, + "missing_information": []any{map[string]any{"what": "the year", "search_hint": "1999"}}, + }} + got := SufficientContextAgent(context.Background(), SCADeps{ + KB: &harness.Kbinfos{}, + Model: mdl, + }, "q", []ClaimDraft{{ID: "c1", Draft: "OmiyaSoft made it"}}) + g, ok := got.Claims["_global"] + if !ok { + t.Fatal("top-level missing_information must be harvested as the _global gap") + } + if len(g.MissingInformation) != 1 || g.MissingInformation[0].What != "the year" { + t.Errorf("gap = %+v", g.MissingInformation) + } + + // No structured gap at all: fall back to the drafts themselves. + mdl = &stubJSONModel{value: map[string]any{"is_sufficient": false}} + got = SufficientContextAgent(context.Background(), SCADeps{ + KB: &harness.Kbinfos{}, + Model: mdl, + }, "q", []ClaimDraft{{ID: "c1", Draft: "OmiyaSoft made it"}}) + g, ok = got.Claims["_global"] + if !ok || len(g.MissingInformation) == 0 { + t.Fatal("draft-derived fallback gap missing") + } + if g.MissingInformation[0].What != "OmiyaSoft made it" { + t.Errorf("fallback gap = %q, want the draft text", g.MissingInformation[0].What) + } +} + +func TestSCAEvidenceAnchorsUseChunkIndices(t *testing.T) { + // EvidenceIDs are INDICES into Kbinfos.Chunks (not chunk_id hashes) — that + // indexing is what makes anchor lookup hit. + kb := &harness.Kbinfos{Chunks: []map[string]any{ + {"content": "Culdcept was released in 1999 by OmiyaSoft."}, + }} + contextText := renderClaimContext([]ClaimDraft{ + {ID: "c1", Draft: "OmiyaSoft made Culdcept", EvidenceIDs: []string{"0"}}, + }, kb) + if !strings.Contains(contextText, "1999") { + t.Errorf("anchor not resolved from index 0; got %q", contextText) + } + // An out-of-range index is simply skipped. + if s := renderClaimContext([]ClaimDraft{{ID: "c1", Draft: "d", EvidenceIDs: []string{"99"}}}, kb); strings.Contains(s, "Evidence:") { + t.Error("unknown evidence index must not produce an anchor") + } +} + +func TestBoundedExcerptKeepsTablesWhole(t *testing.T) { + table := "| a | b |\n| c | d |\n| e | f |\n| g | h |" + if got := boundedExcerpt(table, "unrelated hint", 50); got != table { + t.Errorf("table text must be returned whole, got %q", got) + } + // Prose is windowed around a hint token. + prose := strings.Repeat("prefix filler ", 40) + "TARGET sentence here" + strings.Repeat(" trailing filler", 40) + got := boundedExcerpt(prose, "TARGET", 120) + if len(got) > 130 { + t.Errorf("prose excerpt not bounded: %d chars", len(got)) + } + if !strings.Contains(got, "TARGET") { + t.Error("excerpt must contain the hint token") + } +} + +// boundedExcerpt must slice by code point, not byte, so a CJK hint inside a CJK +// passage is windowed without splitting a rune (which would emit invalid UTF-8). +func TestBoundedExcerptCJKByRune(t *testing.T) { + // 12 CJK chars around a TARGET token; with maxChars well below the full + // length the window should still be valid UTF-8 and contain the token. + prose := strings.Repeat("字", 40) + "目标句在此" + strings.Repeat("文", 40) + got := boundedExcerpt(prose, "目标", 120) + if !utf8.ValidString(got) { + t.Errorf("CJK excerpt is not valid UTF-8: %q", got) + } + if !strings.Contains(got, "目标") { + t.Errorf("CJK excerpt must contain the hint token, got %q", got) + } + // The no-hint tail path must also stay valid UTF-8 (text[-tail:] by byte + // would split the trailing runes). + got2 := boundedExcerpt(prose, "absent", 60) + if !utf8.ValidString(got2) { + t.Errorf("CJK tail excerpt is not valid UTF-8: %q", got2) + } +} + +func TestSCABoostAdaptsVerdict(t *testing.T) { + res := SCAResult{ + IsSufficient: false, + Confidence: 0.3, + Contradictions: []string{"c1"}, + Claims: map[string]ClaimVerdict{ + "c1": {MissingInformation: []MissingPiece{{What: "the year"}}}, + "c2": {MissingInformation: []MissingPiece{{What: "the year"}}}, // duplicate + }, + } + b := res.Boost([]string{"fallback query"}) + if b.IsSufficient { + t.Error("boost must carry is_sufficient=false") + } + if len(b.Missing) != 1 || b.Missing[0] != "the year" { + t.Errorf("missing = %v, want the deduped 'the year'", b.Missing) + } + if !strings.Contains(b.Feedback, "the year") { + t.Errorf("feedback = %q, must mention the missing piece", b.Feedback) + } + if len(b.Followups) != 1 || b.Followups[0] != "fallback query" { + t.Errorf("followups = %v", b.Followups) + } +} + +// --------------------------------------------------------------------------- +// Query rewriter +// --------------------------------------------------------------------------- + +func TestClampAndTruthy(t *testing.T) { + if got := clamp(float64(1.5)); got != 1.0 { + t.Errorf("clamp(1.5) = %v, want 1.0", got) + } + if got := clamp(float64(-0.2)); got != 0.0 { + t.Errorf("clamp(-0.2) = %v, want 0.0", got) + } + if got := clamp("0.4"); got != 0.4 { + t.Errorf("clamp(\"0.4\") = %v, want 0.4", got) + } + // Unparseable -> Python's default of 1.0. + if got := clamp("not a number"); got != 1.0 { + t.Errorf("clamp(bad) = %v, want 1.0", got) + } + for _, v := range []any{true, "true", "TRUE", "1", "yes", "false", "0", float64(1)} { + if !truthy(v) { + t.Errorf("truthy(%v) = false, want true", v) + } + } + for _, v := range []any{false, "", float64(0), nil} { + if truthy(v) { + t.Errorf("truthy(%v) = true, want false", v) + } + } +} diff --git a/internal/rag/advanced_rag/harness/report_prompt.go b/internal/rag/advanced_rag/harness/report_prompt.go new file mode 100644 index 00000000000..c20c8f3d628 --- /dev/null +++ b/internal/rag/advanced_rag/harness/report_prompt.go @@ -0,0 +1,54 @@ +// +// 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. + +package harness + +// Report synthesis prompts. +// +// Mirrors rag/advanced_rag/harness/prompts/report_prompt.py. {cite_rules} in +// FinalAnswerSystem is substituted by the caller (see advanced_rag.ComposeAnswer). + +// FinalAnswerSystem mirrors report_prompt.FINAL_ANSWER_SYSTEM. {cite_rules} is +// substituted by the caller. +const FinalAnswerSystem = `You are a smart agent. Answer the user's question using ONLY the evidence provided below. Do not invent facts: if the evidence cannot support a claim, say so plainly instead of guessing. + +# Answer target +First resolve the exact role requested by the user's question. Multi-hop questions +often mention bridge entities that are only clues. Do not answer with a bridge +entity just because it satisfies a later clue; answer the entity, value, or fact +that satisfies the top-level question. If an Answer Target Contract is provided, +obey it over any research-summary wording. + +# Citation rules +{cite_rules} + +# Attribute fidelity (CRITICAL) +Answer the EXACT attribute/relation the question asks for. Do NOT substitute a similar but +different attribute, even when it is semantically related. For example: +- HOMETOWN ≠ BIRTHPLACE (place of birth): if asked for someone's hometown, do not answer with + where they were born unless the evidence equates the two. +- FIRST ≠ LARGEST, AGE AT DEATH ≠ BIRTH YEAR, etc. +Answer the question's own attribute using the evidence for THAT attribute. If the evidence only +supports a different attribute, say that you could only find the related (different) attribute and +do not present it as the answer to the requested one. + +# Language +Answer in the SAME language as the question. Translate retrieved evidence into that language as part of composing the answer; only verbatim quoted snippets may stay in their source language. + +# Fallback +If the evidence does not answer the question, reply with a clear statement that you don't have enough information based on the available sources (in the user's language).` + +// PartialAnswerPreamble mirrors report_prompt.PARTIAL_ANSWER_PREAMBLE. +const PartialAnswerPreamble = "Note: the following answer is based on partial information and may be incomplete." diff --git a/internal/rag/advanced_rag/harness/stats.go b/internal/rag/advanced_rag/harness/stats.go new file mode 100644 index 00000000000..96d05a968ca --- /dev/null +++ b/internal/rag/advanced_rag/harness/stats.go @@ -0,0 +1,671 @@ +// +// 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. +// + +package harness + +import ( + "context" + "fmt" + "log" + "sort" + "sync" + "time" + + "gorm.io/gorm" + + "ragflow/internal/agent/chat" +) + +// LLM-call instrumentation for the harness. +// +// Mirrors Python harness/stats.py. Every phase of the pipeline (route / +// planner / orchestrator / direct / sufficiency / finalize, ...) drives the LLM, +// and each call is attributed to the phase that was executing. Phase wall-clock +// is measured here rather than summing LLM latency, which is meaningless when +// calls run in parallel. +// +// Python stores the current phase and the active stats in ContextVars so +// parallel asyncio tasks get independent accounting. Go has no ContextVars; the +// same isolation is achieved by carrying both on the context.Context, which is +// already per-request (and per-goroutine when a phase fans out). + +// Canonical pipeline order for the per-phase usage table. Phases are listed in +// execution order so the log reads top-to-bottom like the actual flow, +// regardless of which phase first touched the counters. Phases not in this list +// are appended afterwards, alphabetically. +// This list matches Python _PHASE_ORDER (harness/stats.py) EXACTLY, so a Go run +// and a Python run emit comparable usage tables. Python's _PHASE_ORDER omits +// dynamic/draft/sca/rewrite (they are real @in_phase phases in Python too, but +// not in its canonical list, so Python appends them alphabetically at the end); +// compute is a Go-only phase (arithmetic.Compute). The snapshot/Log logic below +// re-appends any phase not present here alphabetically, mirroring Python, so all +// of them still appear in both runs in the same relative position. +var phaseOrder = []string{ + "formalize", + "route", + "planner", + "decompose", + "direct", + "orchestrator", + "claim_research", + "sufficiency", + "grounded", + "finalize", +} + +// Phase names used by the harness (Python @in_phase labels). +const ( + PhaseFormalize = "formalize" + PhaseRoute = "route" + PhasePlanner = "planner" + PhaseDecompose = "decompose" + PhaseDynamic = "dynamic" + PhaseDirect = "direct" + PhaseOrchestrator = "orchestrator" + PhaseClaimResearch = "claim_research" + PhaseDraft = "draft" + PhaseSufficiency = "sufficiency" + PhaseSCA = "sca" + PhaseRewrite = "rewrite" + PhaseCompute = "compute" + PhaseGrounded = "grounded" + PhaseFinalize = "finalize" +) + +var phaseRank = func() map[string]int { + m := make(map[string]int, len(phaseOrder)) + for i, n := range phaseOrder { + m[n] = i + } + return m +}() + +// phaseRoundKey identifies a phase within one orchestrator round. +type phaseRoundKey struct { + phase string + round int +} + +// LLMUsageStats holds per-phase LLM call, wall-clock, and token counters for +// one harness run. +type LLMUsageStats struct { + mu sync.Mutex + + calls map[string]int + failed map[string]int + phaseTimeMs map[string]float64 + promptTokens map[string]int + completionTokens map[string]int + totalTokens map[string]int + rounds map[string]int + roundTimes map[string][]float64 + // roundPhaseTimesMs is the phase wall-clock split per orchestrator round + // (index 0 = round 1). A phase that runs several times inside one round + // accumulates into that round. + roundPhaseTimesMs map[string][]float64 + roundClaimCounts map[string][]int + + roundStarts map[string]time.Time + currentRound int + phaseActive map[string]int + phaseStarts map[string]time.Time + roundPhaseAct map[phaseRoundKey]int + roundPhaseSt map[phaseRoundKey]time.Time +} + +// NewLLMUsageStats builds an empty counter set. +func NewLLMUsageStats() *LLMUsageStats { + return &LLMUsageStats{ + calls: map[string]int{}, + failed: map[string]int{}, + phaseTimeMs: map[string]float64{}, + promptTokens: map[string]int{}, + completionTokens: map[string]int{}, + totalTokens: map[string]int{}, + rounds: map[string]int{}, + roundTimes: map[string][]float64{}, + roundPhaseTimesMs: map[string][]float64{}, + roundClaimCounts: map[string][]int{}, + roundStarts: map[string]time.Time{}, + phaseActive: map[string]int{}, + phaseStarts: map[string]time.Time{}, + roundPhaseAct: map[phaseRoundKey]int{}, + roundPhaseSt: map[phaseRoundKey]time.Time{}, + } +} + +// elapsedMs returns a monotonic-aware wall duration in milliseconds. Python's +// stats use time.perf_counter() (a monotonic clock); Go's time.Time carries a +// monotonic reading too as long as we keep the struct (time.Now().UnixNano() +// would strip it and expose wall-clock step-backs), so we subtract the stored +// start time directly. This matches perf_counter's guarantee that phase/round +// durations never go negative when the system clock is stepped backwards. +func elapsedMs(now, start time.Time) float64 { + return now.Sub(start).Seconds() * 1000.0 +} + +// CurrentRound is the 1-based index of the orchestrator round executing, 0 outside. +func (s *LLMUsageStats) CurrentRound() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.currentRound +} + +// RecordCall counts one LLM call in phaseName. +func (s *LLMUsageStats) RecordCall(phaseName string) { + s.mu.Lock() + defer s.mu.Unlock() + s.calls[phaseName]++ +} + +// RecordFailed counts one failed LLM call in phaseName. +func (s *LLMUsageStats) RecordFailed(phaseName string) { + s.mu.Lock() + defer s.mu.Unlock() + s.failed[phaseName]++ +} + +// RecordUsage adds provider-reported token usage to phaseName. +func (s *LLMUsageStats) RecordUsage(phaseName string, prompt, completion, total int) { + s.mu.Lock() + defer s.mu.Unlock() + s.promptTokens[phaseName] += prompt + s.completionTokens[phaseName] += completion + s.totalTokens[phaseName] += total +} + +// RecordRound counts one iteration of a looping phase (e.g. an orchestrator +// cycle) and closes the previous iteration's wall-clock. +func (s *LLMUsageStats) RecordRound(phaseName string) { + s.mu.Lock() + defer s.mu.Unlock() + s.rounds[phaseName]++ + s.currentRound = s.rounds[phaseName] + now := time.Now() + if prev, ok := s.roundStarts[phaseName]; ok { + s.roundTimes[phaseName] = append(s.roundTimes[phaseName], elapsedMs(now, prev)) + } + s.roundStarts[phaseName] = now +} + +// RecordRoundClaims records how many claim-level tasks ran in the current round. +func (s *LLMUsageStats) RecordRoundClaims(phaseName string, count int) { + s.mu.Lock() + defer s.mu.Unlock() + if s.currentRound <= 0 { + return + } + counts := s.roundClaimCounts[phaseName] + for len(counts) < s.currentRound { + counts = append(counts, 0) + } + counts[s.currentRound-1] += count + s.roundClaimCounts[phaseName] = counts +} + +// notePhaseEnter / notePhaseExit implement the re-entrancy rule from Python: +// the same phase may be wrapped several times along one call path, and only the +// outermost interval is timed. +func (s *LLMUsageStats) notePhaseEnter(phaseName string, entryRound int) { + s.mu.Lock() + defer s.mu.Unlock() + now := time.Now() + s.phaseActive[phaseName]++ + if s.phaseActive[phaseName] == 1 { + s.phaseStarts[phaseName] = now + } + if entryRound > 0 { + k := phaseRoundKey{phaseName, entryRound} + s.roundPhaseAct[k]++ + if s.roundPhaseAct[k] == 1 { + s.roundPhaseSt[k] = now + } + } +} + +func (s *LLMUsageStats) notePhaseExit(phaseName string, entryRound int) { + s.mu.Lock() + defer s.mu.Unlock() + now := time.Now() + if active := s.phaseActive[phaseName]; active > 0 { + active-- + if active == 0 { + start, ok := s.phaseStarts[phaseName] + if !ok { + start = now + } + delete(s.phaseStarts, phaseName) + delete(s.phaseActive, phaseName) + s.phaseTimeMs[phaseName] += elapsedMs(now, start) + pending := s.rounds[phaseName] - len(s.roundTimes[phaseName]) + if pending > 0 { + settled := 0.0 + for _, t := range s.roundTimes[phaseName] { + settled += t + } + s.roundTimes[phaseName] = append(s.roundTimes[phaseName], max(0.0, s.phaseTimeMs[phaseName]-settled)) + delete(s.roundStarts, phaseName) + } + if phaseName == PhaseOrchestrator { + s.currentRound = 0 + } + } else { + s.phaseActive[phaseName] = active + } + } + if entryRound > 0 { + k := phaseRoundKey{phaseName, entryRound} + if active := s.roundPhaseAct[k]; active > 0 { + active-- + if active == 0 { + start, ok := s.roundPhaseSt[k] + if !ok { + start = now + } + delete(s.roundPhaseSt, k) + delete(s.roundPhaseAct, k) + times := s.roundPhaseTimesMs[phaseName] + for len(times) < entryRound { + times = append(times, 0.0) + } + times[entryRound-1] += elapsedMs(now, start) + s.roundPhaseTimesMs[phaseName] = times + } else { + s.roundPhaseAct[k] = active + } + } + } +} + +// Snapshot mirrors Python LLMUsageStats.snapshot: rows keyed by phase in +// canonical pipeline order. +func (s *LLMUsageStats) Snapshot() map[string]map[string]any { + s.mu.Lock() + defer s.mu.Unlock() + known := map[string]struct{}{} + for k := range s.calls { + known[k] = struct{}{} + } + for k := range s.failed { + known[k] = struct{}{} + } + for k := range s.totalTokens { + known[k] = struct{}{} + } + for k := range s.phaseTimeMs { + known[k] = struct{}{} + } + for k := range s.rounds { + known[k] = struct{}{} + } + phases := make([]string, 0, len(known)) + for _, p := range phaseOrder { + if _, ok := known[p]; ok { + phases = append(phases, p) + delete(known, p) + } + } + for p := range known { + phases = append(phases, p) + } + sort.Strings(phases[len(phases)-len(known):]) + + rows := make(map[string]map[string]any, len(phases)) + for _, p := range phases { + perRound := s.roundPhaseTimesMs[p] + rounds, roundTimes := s.rounds[p], append([]float64(nil), s.roundTimes[p]...) + if len(perRound) > 0 { + rounds, roundTimes = len(perRound), append([]float64(nil), perRound...) + } + rows[p] = map[string]any{ + "calls": s.calls[p], + "failed": s.failed[p], + "phase_time_ms": s.phaseTimeMs[p], + "prompt_tokens": s.promptTokens[p], + "completion_tokens": s.completionTokens[p], + "total_tokens": s.totalTokens[p], + "rounds": rounds, + "round_times": roundTimes, + "round_claim_counts": append([]int(nil), s.roundClaimCounts[p]...), + "round_phase_times_ms": append([]float64(nil), s.roundPhaseTimesMs[p]...), + } + } + return rows +} + +// --------------------------------------------------------------------------- +// Context plumbing +// --------------------------------------------------------------------------- + +type statsCtxKey struct{} +type phaseCtxKey struct{} +type progressCtxKey struct{} + +// WithStats binds stats to ctx so every LLM call beneath it is attributed there. +func WithStats(ctx context.Context, stats *LLMUsageStats) context.Context { + return context.WithValue(ctx, statsCtxKey{}, stats) +} + +// CurrentStats returns the stats bound to ctx, or nil. +func CurrentStats(ctx context.Context) *LLMUsageStats { + if s, ok := ctx.Value(statsCtxKey{}).(*LLMUsageStats); ok { + return s + } + return nil +} + +// WithProgress binds a per-request progress sink to ctx so every engine stage and +// every search beneath it can forward tagged lines (Python think_log counterpart) +// to the caller's live reasoning block. progress may be nil to disable. +func WithProgress(ctx context.Context, progress func(string)) context.Context { + return context.WithValue(ctx, progressCtxKey{}, progress) +} + +// CurrentProgress returns the progress sink bound to ctx, or nil. +func CurrentProgress(ctx context.Context) func(string) { + if p, ok := ctx.Value(progressCtxKey{}).(func(string)); ok { + return p + } + return nil +} + +// CurrentPhase returns the phase executing in ctx ("unknown" when none set). +func CurrentPhase(ctx context.Context) string { + if p, ok := ctx.Value(phaseCtxKey{}).(string); ok && p != "" { + return p + } + return "unknown" +} + +// Phase mirrors Python's phase() context manager: it marks the enclosed block +// as executing `name` and accrues its wall-clock into the bound stats. +// +// The returned func MUST be called when the block ends (defer it). Nesting the +// same phase name is supported: only the outermost interval is timed, so the +// time is not counted two or three times along a call path. +func Phase(ctx context.Context, name string) (context.Context, func()) { + stats := CurrentStats(ctx) + round := 0 + if stats != nil { + round = stats.CurrentRound() + stats.notePhaseEnter(name, round) + } + child := context.WithValue(ctx, phaseCtxKey{}, name) + return child, func() { + if stats != nil { + stats.notePhaseExit(name, round) + } + } +} + +// InPhase mirrors Python's in_phase decorator: it runs fn inside Phase(name). +func InPhase(ctx context.Context, name string, fn func(context.Context) error) error { + ctx, done := Phase(ctx, name) + defer done() + return fn(ctx) +} + +// RecordExternalResponse mirrors Python record_external_response: records a raw +// completion response that bypasses CountingInvoker, including token usage. +// action_session calls this for the two raw model calls it makes directly +// (action_session.py:_acompletion/1086). +func RecordExternalResponse(ctx context.Context, resp *chat.Response) { + stats := CurrentStats(ctx) + if stats == nil { + return + } + phase := CurrentPhase(ctx) + stats.RecordCall(phase) + if resp != nil { + recordResponseUsage(stats, phase, resp.Usage, resp.Tokens) + } +} + +// recordResponseUsage attributes one call's token usage, honouring the split +// when it is present and falling back to the single total counter otherwise. +func recordResponseUsage(stats *LLMUsageStats, phase string, usage *chat.Usage, totalOnly int) { + if usage != nil { + stats.RecordUsage(phase, usage.PromptTokens, usage.CompletionTokens, usage.TotalTokens) + return + } + if totalOnly > 0 { + stats.RecordUsage(phase, 0, 0, totalOnly) + } +} + +// RecordRound mirrors Python record_round. +func RecordRound(ctx context.Context, name string) { + if s := CurrentStats(ctx); s != nil { + s.RecordRound(name) + } +} + +// RecordRoundClaims mirrors Python record_round_claims. +func RecordRoundClaims(ctx context.Context, name string, count int) { + if s := CurrentStats(ctx); s != nil { + s.RecordRoundClaims(name, count) + } +} + +// Log emits the per-phase usage table. Mirrors Python LLMUsageStats.log. +// +// With orchestrator-round data it expands hierarchically: each round repeats +// its "orchestrator" row with the nested sub-phases (claim_research / +// sufficiency / grounded) indented underneath, matching the Python rendering. +// Phases outside the loop (route / planner / finalize) are listed flat. +func (s *LLMUsageStats) Log(logger *log.Logger) { + rows := s.Snapshot() + if len(rows) == 0 { + // No LLM activity (e.g. a cache hit). Still emit a line so every + // completed run is accounted for instead of silently disappearing. + if logger != nil { + logger.Println("[Agentic RAG] LLM usage by phase: (cached / no LLM calls)") + } + return + } + totalCalls, totalTokens := 0, 0 + for _, r := range rows { + totalCalls += r["calls"].(int) + totalTokens += r["total_tokens"].(int) + } + + // Canonical order: phases in phaseOrder first, then any leftover sorted. + seen := map[string]bool{} + phases := make([]string, 0, len(rows)) + for _, p := range phaseOrder { + if _, ok := rows[p]; ok { + phases = append(phases, p) + seen[p] = true + } + } + rest := make([]string, 0, len(rows)-len(phases)) + for p := range rows { + if !seen[p] { + rest = append(rest, p) + } + } + sort.Strings(rest) + phases = append(phases, rest...) + + // Per-round structure, read from the locked snapshot (Python reads + // self.round_phase_times_ms / self.round_times directly). + orchRT := []float64{} + if orchRow, ok := rows[PhaseOrchestrator]; ok { + if v, ok := orchRow["round_times"].([]float64); ok { + orchRT = v + } + } + perRound := map[string][]float64{} + for p, r := range rows { + if v, ok := r["round_phase_times_ms"].([]float64); ok && len(v) > 0 { + perRound[p] = v + } + } + nRounds := len(orchRT) + for _, v := range perRound { + if len(v) > nRounds { + nRounds = len(v) + } + } + + lines := []string{ + "[Agentic RAG] LLM usage by phase:", + fmt.Sprintf(" %-16s %7s %10s %12s %10s %10s", "phase", "llm_calls", "prompt_tok", "output_tok", "total_tok", "time(s)"), + } + + // phaseLabel mirrors Python's phase_label: claim_research gets a + // "(N)" suffix with the round's claim count when known. + phaseLabel := func(p string, r map[string]any, roundIdx int) string { + label := p + if p == PhaseClaimResearch { + if counts, ok := r["round_claim_counts"].([]int); ok && roundIdx < len(counts) && counts[roundIdx] > 0 { + label = fmt.Sprintf("%s (%d)", p, counts[roundIdx]) + } + } + return label + } + // row mirrors Python's custom_row / row: the label is printed verbatim + // (orchestrator round headers pass a custom label), token columns come + // from rows[p]). + row := func(indent, label, p string, tMs float64) string { + r := rows[p] + return fmt.Sprintf("%s%-16s %7d %10d %12d %10d %10.1f", + indent, label, r["calls"].(int), r["prompt_tokens"].(int), r["completion_tokens"].(int), r["total_tokens"].(int), tMs/1000.0) + } + + inRounds := make(map[string]bool, len(perRound)) + for k := range perRound { + inRounds[k] = true + } + + for _, p := range phases { + if p == PhaseOrchestrator && nRounds > 0 { + for i := 0; i < nRounds; i++ { + orchT := 0.0 + if i < len(orchRT) { + orchT = orchRT[i] + } else { + orchT = rows[p]["phase_time_ms"].(float64) + } + lines = append(lines, row(" ", fmt.Sprintf("orchestrator round %d", i+1), p, orchT)) + for _, sub := range phases { + if sub == PhaseOrchestrator { + continue + } + v, ok := perRound[sub] + if !ok || i >= len(v) { + continue + } + lines = append(lines, row(" ", phaseLabel(sub, rows[sub], i), sub, v[i])) + } + } + } else if inRounds[p] && nRounds > 0 { + // Already printed as a nested sub-phase of each orchestrator round. + continue + } else { + lines = append(lines, row(" ", p, p, rows[p]["phase_time_ms"].(float64))) + } + } + lines = append(lines, fmt.Sprintf(" total: %d LLM calls, %d tokens", totalCalls, totalTokens)) + if logger != nil { + logger.Println(joinLines(lines)) + } +} + +func joinLines(lines []string) string { + out := "" + for i, l := range lines { + if i > 0 { + out += "\n" + } + out += l + } + return out +} + +// CountingInvoker mirrors Python CountingChatModel: it wraps a chat.Invoker and +// records calls / failures / token usage against the phase carried on ctx. +// +// Unlike the Python proxy (which falls back to a bundle-wide stats object), the +// Go version records only when stats are bound to the context — matching how +// Python's _CURRENT_STATS resolution behaves for the innermost active stats. +type CountingInvoker struct { + Inner chat.Invoker + Stats *LLMUsageStats +} + +// Invoke implements chat.Invoker. +func (c *CountingInvoker) Invoke(ctx context.Context, db *gorm.DB, req chat.Request) (*chat.Response, error) { + stats := CurrentStats(ctx) + if stats == nil { + stats = c.Stats + } + phase := CurrentPhase(ctx) + if stats != nil { + stats.RecordCall(phase) + } + resp, err := c.Inner.Invoke(ctx, db, req) + if err != nil { + if stats != nil { + stats.RecordFailed(phase) + } + return nil, err + } + if stats != nil && resp != nil { + recordResponseUsage(stats, phase, resp.Usage, resp.Tokens) + } + return resp, nil +} + +// Stream implements chat.StreamingInvoker so a wrapped invoker keeps streaming +// AND is counted. Without this, StreamComplete's type assertion +// (m.Invoker.(chat.StreamingInvoker)) fails on the wrapper and the caller falls +// back to a one-shot (non-streaming) Invoke — losing both the stream and the +// accounting. Mirrors Python CountingChatModel.async_chat_streamly / +// async_chat_streamly_delta, which record usage in a finally block so the call +// is counted even when the inner model raised (last_usage is None then, so +// record_usage is a no-op — the same outcome as the success-only branch below). +// +// record_usage is taken from the returned *Response, mirroring Python's +// _last_usage(self._chat_mdl). If the inner invoker is not itself a +// StreamingInvoker, we decline rather than silently downgrade to a blocking +// Invoke, so callers keep their existing "fall back to the one-shot call" +// behaviour. +func (c *CountingInvoker) Stream(ctx context.Context, db *gorm.DB, req chat.Request, onDelta func(delta string, isThink bool) error) (*chat.Response, error) { + stats := CurrentStats(ctx) + if stats == nil { + stats = c.Stats + } + phase := CurrentPhase(ctx) + if stats != nil { + stats.RecordCall(phase) + } + inner, ok := c.Inner.(chat.StreamingInvoker) + if !ok { + return nil, fmt.Errorf("harness: chat invoker %T does not support streaming", c.Inner) + } + resp, err := inner.Stream(ctx, db, req, onDelta) + if err != nil { + if stats != nil { + stats.RecordFailed(phase) + } + return nil, err + } + if stats != nil && resp != nil { + recordResponseUsage(stats, phase, resp.Usage, resp.Tokens) + } + return resp, nil +} diff --git a/internal/rag/advanced_rag/harness/stats_test.go b/internal/rag/advanced_rag/harness/stats_test.go new file mode 100644 index 00000000000..cf50970d2fc --- /dev/null +++ b/internal/rag/advanced_rag/harness/stats_test.go @@ -0,0 +1,161 @@ +package harness + +import ( + "bytes" + "context" + "log" + "strings" + "testing" + + "ragflow/internal/agent/chat" +) + +// TestLogHierarchicalRounds verifies that Log mirrors Python LLMUsageStats.log: +// the orchestrator phase expands into one "orchestrator round N" row per round, +// with the in-loop sub-phases (claim_research / sufficiency) nested underneath, +// while the out-of-loop phases (route / planner / finalize) stay flat. +// +// NOTE: this test cannot run while the unrelated pre-existing break in +// internal/agent/tool/retrieval_nlp.go (RankFeature) blocks compilation of the +// harness test binary. It will run once that is resolved. +func TestLogHierarchicalRounds(t *testing.T) { + s := NewLLMUsageStats() + ctx := WithStats(context.Background(), s) + + // Flat phases before the orchestrator loop. + func() { + _, done := Phase(ctx, PhaseRoute) + defer done() + s.RecordCall(PhaseRoute) + }() + func() { + _, done := Phase(ctx, PhasePlanner) + defer done() + s.RecordCall(PhasePlanner) + }() + + // Orchestrator loop: two rounds, each doing claim_research + sufficiency. + func() { + c, done := Phase(ctx, PhaseOrchestrator) + defer done() + + RecordRound(c, PhaseOrchestrator) + func() { + _, d := Phase(c, PhaseClaimResearch) + defer d() + s.RecordCall(PhaseClaimResearch) + s.RecordUsage(PhaseClaimResearch, 0, 0, 120) + }() + func() { + _, d := Phase(c, PhaseSufficiency) + defer d() + s.RecordCall(PhaseSufficiency) + }() + + RecordRound(c, PhaseOrchestrator) + func() { + _, d := Phase(c, PhaseClaimResearch) + defer d() + s.RecordCall(PhaseClaimResearch) + s.RecordUsage(PhaseClaimResearch, 0, 0, 80) + }() + }() + + // Flat phase after the loop. + func() { + _, done := Phase(ctx, PhaseFinalize) + defer done() + s.RecordCall(PhaseFinalize) + }() + + var buf bytes.Buffer + s.Log(log.New(&buf, "", 0)) + out := buf.String() + + for _, want := range []string{ + "orchestrator round 1", + "orchestrator round 2", + "route", + "planner", + "finalize", + } { + if !strings.Contains(out, want) { + t.Errorf("log output missing %q\n---\n%s", want, out) + } + } + if !strings.Contains(out, "sufficiency") { + t.Errorf("log output missing sufficiency\n---\n%s", out) + } + // claim_research runs inside every round, so it must appear at least once + // per round as a nested (indented) row, not just as a flat top-level row. + if n := strings.Count(out, "claim_research"); n < 2 { + t.Errorf("expected claim_research at least twice (per round), got %d\n---\n%s", n, out) + } +} + +// TestProgressCtxRoundTrip verifies WithProgress binds a per-request progress +// sink on ctx and CurrentProgress retrieves the same callback. +func TestProgressCtxRoundTrip(t *testing.T) { + ctx := context.Background() + if p := CurrentProgress(ctx); p != nil { + t.Fatal("no progress bound on a bare ctx") + } + var got string + ctx = WithProgress(ctx, func(line string) { got = line }) + p := CurrentProgress(ctx) + if p == nil { + t.Fatal("WithProgress must bind a sink") + } + p("[Hybrid search] test") + if got != "[Hybrid search] test" { + t.Fatalf("sink did not fire: got %q", got) + } +} + +// TestCountingInvokerCountsStreaming mirrors Python CountingChatModel +// async_chat_streamly / async_chat_streamly_delta: a wrapped invoker that DOES +// stream must keep streaming AND be counted. Before CountingInvoker gained a +// Stream method, StreamComplete's type assertion (m.Invoker.(chat.StreamingInvoker)) +// failed on the wrapper, so the whole pipeline fell back to a one-shot Invoke and +// the stream was lost — the streaming branch was effectively uncredited. +func TestCountingInvokerCountsStreaming(t *testing.T) { + stats := NewLLMUsageStats() + wrapped := &CountingInvoker{ + Inner: &streamingInvoker{pieces: []piece{{text: "hi", isThink: false}}}, + Stats: stats, + } + ctx, done := Phase(context.Background(), "finalize") + defer done() + + resp, err := wrapped.Stream(ctx, nil, chat.Request{}, func(string, bool) error { return nil }) + if err != nil { + t.Fatalf("Stream failed: %v", err) + } + if resp.Content != "hi" { + t.Fatalf("Content = %q, want %q", resp.Content, "hi") + } + calls, _ := stats.Snapshot()["finalize"]["calls"].(int) + if calls != 1 { + t.Fatalf("streaming call not counted: calls = %v, want 1", stats.Snapshot()["finalize"]["calls"]) + } +} + +// TestCountingInvokerStreamDeclinesWithoutStreamingInner mirrors Python's +// invariant that the wrapper only streams when the inner model can: a non- +// streaming inner returns an explicit error rather than silently downgrading to +// a blocking Invoke (which would look like a one-shot call in the stats). + +// TestCountingInvokerStreamDeclinesWithoutStreamingInner mirrors Python's +// invariant that the wrapper only streams when the inner model can: a non- +// streaming inner returns an explicit error rather than silently downgrading to +// a blocking Invoke (which would look like a one-shot call in the stats). +func TestCountingInvokerStreamDeclinesWithoutStreamingInner(t *testing.T) { + wrapped := &CountingInvoker{Inner: &plainInvoker{}} + if _, err := wrapped.Stream(context.Background(), nil, chat.Request{}, nil); err == nil { + t.Fatal("want an error when the inner invoker cannot stream") + } +} + +// capturingInvoker records the last Request and returns a native tool call so we +// can verify the seam forwards the declared tools (Python native tools) and reads +// the model's calls back out of the native tool_calls field. diff --git a/internal/rag/advanced_rag/harness/structure_qa.go b/internal/rag/advanced_rag/harness/structure_qa.go new file mode 100644 index 00000000000..50e7116490c --- /dev/null +++ b/internal/rag/advanced_rag/harness/structure_qa.go @@ -0,0 +1,212 @@ +// +// 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. +// + +package harness + +import ( + "context" + "fmt" + "strings" + "unicode" + + "github.com/cloudwego/eino/schema" + + "ragflow/internal/agent/chat" +) + +// Ask the chat model to answer a question from a compiled-structure outline. +// +// Mirrors Python harness/structure_qa.py. Both Go navigation paths that read +// compiled rows render entities + relations into the same compact outline, ask +// the model whether that outline alone answers the question, and use the +// returned relevant_entities to pull the underlying source chunks even when the +// outline is NOT sufficient (so evidence still flows back to the caller). +// +// Lives apart from navigation.go because it is pure prompt/render work with no +// store access, and because both callers would otherwise import it from a file +// that in turn imports them. + +// RenderStructure renders a compiled structure (entities + relations) as a +// compact outline for the prompt. Mirrors Python _render_structure: +// +// Entities: +// - name (type): description +// (blank line) +// Relations: +// - src -[type]-> tgt +// +// Both lists are capped at maxStructureEntities / maxStructureRelations; empty +// names and empty relation endpoints are dropped. Entities with no type fall +// back to "other"; relations with no type fall back to "related". +func RenderStructure(entities, relations []map[string]any) string { + var lines []string + if len(entities) > 0 { + lines = append(lines, "Entities:") + n := len(entities) + if n > maxStructureEntities { + n = maxStructureEntities + } + for _, e := range entities[:n] { + name := strings.TrimSpace(strAny(e["name"])) + if name == "" { + continue + } + typ := strings.TrimSpace(orStr(strAny(e["type"]), "other")) + desc := strings.Join(strings.Fields(strAny(e["description"])), " ") + line := "- " + name + " (" + typ + ")" + if desc != "" { + line += ": " + desc + } + lines = append(lines, line) + } + } + if len(relations) > 0 { + lines = append(lines, "\nRelations:") + n := len(relations) + if n > maxStructureRelations { + n = maxStructureRelations + } + for _, r := range relations[:n] { + src := strings.TrimSpace(strAny(r["from"])) + tgt := strings.TrimSpace(strAny(r["to"])) + if src == "" || tgt == "" { + continue + } + rt := strings.TrimSpace(orStr(strAny(r["type"]), "related")) + lines = append(lines, "- "+src+" -["+rt+"]-> "+tgt) + } + } + return strings.Join(lines, "\n") +} + +// AskStructure asks the chat model to answer `topic` from the rendered outline. +// +// Mirrors Python _ask_structure. Returns (answer, relevant_entity_names): +// answer is empty unless the model judged the outline sufficient; the names are +// always returned so the caller can pull the underlying source chunks. `noun` +// is the display noun ("catalog" / "mindmap" / "knowledge graph"); `label` is +// the log tag. `model` is the request-scoped chat model (Python passes +// tools.chat_mdl); a nil model means no model is available and the call skips, +// mirroring Python's no-op when tools.chat_mdl is absent. Never raises: on any +// chat/parse failure both results are empty, matching Python's except-return of +// an empty verdict. +func AskStructure(ctx context.Context, model SessionModel, topic, noun, label string, entities, relations []map[string]any) (string, []string) { + if model == nil { + _LOG.Printf("[%s] structure QA skipped (no chat model)", label) + return "", nil + } + system := strings.ReplaceAll(navSystemPrompt, "{noun}", "the "+noun) + rendered := RenderStructure(entities, relations) + user := fmt.Sprintf("Question:\n%s\n\n%s:\n%s\n\nOutput JSON:", topic, capitalizeWord(noun), rendered) + + // Mirror Python _ask_structure: + // message_fit_in(form_message(system, user), tools.chat_mdl.max_length) + // tools.chat_mdl.max_length is exposed via ContextLengthModel; when absent, + // the 8192 default (chat EffectiveContextLength) applies, matching Python's + // LLM.max_length defaulting when the model config omits max_tokens. + budget := 0 + if cl, ok := model.(ContextLengthModel); ok { + budget = cl.ContextLength() + } + if budget <= 0 { + budget = chat.EffectiveContextLength(0) + } + fitted, fitErr := chat.FitMessages(system, []schema.Message{ + *schema.UserMessage(user), + }, budget) + if fitErr != "" { + _LOG.Printf("[%s] prompt fitting failed: %s", label, fitErr) + return "", nil + } + // FitMessages may prepend/trim a system message; re-extract it so the model + // call is exactly [system, user...] as Python sends msg[0] then msg[1:]. + if len(fitted) > 0 && fitted[0].Role == schema.System { + system = fitted[0].Content + fitted = fitted[1:] + } + msgs := make([]schema.Message, 0, 1+len(fitted)) + msgs = append(msgs, *schema.SystemMessage(system)) + msgs = append(msgs, fitted...) + // Python hardcodes {"temperature": 0.2} for this node — a stable verdict on + // a mechanical render, so it must not sample hot. Go mirrors that exactly + // when the model implements TemperatureModel; models without per-call + // temperature fall back to the plain Complete and run at their own default. + // (Documented seam, not a bug — see HARNESS.md and keywords.go.) + var resp *ModelReply + var err error + if tm, ok := model.(TemperatureModel); ok { + resp, err = tm.CompleteWithTemperature(ctx, msgs, nil, 0.2) + } else { + resp, err = model.Complete(ctx, msgs, nil) + } + if err != nil { + _LOG.Printf("[%s] could not read the outline with the model: %v", label, err) + return "", nil + } + + var verdict structureNavVerdict + if err := UnmarshalModelJSON(resp.Content, &verdict); err != nil { + _LOG.Printf("[%s] could not parse the outline verdict: %v", label, err) + return "", nil + } + + answer := "" + if verdict.IsSufficient { + answer = strings.TrimSpace(verdict.Answer) + } + relevant := make([]string, 0, len(verdict.RelevantEntities)) + for _, n := range verdict.RelevantEntities { + if s := strings.TrimSpace(n); s != "" { + relevant = append(relevant, s) + } + } + outcome := "does not fully answer" + if verdict.IsSufficient { + outcome = "answers" + } + _LOG.Printf("[%s] the %s %s the question; %d relevant entity(ies)", label, noun, outcome, len(relevant)) + return answer, relevant +} + +// strAny reads a map field as its plain string form. +func strAny(v any) string { + switch x := v.(type) { + case string: + return x + case fmt.Stringer: + return x.String() + case nil: + return "" + default: + return fmt.Sprint(x) + } +} + +// capitalizeWord mirrors Python str.capitalize(): uppercase the first rune and +// lowercase every remaining rune. Python lowercases the rest, so e.g. +// "hELLo".capitalize() -> "Hello"; the previous Go version left the tail +// untouched ("HELLO"), which diverged. +func capitalizeWord(s string) string { + if s == "" { + return s + } + rs := []rune(s) + rs[0] = unicode.ToUpper(rs[0]) + for i := 1; i < len(rs); i++ { + rs[i] = unicode.ToLower(rs[i]) + } + return string(rs) +} diff --git a/internal/rag/advanced_rag/harness/structure_qa_test.go b/internal/rag/advanced_rag/harness/structure_qa_test.go new file mode 100644 index 00000000000..96c8f1078e6 --- /dev/null +++ b/internal/rag/advanced_rag/harness/structure_qa_test.go @@ -0,0 +1,175 @@ +// +// 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. +// + +package harness + +import ( + "context" + "strings" + "testing" +) + +// entity map helper (mirrors Python structure_qa.py rendering inputs). +func saEntity(name, typ, desc string) map[string]any { + return map[string]any{"name": name, "type": typ, "description": desc} +} + +func saRelation(from, to, typ string) map[string]any { + return map[string]any{"from": from, "to": to, "type": typ} +} + +// RenderStructure feeds the LLM prompt in graph_explore (via AskStructure); it +// must render exactly "Name (Type): Description" for entities (Type defaulting +// to "other") and "From -[Type]-> To" for relations (Type defaulting to +// "related"), mirroring Python _render_structure. +func TestRenderStructure(t *testing.T) { + entities := []map[string]any{ + saEntity("OmiyaSoft", "company", "game dev"), + saEntity("NoType", "", " "), + {"name": " "}, // blank name dropped + } + relations := []map[string]any{ + saRelation("OmiyaSoft", "Culdcept", "founded"), + saRelation("A", "B", ""), // missing type -> related + } + out := RenderStructure(entities, relations) + + if !strings.Contains(out, "Entities:") || !strings.Contains(out, "Relations:") { + t.Fatalf("missing section headers: %q", out) + } + // Whitespace in descriptions is collapsed. + if !strings.Contains(out, "- OmiyaSoft (company): game dev") { + t.Errorf("entity with description not rendered: %q", out) + } + // No type -> "other"; blank description -> no trailing colon. + if !strings.Contains(out, "- NoType (other)") { + t.Errorf("entity default type missing: %q", out) + } + if strings.Contains(out, "- NoType (other):") { + t.Errorf("blank description must not render a colon: %q", out) + } + if strings.Contains(out, "- (") { + t.Errorf("blank-name entity must be dropped: %q", out) + } + if !strings.Contains(out, "- OmiyaSoft -[founded]-> Culdcept") { + t.Errorf("relation not rendered: %q", out) + } + // Missing relation type -> "related". + if !strings.Contains(out, "- A -[related]-> B") { + t.Errorf("relation default type missing: %q", out) + } +} + +func TestRenderStructureCapsAtLimits(t *testing.T) { + entities := make([]map[string]any, maxStructureEntities+5) + for i := range entities { + entities[i] = saEntity("E", "t", "") + } + relations := make([]map[string]any, maxStructureRelations+5) + for i := range relations { + relations[i] = saRelation("A", "B", "r") + } + out := RenderStructure(entities, relations) + // Each entity bullet is "\n- E (t)"; caps at maxStructureEntities. + if n := strings.Count(out, "\n- E (t)"); n != maxStructureEntities { + t.Errorf("entity bullets = %d, want cap %d", n, maxStructureEntities) + } + if n := strings.Count(out, "\n- A -[r]-> B"); n != maxStructureRelations { + t.Errorf("relation bullets = %d, want cap %d", n, maxStructureRelations) + } +} + +// Python _render_structure joins an empty list, so both-empty input renders "". +func TestRenderStructureEmpty(t *testing.T) { + if out := RenderStructure(nil, nil); out != "" { + t.Errorf("empty structure must render empty string, got %q", out) + } +} + +// capitalizeWord must mirror Python str.capitalize(): uppercase the first rune +// AND lowercase every remaining rune. The previous Go version left the tail +// untouched, so "hELLo" produced "HELLO" instead of Python's "Hello". +func TestCapitalizeWord(t *testing.T) { + cases := []struct { + in, want string + }{ + {"", ""}, + {"knowledge graph", "Knowledge graph"}, + {"hELLo", "Hello"}, + {"WORLD", "World"}, + {"already", "Already"}, + {"123abc", "123abc"}, // first char non-letter: untouched, rest lowercased + {"ÜBER", "Über"}, // unicode: first upper, rest lower + } + for _, c := range cases { + if got := capitalizeWord(c.in); got != c.want { + t.Errorf("capitalizeWord(%q) = %q, want %q", c.in, got, c.want) + } + } +} + +// --------------------------------------------------------------------------- +// AskStructure: request-scoped model + temperature 0.2 (Python _ask_structure). +// --------------------------------------------------------------------------- + +// TestAskStructureNilModelSkips verifies a nil model short-circuits to an empty +// verdict instead of reaching the global invoker (mirrors Python's no-op when +// tools.chat_mdl is absent). +func TestAskStructureNilModelSkips(t *testing.T) { + answer, relevant := AskStructure(context.Background(), nil, "Q", "knowledge graph", "Graph exploration", nil, nil) + if answer != "" || len(relevant) != 0 { + t.Errorf("nil model -> (%q, %v), want empty", answer, relevant) + } +} + +// TestAskStructureUsesTemperatureTwoTenths verifies the structure verdict is a +// mechanical rewrite drawn at 0.2, matching Python {"temperature": 0.2}. +func TestAskStructureUsesTemperatureTwoTenths(t *testing.T) { + mdl := &tempRecordingModel{replies: []*ModelReply{{ + Content: `{"is_sufficient": true, "answer": "founded in 1984", "relevant_entities": ["OmiyaSoft"]}`, + }}} + answer, relevant := AskStructure(context.Background(), mdl, "who founded Culdcept?", + "knowledge graph", "Graph exploration", + []map[string]any{saEntity("OmiyaSoft", "company", "")}, nil) + if mdl.temperature == nil { + t.Fatal("CompleteWithTemperature was not called") + } + if *mdl.temperature != 0.2 { + t.Errorf("temperature = %v, want 0.2", *mdl.temperature) + } + if answer != "founded in 1984" { + t.Errorf("answer = %q, want the sufficient verdict answer", answer) + } + if len(relevant) != 1 || relevant[0] != "OmiyaSoft" { + t.Errorf("relevant = %v, want [OmiyaSoft]", relevant) + } +} + +// TestAskStructureInsufficientKeepsRelevant verifies an insufficient verdict +// still returns the relevant entities (evidence pulled from the source chunks). +func TestAskStructureInsufficientKeepsRelevant(t *testing.T) { + mdl := &tempRecordingModel{replies: []*ModelReply{{ + Content: `{"is_sufficient": false, "answer": "", "relevant_entities": ["Culdcept"]}`, + }}} + answer, relevant := AskStructure(context.Background(), mdl, "Q", "mindmap", "Mindmap exploration", + []map[string]any{saEntity("Culdcept", "game", "")}, nil) + if answer != "" { + t.Errorf("insufficient answer = %q, want empty", answer) + } + if len(relevant) != 1 || relevant[0] != "Culdcept" { + t.Errorf("relevant = %v, want [Culdcept]", relevant) + } +} diff --git a/internal/rag/advanced_rag/harness/tool_compiled_expansion.go b/internal/rag/advanced_rag/harness/tool_compiled_expansion.go new file mode 100644 index 00000000000..ff370c54d41 --- /dev/null +++ b/internal/rag/advanced_rag/harness/tool_compiled_expansion.go @@ -0,0 +1,558 @@ +// +// 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. +// + +package harness + +import ( + "context" + "encoding/json" + "math" + "sort" + "strings" + + "ragflow/internal/entity" +) + +// Dense-match parameters for compiled-row search, mirroring Python +// compiled_expansion.py _VECTOR_NUM_CANDIDATES / _VECTOR_SIMILARITY. When a +// SearchCompiled implementation answers matchText with a dense (ANN) leg it MUST +// pass num_candidates = max(topN, vectorNumCandidates) and similarity = +// vectorSimilarity as named options — Python's PR #19172 fixed a bug where 0.1 +// was passed positionally as num_candidates (ef_search), collapsing the HNSW +// candidate list and silently destroying recall. Go expresses dense options as a +// named map (engine MatchDenseExpr.ExtraOptions), so the pitfall is avoided as +// long as the implementation uses these constants. +const ( + vectorNumCandidates = 256 + vectorSimilarity = 0.1 +) + +// CompiledStore is the seam over the doc-store compiled-structure rows that the +// harness must not own directly (it would pull in the retrieval backend and +// break unit-tier `go test ./...`). It mirrors the three primitives +// compiled_expansion.py reaches for: +// +// - settings.docStoreConn.search -> SearchCompiled +// - source_chunk_ids loading -> LoadChunks +// - settings.retriever.get_vector -> Vectorize (kept for callers that need it) +// +// The production implementation lives in the integration layer and is injected +// through SearchDeps.Expand (see NewCompiledExpander). +type CompiledStore interface { + // SearchCompiled returns compiled rows (entity / relation / synthesis page) + // matching the given filters and free-text match, scoped to (kbID, tenantID, + // docIDs). docIDs is applied to the doc store as the scope (Python passes it + // as a "doc_id" filter for entity/relation rows and "source_doc_ids" for + // synthesis pages; the exact key is the implementation's concern). A row + // carries at least content_with_weight / source_chunk_ids / doc_id / docnm_kwd + // / from_entity_kwd / to_entity_kwd / name_kwd. + // + // filters keys mirror Python's condition dict: "knowledge_graph_kwd" + // (kind: entity/relation), "compile_kwd" (tree/wiki_page/artifact_page/essence), + // "compilation_template_kind_kwd", plus exact-list lookups ("name_kwd", + // "from_entity_kwd", "to_entity_kwd") and "available_int". Each value is an + // OR-list; filters are AND-ed. + // + // When matchText is answered with a dense (ANN) leg the implementation must + // set its num_candidates = max(topN, vectorNumCandidates) and its similarity + // threshold to vectorSimilarity (see the consts above). + SearchCompiled(ctx context.Context, kbID, tenantID string, docIDs []string, filters map[string][]string, matchText string, topN int) ([]map[string]any, error) + // LoadChunks returns the raw chunks for the given source_chunk_ids. + LoadChunks(ctx context.Context, kbID, tenantID string, chunkIDs []string) ([]map[string]any, error) + // Vectorize returns the embedding of text. Kept for the interface contract; + // a faithful port assigns chunks a similarity and blends them by that field, + // so expansion itself does not call Vectorize. + Vectorize(ctx context.Context, text string) ([]float64, error) +} + +// compiledScope is one (kb_id, tenant_id, doc_ids) triple. Mirrors Python +// tools._kg_scopes, which returns exactly that list for a (possibly empty) +// doc_scope. +type compiledScope struct { + kbID string + tenantID string + docIDs []string +} + +// Template-kind labels for the entity 1-hop strategies, in the exact order +// Python iterates them in _expand_with_compiled. +var compiledEntityKinds = []struct { + label string + kind string +}{ + {"knowledge_graph", "knowledge_graph"}, + {"mind_map", "mind_map"}, + {"timeline", "timeline"}, + {"page_index", "page_index"}, +} + +// Synthesis compile keywords, in the exact order Python iterates them. +var compiledSynthesisKinds = []struct { + label string + kind string +}{ + {"wiki_page", "wiki_page"}, + {"artifact_page", "artifact_page"}, + {"essence", "essence"}, +} + +// CompiledScopeConfig carries the scope-resolution inputs of one search +// session, mirroring the slice of Python's RAGTools that _kg_scopes +// (exploration.py:_kg_scopes) reads: the bound datasets (each with its OWN owner +// tenant), the request tenant used as a fallback, and the optional +// scoped_doc_ids / doc→(kb,tenant) hooks. +type CompiledScopeConfig struct { + // DatasetIDs are the bound dataset ids (Python RAGTools.kb_ids). + DatasetIDs []string + // TenantID is the request tenant, used only when a bound dataset carries no + // tenant id of its own. + TenantID string + // KBs are the resolved dataset objects; their (ID, TenantID) pairs give each + // bound dataset its own compiled-row index scope (Python kb.tenant_id). + KBs []*entity.Knowledgebase + // DocTenantResolver resolves a document id to its owning (kb, tenant) so a + // doc scope is grouped by real owner (Python tools._resolve_doc_tenant). Nil + // keeps the fallback: each bound dataset searched with the whole doc scope. + DocTenantResolver DocTenantResolver +} + +// compiledExpander is the real implementation of CompiledExpander. It ports +// tools/compiled_expansion.py::_expand_with_compiled and its strategy helpers, +// with the doc-store side delegated to CompiledStore. +type compiledExpander struct { + store CompiledStore + cfg CompiledScopeConfig +} + +// NewCompiledExpander builds a CompiledExpander for one search session. A nil +// store, no bound dataset, or no fallback tenant yields a nil expander +// (expansion disabled), matching SearchDeps.Expand == nil. +func NewCompiledExpander(store CompiledStore, cfg CompiledScopeConfig) CompiledExpander { + if store == nil || len(cfg.DatasetIDs) == 0 || strings.TrimSpace(cfg.TenantID) == "" { + return nil + } + return &compiledExpander{store: store, cfg: cfg} +} + +// Expand mirrors Python _expand_with_compiled: a zero-LLM enrichment that layers +// the dataset's compiled products on top of the retrieved chunks. For each bound +// KB it runs the per-template 1-hop entity expansion (knowledge_graph / mind_map +// / timeline / page_index), the tree structure graph (compile_kwd="tree"), and +// the three synthesis-page expansions (wiki_page / artifact_page / essence) — +// each capped at max_chunks=5 — then re-sorts the whole kbinfos["chunks"] by +// similarity so compiled chunks blend by relevance with the regular ones. +func (e *compiledExpander) Expand(ctx context.Context, kb *Kbinfos, query, keywords string, docScope []string) error { + if e == nil || e.store == nil || kb == nil { + return nil + } + before := len(kb.Chunks) + seen := make(map[string]bool, len(kb.Chunks)) + for _, c := range kb.Chunks { + if id := ChunkIDOf(c); id != "" { + seen[id] = true + } + } + match := strings.TrimSpace(query) + if match == "" { + match = strings.TrimSpace(keywords) + } + + scopes := e.kgScopes(docScope) + for _, sc := range scopes { + // 1-hop entity-graph expansion, per template kind (Python L71-89): + // compile_kwd empty, template_kind selects the template. + for _, tk := range compiledEntityKinds { + chunks := e.expandCompiledStrategy(ctx, sc, match, seen, "", tk.kind, 5) + if len(chunks) > 0 { + kb.Chunks = append(kb.Chunks, chunks...) + _LOG.Printf("[Compiled expand] %s: +%d chunks", tk.label, len(chunks)) + } + } + // Tree structure graph, selected by compile_kwd (Python L91-104): + // template_kind empty, compile_kwd="tree". + chunks := e.expandCompiledStrategy(ctx, sc, match, seen, "tree", "", 5) + if len(chunks) > 0 { + kb.Chunks = append(kb.Chunks, chunks...) + _LOG.Printf("[Compiled expand] tree: +%d chunks", len(chunks)) + } + // Synthesis pages — standalone rendered articles, searched directly + // (Python L106-125). + for _, ck := range compiledSynthesisKinds { + chunks := e.expandWikiPageStrategy(ctx, sc, match, seen, ck.kind, 5) + if len(chunks) > 0 { + kb.Chunks = append(kb.Chunks, chunks...) + _LOG.Printf("[Compiled expand] %s: +%d chunks", ck.label, len(chunks)) + } + } + } + + // Re-sort so compiled-expansion chunks blend by similarity with regular ones + // (Python L127-130). + if len(kb.Chunks) > 0 { + sort.SliceStable(kb.Chunks, func(i, j int) bool { + return similarityOf(kb.Chunks[i]) > similarityOf(kb.Chunks[j]) + }) + } + + _LOG.Printf("[Hybrid search] Compiled expansion added %d chunks.", len(kb.Chunks)-before) + return nil +} + +// kgScopes mirrors Python _kg_scopes by delegating to the +// same resolver graph_explore uses: with a doc scope the documents are grouped +// by their real owning (kb, tenant) — which may lie OUTSIDE the bound datasets — +// and without one each bound dataset is scanned under its OWN tenant. The doc +// scope arrives already ceilinged by resolveDocScope (Python scoped_doc_ids). +func (e *compiledExpander) kgScopes(docScope []string) []compiledScope { + scopes := resolveKGScope(SearchDeps{ + KbIDs: e.cfg.DatasetIDs, + TenantID: e.cfg.TenantID, + KBs: e.cfg.KBs, + DocTenantResolver: e.cfg.DocTenantResolver, + }, docScope, e.cfg.DatasetIDs) + out := make([]compiledScope, 0, len(scopes)) + for _, sc := range scopes { + out = append(out, compiledScope{kbID: sc.KBID, tenantID: sc.TenantID, docIDs: sc.Docs}) + } + return out +} + +// searchCompiledRows mirrors Python _search_compiled_rows for a single scope: +// a compiled-row search scoped to one (kb_id, tenant_id, doc_ids) with the given +// OR-list filters (including exact name_kwd / from_entity_kwd / to_entity_kwd +// lookups) and an optional free-text match. +func (e *compiledExpander) searchCompiledRows(ctx context.Context, sc compiledScope, matchText string, topN int, filters map[string][]string) []map[string]any { + rows, err := e.store.SearchCompiled(ctx, sc.kbID, sc.tenantID, sc.docIDs, filters, matchText, topN) + if err != nil { + return nil + } + return rows +} + +// expandCompiledStrategy mirrors Python _expand_compiled_strategy: within one +// scope, embedding-match seed entities of a given template_kind/compile_kwd, +// hop 1-hop through adjacent relations (forward + backward), collect neighbour +// entity names, look up their source_chunk_ids by exact name_kwd, then load the +// referenced source chunks, deduped and capped at maxChunks. +func (e *compiledExpander) expandCompiledStrategy(ctx context.Context, sc compiledScope, match string, seen map[string]bool, compileKwd, templateKwd string, maxChunks int) []map[string]any { + // -- 1. Seed entities (embedding match, top 5) -- + seedRows := e.searchCompiledRows(ctx, sc, match, 5, seedFilters("entity", compileKwd, templateKwd)) + if len(seedRows) == 0 { + return nil + } + seedNames := make(map[string]bool) + for _, r := range seedRows { + if name := seedNameFromRow(r); name != "" { + seedNames[name] = true + } + } + if len(seedNames) == 0 { + return nil + } + + // -- 2. Adjacent relations (outgoing + incoming), top 50 each -- + // Provide both original and lowercased names — dataset_structure_merger + // lowercases merged-row endpoints while per-doc rows keep original case. + seedList := lowerUnionSorted(seedNames) + var allRels []map[string]any + for _, relFilter := range []map[string][]string{ + {"from_entity_kwd": seedList}, + {"to_entity_kwd": seedList}, + } { + f := seedFilters("relation", compileKwd, templateKwd) + for k, v := range relFilter { + f[k] = v + } + allRels = append(allRels, e.searchCompiledRows(ctx, sc, "", 50, f)...) + } + + // -- 3. Neighbour names (1-hop, exclude seeds) -- + seedLower := make(map[string]bool, len(seedNames)) + for n := range seedNames { + seedLower[strings.ToLower(n)] = true + } + neighbourNames := make(map[string]bool) + for _, rel := range allRels { + frm := strings.TrimSpace(compiledRelationEndpoint(rel, "from_entity_kwd")) + to := strings.TrimSpace(compiledRelationEndpoint(rel, "to_entity_kwd")) + if frm != "" && seedLower[strings.ToLower(frm)] && to != "" && !seedLower[strings.ToLower(to)] { + neighbourNames[to] = true + } + if to != "" && seedLower[strings.ToLower(to)] && frm != "" && !seedLower[strings.ToLower(frm)] { + neighbourNames[frm] = true + } + } + if len(neighbourNames) == 0 { + return nil + } + + // -- 4. Neighbour entity source_chunk_ids (exact name_kwd lookup) -- + neighList := lowerUnionSorted(neighbourNames) + if len(neighList) > 100 { + neighList = neighList[:100] // reasonable cap for name_kwd search + } + neighFilter := seedFilters("entity", compileKwd, templateKwd) + neighFilter["name_kwd"] = neighList // exact name_kwd lookup (Python L361) + neighRows := e.searchCompiledRows(ctx, sc, "", len(neighList), neighFilter) + + // -- 5. Group chunk ids by doc, load, dedupe, cap -- + byDoc := map[string][]string{} + order := []string{} + for _, r := range neighRows { + docID := compiledDocID(r) + for _, cid := range compiledSourceChunkIDs(r) { + if cid == "" || seen[cid] { + continue + } + if _, ok := byDoc[docID]; !ok { + order = append(order, docID) + } + byDoc[docID] = append(byDoc[docID], cid) + } + } + return e.loadByDoc(ctx, sc, order, byDoc, seen, maxChunks) +} + +// expandWikiPageStrategy mirrors Python _expand_wiki_page_strategy: search the +// synthesis-compiled pages of one compile_kwd directly, collect their +// source_chunk_ids, then load the referenced source chunks. Pages rank high, so +// each loaded chunk is assigned similarity=0.9 unless it already carries one. +func (e *compiledExpander) expandWikiPageStrategy(ctx context.Context, sc compiledScope, match string, seen map[string]bool, compileKwd string, maxChunks int) []map[string]any { + // -- 1. Search synthesis pages (no knowledge_graph_kwd filter) -- + rows := e.searchSynthesisPages(ctx, sc, match, compileKwd, 5) + if len(rows) == 0 { + return nil + } + + // -- 2. Collect source_chunk_ids from matching pages -- + byDoc := map[string][]string{} + order := []string{} + for _, r := range rows { + docID := compiledDocID(r) + for _, cid := range compiledSourceChunkIDs(r) { + if cid == "" || seen[cid] { + continue + } + if _, ok := byDoc[docID]; !ok { + order = append(order, docID) + } + byDoc[docID] = append(byDoc[docID], cid) + } + } + if len(order) == 0 { + return nil + } + + // -- 3. Load chunks, assign high similarity for priority ranking -- + loaded := e.loadByDoc(ctx, sc, order, byDoc, seen, maxChunks) + for _, c := range loaded { + if _, has := c["similarity"]; !has { + c["similarity"] = 0.9 // wiki pages rank high + } + } + return loaded +} + +// searchSynthesisPages mirrors Python _search_synthesis_pages: find synthesis +// page rows whose title/topic/content matches the query, filtered by compile_kwd +// and available_int=1. Synthesis pages are standalone articles that do NOT carry +// the knowledge_graph_kwd field, so no entity/relation filter is applied. +func (e *compiledExpander) searchSynthesisPages(ctx context.Context, sc compiledScope, matchText, compileKwd string, topN int) []map[string]any { + return e.searchCompiledRows(ctx, sc, matchText, topN, map[string][]string{ + "compile_kwd": {compileKwd}, + "available_int": {"1"}, + }) +} + +// loadByDoc loads source chunks grouped per doc within one scope, honoring a +// global maxChunks cap and the seen-id dedup set. Returns newly added chunks in +// doc order. Mirrors Python's per-doc _load_chunks_for_doc loop and its +// max_chunks break/limit accounting. +func (e *compiledExpander) loadByDoc(ctx context.Context, sc compiledScope, order []string, byDoc map[string][]string, seen map[string]bool, maxChunks int) []map[string]any { + // Python _load_chunks_for_doc resolves EACH row's doc_id to its owning + // (kb, tenant) — not the searched scope — and loads nothing when that + // resolution fails (merged dataset rows carry a pseudo/empty doc_id). Loading + // from the scope instead would surface chunks Python deliberately drops, and + // would query the wrong dataset for a row whose doc belongs elsewhere. + owners := map[string]DocTenant{} + if e.cfg.DocTenantResolver != nil { + ids := make([]string, 0, len(order)) + for _, docID := range order { + if docID != "" { + ids = append(ids, docID) + } + } + if resolved, err := e.cfg.DocTenantResolver.ResolveDocTenants(ctx, ids); err == nil { + owners = resolved + } + } + var out []map[string]any + for _, docID := range order { + if len(out) >= maxChunks { + break + } + kbID, tenantID := sc.kbID, sc.tenantID + if e.cfg.DocTenantResolver != nil { + owner, ok := owners[docID] + if docID == "" || !ok || owner.KBID == "" { + continue + } + kbID, tenantID = owner.KBID, owner.TenantID + } + cids := byDoc[docID] + remaining := maxChunks - len(out) + if len(cids) > remaining { + cids = cids[:remaining] + } + rows, err := e.store.LoadChunks(ctx, kbID, tenantID, cids) + if err != nil { + continue + } + for _, c := range rows { + id := ChunkIDOf(c) + if id == "" || seen[id] { + continue + } + seen[id] = true + out = append(out, c) + } + } + return out +} + +// seedNameFromRow mirrors Python L293-300: parse content_with_weight as JSON and +// read payload.name or payload.title (stripped). +func seedNameFromRow(row map[string]any) string { + cww, _ := row["content_with_weight"].(string) + if cww == "" { + return "" + } + var payload map[string]any + if err := json.Unmarshal([]byte(cww), &payload); err != nil { + return "" + } + name := strings.TrimSpace(asString(payload["name"])) + if name == "" { + name = strings.TrimSpace(asString(payload["title"])) + } + return name +} + +// lowerUnionSorted returns the sorted union of the names and their lowercased +// forms, mirroring Python `sorted({n.lower() for n in X} | X)`. +func lowerUnionSorted(names map[string]bool) []string { + seen := make(map[string]bool, len(names)*2) + for n := range names { + if n == "" { + continue + } + seen[n] = true + seen[strings.ToLower(n)] = true + } + out := make([]string, 0, len(seen)) + for n := range seen { + out = append(out, n) + } + sort.Strings(out) + return out +} + +func compiledDocID(row map[string]any) string { + return asString(row["doc_id"]) +} + +// compiledRelationEndpoint reads a relation's from_entity_kwd/to_entity_kwd +// (which may be a bare string or a single-element list). +func compiledRelationEndpoint(row map[string]any, key string) string { + if v, ok := row[key].(string); ok { + return v + } + return asString(row[key]) +} + +func compiledSourceChunkIDs(row map[string]any) []string { + switch v := row["source_chunk_ids"].(type) { + case []string: + return v + case []any: + out := make([]string, 0, len(v)) + for _, x := range v { + if s, ok := x.(string); ok { + out = append(out, s) + } + } + return out + case string: + return []string{v} + } + return nil +} + +// similarityOf returns a chunk's similarity score as a float64 (Python +// c.get("similarity", 0.0)); nil/absent counts as 0. +func similarityOf(c map[string]any) float64 { + switch v := c["similarity"].(type) { + case float64: + return v + case float32: + return float64(v) + case int: + return float64(v) + case int64: + return float64(v) + } + return 0.0 +} + +func asString(v any) string { + if s, ok := v.(string); ok { + return s + } + return "" +} + +// seedFilters builds the entity/relation condition, mirroring Python +// _search_compiled_rows: {"knowledge_graph_kwd": [kind]} plus an optional +// compile_kwd ("tree") or compilation_template_kind_kwd selector. +func seedFilters(kind, compileKwd, templateKwd string) map[string][]string { + f := map[string][]string{"knowledge_graph_kwd": {kind}} + if compileKwd != "" { + f["compile_kwd"] = []string{compileKwd} + } + if templateKwd != "" { + f["compilation_template_kind_kwd"] = []string{templateKwd} + } + return f +} + +// cosine returns the cosine similarity of two equal-length vectors. Shared with +// tool_navigation.go (navigation.py _node_score). Returns 0 on empty/mismatched +// input or when either vector is zero. +func cosine(a, b []float64) float64 { + if len(a) == 0 || len(b) == 0 || len(a) != len(b) { + return 0 + } + var dot, na, nb float64 + for i := range a { + dot += a[i] * b[i] + na += a[i] * a[i] + nb += b[i] * b[i] + } + if na == 0 || nb == 0 { + return 0 + } + return dot / (math.Sqrt(na) * math.Sqrt(nb)) +} diff --git a/internal/rag/advanced_rag/harness/tool_compiled_expansion_test.go b/internal/rag/advanced_rag/harness/tool_compiled_expansion_test.go new file mode 100644 index 00000000000..abe22301375 --- /dev/null +++ b/internal/rag/advanced_rag/harness/tool_compiled_expansion_test.go @@ -0,0 +1,431 @@ +// +// 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. +// + +package harness + +import ( + "context" + "strings" + "testing" + + "ragflow/internal/entity" +) + +// stubCompiledStore is an in-memory CompiledStore so the expander logic can be +// exercised in the unit tier. It behaves like the doc store: +// +// - rows carry knowledge_graph_kwd / compile_kwd / available_int / from_entity_kwd +// / to_entity_kwd / name_kwd / content_with_weight / source_chunk_ids / doc_id. +// - filters are AND-ed, each value an OR-set (a row matches if its field's +// string form equals a member). +// - matchText selects rows whose name/content contains it (stand-in for the +// dense+keyword retrieval the store normally does). +type stubCompiledStore struct { + rows []map[string]any + chunks map[string]string +} + +func (s *stubCompiledStore) SearchCompiled(_ context.Context, _, _ string, _ []string, filters map[string][]string, matchText string, topN int) ([]map[string]any, error) { + var out []map[string]any + for _, r := range s.rows { + if !rowMatchesFilters(r, filters) { + continue + } + if matchText != "" { + hay := strings.ToLower(asString(r["name_kwd"]) + " " + asString(r["content_with_weight"])) + if !strings.Contains(hay, strings.ToLower(matchText)) { + continue + } + } + out = append(out, r) + if topN > 0 && len(out) >= topN { + break + } + } + return out, nil +} + +func (s *stubCompiledStore) LoadChunks(_ context.Context, _, _ string, chunkIDs []string) ([]map[string]any, error) { + var out []map[string]any + for _, id := range chunkIDs { + if content, ok := s.chunks[id]; ok { + out = append(out, map[string]any{"id": id, "content": content, "doc_id": "d1"}) + } + } + return out, nil +} + +func (s *stubCompiledStore) Vectorize(_ context.Context, _ string) ([]float64, error) { + return nil, nil +} + +// scopeRecordingStore records the (kb, tenant, docs) triple of every +// SearchCompiled call and returns no rows, so only scope resolution is under +// test. +type scopeRecordingStore struct { + calls []scopeCall +} + +type scopeCall struct { + kb, tenant string + docs []string +} + +func (s *scopeRecordingStore) SearchCompiled(_ context.Context, kbID, tenantID string, docIDs []string, _ map[string][]string, _ string, _ int) ([]map[string]any, error) { + s.calls = append(s.calls, scopeCall{kb: kbID, tenant: tenantID, docs: append([]string(nil), docIDs...)}) + return nil, nil +} + +func (s *scopeRecordingStore) LoadChunks(context.Context, string, string, []string) ([]map[string]any, error) { + return nil, nil +} + +func (s *scopeRecordingStore) Vectorize(context.Context, string) ([]float64, error) { + return nil, nil +} + +// ownerRecordingStore wraps stubCompiledStore to record the owner each +// LoadChunks call is issued against. +type ownerRecordingStore struct { + *stubCompiledStore + loads []scopeCall +} + +func (s *ownerRecordingStore) LoadChunks(ctx context.Context, kbID, tenantID string, chunkIDs []string) ([]map[string]any, error) { + s.loads = append(s.loads, scopeCall{kb: kbID, tenant: tenantID, docs: append([]string(nil), chunkIDs...)}) + return s.stubCompiledStore.LoadChunks(ctx, kbID, tenantID, chunkIDs) +} + +// TestCompiledExpanderLoadsFromEachDocsOwnerAndSkipsUnresolvable mirrors Python +// _load_chunks_for_doc: a neighbour row's source chunks are fetched from THAT +// row's doc owner (not the searched scope), and a row whose doc id cannot be +// resolved (empty / merged pseudo doc) contributes nothing. +func TestCompiledExpanderLoadsFromEachDocsOwnerAndSkipsUnresolvable(t *testing.T) { + store := &ownerRecordingStore{stubCompiledStore: &stubCompiledStore{ + rows: []map[string]any{ + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "Culdcept", "content_with_weight": `{"name":"Culdcept"}`, "doc_id": "seedDoc"}, + {"knowledge_graph_kwd": "relation", "compilation_template_kind_kwd": "knowledge_graph", + "from_entity_kwd": "Culdcept", "to_entity_kwd": "OmiyaSoft", "doc_id": "seedDoc"}, + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "OmiyaSoft", "content_with_weight": `{"name":"OmiyaSoft"}`, + "source_chunk_ids": []string{"s1"}, "doc_id": "docA"}, + // No doc id -> Python's _resolve_doc_tenant fails, so its source + // chunks are dropped. + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "OmiyaSoft", "content_with_weight": `{"name":"OmiyaSoft"}`, + "source_chunk_ids": []string{"s2"}, "doc_id": ""}, + }, + chunks: map[string]string{"s1": "a", "s2": "b"}, + }} + exp := NewCompiledExpander(store, CompiledScopeConfig{ + DatasetIDs: []string{"kb1"}, + TenantID: "t1", + KBs: []*entity.Knowledgebase{{ID: "kb1", TenantID: "t1"}}, + DocTenantResolver: stubTenantResolver{owner: DocTenant{KBID: "kbOwner", TenantID: "tOwner"}}, + }).(*compiledExpander) + + kb := &Kbinfos{} + if err := exp.Expand(context.Background(), kb, "culdcept", "", nil); err != nil { + t.Fatalf("Expand: %v", err) + } + if len(store.loads) != 1 { + t.Fatalf("LoadChunks calls = %d (%+v), want 1 (the unresolvable doc must be skipped)", len(store.loads), store.loads) + } + if store.loads[0].kb != "kbOwner" || store.loads[0].tenant != "tOwner" { + t.Errorf("load owner = %+v, want the doc's own owner kbOwner/tOwner", store.loads[0]) + } + got := compiledIDs(kb.Chunks) + if len(got) != 1 || got[0] != "s1" { + t.Errorf("expanded = %v, want only s1", got) + } +} + +// TestNewCompiledExpanderGuard pins the fail-closed cases: a nil store, no bound +// dataset, or no fallback tenant leaves expansion disabled rather than searching +// an unscoped/empty index. +func TestNewCompiledExpanderGuard(t *testing.T) { + store := &scopeRecordingStore{} + if exp := NewCompiledExpander(nil, CompiledScopeConfig{DatasetIDs: []string{"kb1"}, TenantID: "t1"}); exp != nil { + t.Error("nil store must disable expansion") + } + if exp := NewCompiledExpander(store, CompiledScopeConfig{TenantID: "t1"}); exp != nil { + t.Error("no dataset must disable expansion") + } + if exp := NewCompiledExpander(store, CompiledScopeConfig{DatasetIDs: []string{"kb1"}}); exp != nil { + t.Error("no tenant must disable expansion") + } + if exp := NewCompiledExpander(store, CompiledScopeConfig{DatasetIDs: []string{"kb1"}, TenantID: "t1"}); exp == nil { + t.Error("store + dataset + tenant must enable expansion") + } +} + +// TestCompiledExpanderScansEachDatasetUnderItsOwnTenant mirrors Python +// `[(kb.id, kb.tenant_id, None) for kb in tools.kbs]`: with no doc scope each +// bound dataset is scanned under ITS OWN owner tenant, not the request tenant. +func TestCompiledExpanderScansEachDatasetUnderItsOwnTenant(t *testing.T) { + store := &scopeRecordingStore{} + exp := NewCompiledExpander(store, CompiledScopeConfig{ + DatasetIDs: []string{"kb1", "kb2"}, + TenantID: "request-tenant", + KBs: []*entity.Knowledgebase{ + {ID: "kb1", TenantID: "t1"}, + {ID: "kb2", TenantID: "t2"}, + }, + }) + if err := exp.Expand(context.Background(), &Kbinfos{}, "q", "", nil); err != nil { + t.Fatalf("Expand: %v", err) + } + if len(store.calls) == 0 { + t.Fatal("no compiled search was performed") + } + tenants := map[string]string{} + for _, c := range store.calls { + tenants[c.kb] = c.tenant + if len(c.docs) != 0 { + t.Errorf("no doc scope must be sent for %s, got %v", c.kb, c.docs) + } + if c.tenant == "request-tenant" { + t.Errorf("request tenant leaked into scope %+v; each dataset must use its owner tenant", c) + } + } + if tenants["kb1"] != "t1" || tenants["kb2"] != "t2" { + t.Errorf("per-dataset tenants = %v, want kb1=t1 kb2=t2", tenants) + } +} + +// TestCompiledExpanderGroupsDocScopeByRealOwner mirrors the doc-scope branch of +// Python _kg_scopes: documents are grouped by their real owning (kb, tenant) — +// which may lie OUTSIDE the bound datasets — and the bound list is not scanned. +func TestCompiledExpanderGroupsDocScopeByRealOwner(t *testing.T) { + store := &scopeRecordingStore{} + exp := NewCompiledExpander(store, CompiledScopeConfig{ + DatasetIDs: []string{"kb1", "kb2"}, + TenantID: "request-tenant", + KBs: []*entity.Knowledgebase{ + {ID: "kb1", TenantID: "t1"}, + {ID: "kb2", TenantID: "t2"}, + }, + DocTenantResolver: stubTenantResolver{owner: DocTenant{KBID: "kbX", TenantID: "tX"}}, + }) + if err := exp.Expand(context.Background(), &Kbinfos{}, "q", "", []string{"d1"}); err != nil { + t.Fatalf("Expand: %v", err) + } + if len(store.calls) == 0 { + t.Fatal("no compiled search was performed") + } + for _, c := range store.calls { + if c.kb != "kbX" || c.tenant != "tX" { + t.Errorf("scope = %+v, want the document's real owner kbX/tX", c) + } + if len(c.docs) != 1 || c.docs[0] != "d1" { + t.Errorf("docs = %v, want [d1]", c.docs) + } + } +} + +func rowMatchesFilters(r map[string]any, filters map[string][]string) bool { + for k, vals := range filters { + rv := asString(r[k]) + matched := false + for _, v := range vals { + if rv == v { + matched = true + break + } + } + if !matched { + return false + } + } + return true +} + +func compiledIDs(chunks []map[string]any) []string { + out := make([]string, 0, len(chunks)) + for _, c := range chunks { + out = append(out, asString(c["id"])) + } + return out +} + +// TestSeedNameFromRowParsesContentWithWeight mirrors Python L293-300: the seed +// name comes from content_with_weight JSON (name, else title), never from name_kwd. +func TestSeedNameFromRowParsesContentWithWeight(t *testing.T) { + if got := seedNameFromRow(map[string]any{"content_with_weight": `{"name":"Culdcept","title":"Game"}`}); got != "Culdcept" { + t.Errorf("name: got %q", got) + } + if got := seedNameFromRow(map[string]any{"content_with_weight": `{"title":"Released 1984"}`}); got != "Released 1984" { + t.Errorf("title fallback: got %q", got) + } + if got := seedNameFromRow(map[string]any{"content_with_weight": `not json`}); got != "" { + t.Errorf("bad json: got %q", got) + } + // name_kwd is not consulted — Python reads only the JSON payload. + if got := seedNameFromRow(map[string]any{"content_with_weight": `{}`, "name_kwd": "X"}); got != "" { + t.Errorf("name_kwd must be ignored, got %q", got) + } +} + +func TestLowerUnionSorted(t *testing.T) { + got := lowerUnionSorted(map[string]bool{"OmiyaSoft": true, "X": true}) + // Byte-order ascending over the original + lowercased forms. + want := []string{"OmiyaSoft", "X", "omiyasoft", "x"} + if len(got) != len(want) { + t.Fatalf("lowerUnionSorted = %v", got) + } + for i := range want { + if got[i] != want[i] { + t.Fatalf("lowerUnionSorted[%d] = %q, want %q (%v)", i, got[i], want[i], got) + } + } +} + +// TestExpandEntityStrategyOneHop verifies the 1-hop entity strategy: a seed +// entity matching the query (found via its template kind) walks a forward +// relation to a neighbour, resolves the neighbour by exact name_kwd, and loads +// its source chunks. +func TestExpandEntityStrategyOneHop(t *testing.T) { + store := &stubCompiledStore{ + rows: []map[string]any{ + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "Culdcept", "content_with_weight": `{"name":"Culdcept"}`}, + {"knowledge_graph_kwd": "relation", "compilation_template_kind_kwd": "knowledge_graph", + "from_entity_kwd": "Culdcept", "to_entity_kwd": "OmiyaSoft"}, + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "OmiyaSoft", "content_with_weight": `{"name":"OmiyaSoft"}`, + "source_chunk_ids": []string{"s1", "s2"}}, + }, + chunks: map[string]string{"s1": "a", "s2": "b"}, + } + exp := NewCompiledExpander(store, CompiledScopeConfig{DatasetIDs: []string{"kb1"}, TenantID: "t1"}).(*compiledExpander) + kb := &Kbinfos{} + if err := exp.Expand(context.Background(), kb, "culdcept", "", nil); err != nil { + t.Fatalf("Expand: %v", err) + } + if len(kb.Chunks) != 2 { + t.Fatalf("expanded = %d (%v), want 2 neighbour source chunks", len(kb.Chunks), compiledIDs(kb.Chunks)) + } +} + +// TestExpandBackwardRelation confirms the strategy also walks incoming +// (to_entity_kwd) relations, mirroring Python's fwd+bwd merge. +func TestExpandBackwardRelation(t *testing.T) { + store := &stubCompiledStore{ + rows: []map[string]any{ + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "mind_map", + "name_kwd": "Culdcept", "content_with_weight": `{"name":"Culdcept"}`}, + // Relation where the seed is the TARGET, not the source. + {"knowledge_graph_kwd": "relation", "compilation_template_kind_kwd": "mind_map", + "from_entity_kwd": "OmiyaSoft", "to_entity_kwd": "Culdcept"}, + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "mind_map", + "name_kwd": "OmiyaSoft", "content_with_weight": `{"name":"OmiyaSoft"}`, + "source_chunk_ids": []string{"o1"}}, + }, + chunks: map[string]string{"o1": "from"}, + } + exp := NewCompiledExpander(store, CompiledScopeConfig{DatasetIDs: []string{"kb1"}, TenantID: "t1"}).(*compiledExpander) + kb := &Kbinfos{} + if err := exp.Expand(context.Background(), kb, "culdcept", "", nil); err != nil { + t.Fatalf("Expand: %v", err) + } + if len(kb.Chunks) != 1 { + t.Fatalf("backward relation gave %d (%v), want 1", len(kb.Chunks), compiledIDs(kb.Chunks)) + } +} + +// TestExpandWikiSetsSimilarityAndBlendsByIt verifies wiki synthesis pages load +// their source chunks with a similarity boost (0.9) and the final sort puts the +// higher-similarity wiki chunk ahead of the entity (0-similarity) chunk. +func TestExpandWikiSetsSimilarityAndBlendsByIt(t *testing.T) { + store := &stubCompiledStore{ + rows: []map[string]any{ + // knowledge_graph entity 1-hop -> chunk e1 (similarity 0 by default). + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "Culdcept", "content_with_weight": `{"name":"Culdcept"}`}, + {"knowledge_graph_kwd": "relation", "compilation_template_kind_kwd": "knowledge_graph", + "from_entity_kwd": "Culdcept", "to_entity_kwd": "OmiyaSoft"}, + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "OmiyaSoft", "content_with_weight": `{"name":"OmiyaSoft"}`, + "source_chunk_ids": []string{"e1"}}, + // wiki synthesis page matching the query -> chunk w1. + {"compile_kwd": "wiki_page", "available_int": "1", "doc_id": "d2", + "name_kwd": "Culdcept", "content_with_weight": `{"title":"Culdcept article"}`, + "source_chunk_ids": []string{"w1"}}, + }, + chunks: map[string]string{"e1": "entity", "w1": "wiki"}, + } + exp := NewCompiledExpander(store, CompiledScopeConfig{DatasetIDs: []string{"kb1"}, TenantID: "t1"}).(*compiledExpander) + kb := &Kbinfos{} + if err := exp.Expand(context.Background(), kb, "culdcept", "", nil); err != nil { + t.Fatalf("Expand: %v", err) + } + if len(kb.Chunks) != 2 { + t.Fatalf("expanded = %d (%v), want 2", len(kb.Chunks), compiledIDs(kb.Chunks)) + } + var wSim, eSim float64 + for _, c := range kb.Chunks { + switch asString(c["id"]) { + case "w1": + wSim = similarityOf(c) + case "e1": + eSim = similarityOf(c) + } + } + if wSim != 0.9 { + t.Errorf("wiki similarity = %v, want 0.9", wSim) + } + if eSim != 0.0 { + t.Errorf("entity chunk similarity = %v, want 0.0", eSim) + } + // Final global sort: wiki (0.9) must rank before entity (0). + if compiledIDs(kb.Chunks)[0] != "w1" { + t.Errorf("final sort should put wiki (0.9) first, got %v", compiledIDs(kb.Chunks)) + } +} + +// TestExpandCapsMaxChunksAndSkipsSeen confirms a strategy stops adding at 5 and +// chunks already in kbinfos are not duplicated. +func TestExpandCapsMaxChunksAndSkipsSeen(t *testing.T) { + store := &stubCompiledStore{ + rows: []map[string]any{ + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "A", "content_with_weight": `{"name":"A"}`}, + {"knowledge_graph_kwd": "relation", "compilation_template_kind_kwd": "knowledge_graph", + "from_entity_kwd": "A", "to_entity_kwd": "B"}, + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "B", "content_with_weight": `{"name":"B"}`, + "source_chunk_ids": []string{"b1", "b2", "b3", "b4", "b5", "b6", "b7"}}, + }, + chunks: map[string]string{"b1": "1", "b2": "2", "b3": "3", "b4": "4", "b5": "5", "b6": "6", "b7": "7"}, + } + exp := NewCompiledExpander(store, CompiledScopeConfig{DatasetIDs: []string{"kb1"}, TenantID: "t1"}).(*compiledExpander) + // b1 is already present in the working set; it must not come back. + kb := &Kbinfos{Chunks: []map[string]any{{"id": "b1", "content": "pre-existing"}}} + if err := exp.Expand(context.Background(), kb, "a", "", nil); err != nil { + t.Fatalf("Expand: %v", err) + } + // 5 fresh (max_chunks) minus the seen b1 that was skipped within the first + // load batch -> at most 5 new. + if len(kb.Chunks) > 6 { // 1 pre-existing + up to 5 new + t.Fatalf("exceeded max_chunks=5 new chunks: got %d total (%v)", len(kb.Chunks), compiledIDs(kb.Chunks)) + } + for _, c := range kb.Chunks { + if asString(c["id"]) == "b1" && asString(c["content"]) != "pre-existing" { + t.Error("seen chunk b1 was duplicated") + } + } +} diff --git a/internal/rag/advanced_rag/harness/tool_executor.go b/internal/rag/advanced_rag/harness/tool_executor.go new file mode 100644 index 00000000000..502361baf92 --- /dev/null +++ b/internal/rag/advanced_rag/harness/tool_executor.go @@ -0,0 +1,988 @@ +// +// 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. +// + +// Package harness holds the low-level agentic-RAG capability library: the +// retrieval backend, the action-session runtime, the tool executor, and the +// compiled-structure / knowledge-graph navigation. These are the leaf building +// blocks the RAGTools methods in the parent `agent` package (Run, ComposeAnswer, +// ComposeNaiveAnswer, Formalize, ...) orchestrate. The split mirrors Python's +// layout, where agentic_rag.py's RAGTools imports the helpers under +// harness/ rather than inlining them. +// +// tool_executor.go is the Go-side tool-executor adapter: its +// searchExecutor type and the Execute dispatch correspond to the _exec_* tool +// methods in Python's harness/action_session.py (e.g. _exec_retrieve, +// _exec_navigate_tree, _exec_navigate_structure, _exec_list_chunks, +// _exec_calculate, _exec_web_search, _exec_wiki_query, _exec_graph_explore). +// In Python those live inline inside action_session.py; in Go they are pulled +// out into this file so the harness package need not import the advanced_rag package. +package harness + +import ( + "context" + "encoding/json" + "fmt" + "strings" + + "ragflow/internal/agent/runtime" + "ragflow/internal/service/nav" +) + +// RunRequest is one harness run. It lives in the harness package (not the agent +// package) because searchExecutor needs it to carry the per-run query, and the +// advanced_rag package must not be imported from here (import-cycle rule). RAGTools.Run +// in the advanced_rag package uses it via the harness package. +type RunRequest struct { + // Question is the user's question. + Question string + // ThinkingMode selects the ModeSpec ("low"/"medium"/"high"/"ultra"). + // An unrecognised value degrades to NAIVE, as in Python. + ThinkingMode string + // Keywords narrow retrieved chunks to the sentences mentioning them. + Keywords string + // DatasetIDs restricts retrieval. Empty falls back to the canvas context. + DatasetIDs []string + // TenantID scopes retrieval. Empty falls back to the canvas context. + TenantID string + // UseCompiled enables compiled-structure expansion during retrieval. + UseCompiled bool + // TopN is the per-search result count. <=0 selects the default. + TopN int + // DeadlineLeft is the wall-clock budget in seconds. <=0 selects the default. + DeadlineLeft float64 + // MaxLength is the chat model's context window (Python + // tools.chat_mdl.max_length). It bounds evidence and document-level reads. + // <=0 selects the file-level defaults. + MaxLength int + // SessionID identifies the conversation this call belongs to. It is carried + // for plumbing (e.g. future session-scoped state) but is not read by the + // near-duplicate answer cache: that cache is per-request, mirroring Python's + // per-turn RAGTools._rag_cache. + SessionID string + // Images are vision-gated base64 data URIs (Python image_attachments). The + // outer react loop turns them into multimodal content blocks on the last + // user message so a vision model sees them (advanced_rag.Rag assembles the + // message from these). + Images []string + // TextAttachments is the joined text-file content (Python + // text_attachments_content); appended to the question so the model reads + // attached documents in the reasoning path. + TextAttachments string +} + +// searchExecutor adapts SearchDeps to ToolExecutor, so the retriever and +// compiled expander are what the session's retrieval tools call. +type searchExecutor struct { + deps SearchDeps + req RunRequest +} + +// NewSearchExecutor builds the retrieval/navigation ToolExecutor used by both +// the single-session path and the agentic loop's programmatic fan-out fetches. +// +// Exported so the advanced_rag package (which cannot be imported from here) can reuse +// the same evidence handling instead of duplicating it. +func NewSearchExecutor(deps SearchDeps, req RunRequest) ToolExecutor { + return &searchExecutor{deps: deps, req: req} +} + +// Execute implements ToolExecutor for the wired tools. Tools whose port has not +// landed are classified, not errored: they report MISS (the tool is valid, this +// call reached nothing) so the model falls back to a different tool instead of +// stalling. +func (e *searchExecutor) Execute(ctx context.Context, name string, args map[string]any) (ToolOutcome, error) { + // Mirror Python rag/llm/tool_decorator.py:tool "[Function tool] Running the + // {name} tool with: {args}", one of the three namespaces Python's + // _SCOPED_PREFIXES forwarded into the think block. Python emitted it from a + // root-logging handler; Go has no root logger, so it is logged through the + // wrapped deps.Logger, which thinkLogger forwards to the think block. + if logger := e.deps.Logger; logger != nil && name != "" { + logger.Printf("[Function tool] Running the %s tool with: %s", name, renderToolArgs(args)) + } + switch name { + case "retrieve", "search_chunks", "grep_search", "grep_chunks": + return e.search(ctx, name, args) + case "navigate_tree": + return e.navigateTree(ctx, args) + case "navigate_structure": + return e.navigateStructure(ctx, args) + case "list_chunks": + return e.listChunks(ctx, args) + case "fetch_full_document": + return e.fetchFullDocument(ctx, args) + case "summarize_document": + return e.summarizeDocument(ctx, args) + case "calculate": + return e.calculate(ctx, args) + case "graph_explore": + return e.graphExplore(ctx, args) + case "web_search": + return WebSearchTool(ctx, e.deps, args) + case "wiki_query": + return e.wikiQuery(ctx, args) + } + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": name, + "note": fmt.Sprintf("%s is not wired in this deployment yet. Use retrieve, search_chunks, navigate_tree or navigate_structure.", name), + }}, + Status: StatusMiss, + Reason: ReasonNoDoc, + Metrics: map[string]any{}, + }, nil +} + +// renderToolArgs renders a tool's arguments for the "[Function tool]" think-log +// line. Python interpolated the raw args dict; Go marshals to JSON so nested +// values (scopes, tag maps) stay readable. Empty args render as "{}" to match +// Python's look rather than an empty string. +func renderToolArgs(args map[string]any) string { + if len(args) == 0 { + return "{}" + } + b, err := json.Marshal(args) + if err != nil { + return "{}" + } + return string(b) +} + +func (e *searchExecutor) fetchFullDocument(ctx context.Context, args map[string]any) (ToolOutcome, error) { + docID := argString(args, "doc_id") + if docID == "" { + return ToolOutcome{Payload: []any{}, Status: StatusError, Reason: ReasonBadArgs}, nil + } + if e.deps.DocChunks == nil { + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "fetch_full_document", + "doc_id": docID, + "note": "Whole-document reading is not available for this session.", + }}, + Status: StatusEmpty, + Reason: ReasonNoDoc, + }, nil + } + chunks, aggs := fetchFullDocument(ctx, e.deps, docID, e.req.MaxLength) + if len(chunks) == 0 { + return ToolOutcome{Payload: []any{}, Status: StatusEmpty, Reason: ReasonNoDoc}, nil + } + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "fetch_full_document", + "doc_id": docID, + "count": len(chunks), + "chunks": chunks, + "doc_aggs": aggs, + "doc_names": []string{docID}, + }}, + Status: StatusOK, + Metrics: map[string]any{"chunks": len(chunks)}, + }, nil +} + +// summarizeDocument mirrors Python's summarize_document tool: load the document +// and hand the model the freshly rendered evidence blocks. +func (e *searchExecutor) summarizeDocument(ctx context.Context, args map[string]any) (ToolOutcome, error) { + docID := argString(args, "doc_id") + if docID == "" { + return ToolOutcome{Payload: []any{}, Status: StatusError, Reason: ReasonBadArgs}, nil + } + if e.deps.DocChunks == nil { + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "summarize_document", + "doc_id": docID, + "note": "Whole-document reading is not available for this session.", + }}, + Status: StatusEmpty, + Reason: ReasonNoDoc, + }, nil + } + blocks := summarizeDocument(ctx, e.deps, docID, e.req.MaxLength) + if len(blocks) == 0 { + return ToolOutcome{Payload: []any{}, Status: StatusEmpty, Reason: ReasonNoDoc}, nil + } + content := "" + for _, b := range blocks { + content += b + "\n\n" + } + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "summarize_document", + "doc_id": docID, + "content": content, + }}, + Status: StatusOK, + Metrics: map[string]any{"blocks": len(blocks)}, + }, nil +} + +// navigateTree routes to the top-n documents by descending the dataset's compiled +// navigation tree, reporting three outcomes for the ladder to act on: +// - no router configured → EMPTY/no_structure (disable the tool, dataset-level); +// - tree exists but this query routed to nothing → MISS (fall through to +// `global`, do NOT disable); +// - routed → OK with the doc ids and their summaries. +func (e *searchExecutor) navigateTree(ctx context.Context, args map[string]any) (ToolOutcome, error) { + query := argString(args, "query") + if query == "" { + return ToolOutcome{Payload: []any{}, Status: StatusError, Reason: ReasonBadArgs}, nil + } + router := e.deps.NavRouter + if router == nil { + // Default navigation-tree router mirrors Python _NAV_TREE_ROUTER = "chunk_agg": + // route documents by aggregating raw-chunk retrieval rather than by a nav-row + // KNN descent (nav.NewNavServiceRouter). A nil retrieval backend degrades to the + // nav-row router, which needs no backend. + if e.deps.Backend != nil { + router = nav.NewChunkAggRouter( + chunkAggRetrieveFrom(e.deps.Backend), + nav.ChunkAggSummarize(), + ) + } else { + router = nav.NewNavServiceRouter() + } + } + // The tool argument is NOT threaded (Python _exec_navigate_tree, + // action_session.py:_exec_navigate_tree, calls _navigate_tree_impl(query, keywords=...) with + // no doc_scope), but the SESSION scope still applies: the impl routes through + // _nav_search_titled, which ceilings its scope with tools.scoped_doc_ids(None) + // — the session doc_scope (navigation.py:_nav_search_titled). The router must therefore + // receive the session ceiling, never the tool argument. + res := NavigateTree(ctx, router, NavTreeInput{ + Query: query, + Keywords: e.req.Keywords, + DocScope: e.deps.DocScope, + TenantID: e.deps.TenantID, + KbIDs: e.deps.KbIDs, + }) + + switch res.EmptyReason { + case ReasonNoStructure: + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "navigate_tree", + "note": "This dataset has no compiled document-navigation tree. Use search_chunks / retrieve instead.", + "query": query, + "doc_ids": []string{}, + }}, + Status: StatusEmpty, + Reason: ReasonNoStructure, + Metrics: map[string]any{"docs": 0, "routed_docs": [][2]string{}}, + }, nil + case ReasonNoDoc: + // Structure exists, this query reached nothing — a MISS, not an EMPTY. + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "navigate_tree", + "content": res.Text, + "doc_ids": []string{}, + "note": "The navigation tree exists but this query routed to no document. Try a different topic/entity phrasing, or use search_chunks.", + "query": query, + }}, + Status: StatusMiss, + Reason: ReasonNoDoc, + Metrics: map[string]any{"docs": 0}, + }, nil + case ReasonInfra, ReasonBadArgs: + return ToolOutcome{ + Payload: []any{}, + Status: ReasonStatus(res.EmptyReason), + Reason: res.EmptyReason, + }, nil + } + + // Routed: expose the summary-bearing payload the ladder consumes. + payload := []any{map[string]any{ + "kind": "navigate_tree", + "content": res.Text, + "doc_ids": res.DocIDs, + }} + return ToolOutcome{ + Payload: payload, + EvidenceIDs: nil, // routing only — no passages retrieved + Status: StatusOK, + Reason: ReasonNone, + Metrics: map[string]any{ + "docs": len(res.DocIDs), + "routed_docs": res.RoutedDocs, + }, + }, nil +} + +// chunkAggRetrieveFrom adapts a harness Retriever into the chunk_agg retrieve +// leg. It scopes the search to the dataset (kbID) and the caller's document +// scope and pulls the wide pool chunk_agg needs; the backend is expected to +// exclude compiled rows (the production retrieval filters available_int=1), +// mirroring Python settings.retriever.retrieval under _search_layers_nav_chunk_agg. +// +// It stays in the harness package because it depends on the agentic Retriever / +// RetrieveRequest; the routing algorithm itself lives in internal/service/nav. +func chunkAggRetrieveFrom(r Retriever) nav.ChunkRetriever { + return func(ctx context.Context, tenantID, kbID, query string, docScope []string, topN int, _ float64) []map[string]any { + chunks, err := r.Retrieve(ctx, RetrieveRequest{ + Query: query, + DatasetIDs: []string{kbID}, + TenantID: tenantID, + DocScope: docScope, + TopN: topN, + }) + if err != nil || len(chunks) == 0 { + return nil + } + return chunks + } +} + +// navigateStructure pinpoints passages inside ONE document using its compiled +// structure (heading tree / concept mindmap). +// +// It delegates to the navigation package's NavigateStructure, which loads the +// document's compiled rows, asks the model which entities answer the query, and +// returns the underlying source chunks. +// +// NOTE on shapes: the Go reader (navigation.loadStructureEntities) currently +// reads only the compact graph-blob rows, whereas Python merges BOTH row shapes +// (graph blob AND per-entity/relation rows). ParseCompiledStructure in +// navtools.go already implements the merged parsing; wiring it into the reader +// is the remaining step for full parity. +func (e *searchExecutor) navigateStructure(ctx context.Context, args map[string]any) (ToolOutcome, error) { + query := argString(args, "query") + docID := argString(args, "doc_id") + if query == "" { + query = e.req.Question + } + if query == "" { + return ToolOutcome{Payload: []any{}, Status: StatusError, Reason: ReasonBadArgs}, nil + } + // No scope-as-doc-pin: Python _exec_navigate_structure + // reads only args["doc_id"] — args["doc_scope"] is never consulted. + kind := argString(args, "kind") + if kind == "" { + kind = "catalog" + } + + // Resolve the document set. When the caller omits doc_id, mirror Python + // _navigate_structure_impl: route to the documents by descending the compiled + // navigation tree (the exact seam navigate_tree uses), not by refusing the + // call. Python's _nav_search_titled caps the routed set at _NAV_TREE_MAX_DOCS. + var docIDs []string + if docID != "" { + docIDs = []string{docID} + } else { + // DocScope is the session ceiling, not the tool argument (see the note in + // navigateTree): Python's _exec_navigate_structure never threads + // args["doc_scope"], but the routing it does when doc_id is absent goes + // through _nav_search_titled, which applies tools.scoped_doc_ids(None) + // (navigation.py:_nav_search_titled / :1012). + res := NavigateTree(ctx, e.navRouter(), NavTreeInput{ + Query: query, + Keywords: e.req.Keywords, + DocScope: e.deps.DocScope, + TenantID: e.deps.TenantID, + KbIDs: e.deps.KbIDs, + }) + if res.EmptyReason == ReasonInfra { + return ToolOutcome{Payload: []any{}, Status: ReasonStatus(res.EmptyReason), Reason: res.EmptyReason}, nil + } + docIDs = res.DocIDs + if len(docIDs) > navTreeMaxDocs { + docIDs = docIDs[:navTreeMaxDocs] + } + if len(docIDs) == 0 { + // Routing reached no document (Python: empty_reason="no_doc"). + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "navigate_structure", + "note": "The query routed to no document in this dataset. Try a different topic/entity phrasing, pass doc_id, or use search_chunks.", + "query": query, + "doc_ids": []string{}, + }}, + Status: StatusMiss, + Reason: ReasonNoDoc, + }, nil + } + } + + // Zero-LLM vector-beam drill-down (mirrors Python _read_structures + + // _navigate_structure_impl): read each document's compiled structure of the + // requested kind, drill toward the query, and hand the model the merged + // outline with chunk-pointer anchors. + res, drill := navigateStructures(ctx, e.deps.TenantID, query, docIDs, kind, e.navRouter(), e.deps) + metrics := map[string]any{ + "entities": drill.nodes, + "chunk_ptrs": drill.chunkPtrs, + "top_score": drill.topScore, + "chunk_paths": drill.chunkPaths, + } + if res.EmptyReason != "" { + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "navigate_structure", + "note": fmt.Sprintf("No compiled structure of kind=%q reachable for the located document(s). Try another kind, or use search_chunks / retrieve / list_chunks.", kind), + "doc_ids": docIDs, + }}, + Status: ReasonStatus(res.EmptyReason), + Reason: res.EmptyReason, + Metrics: metrics, + }, nil + } + // Reached structures but drilled to nothing usable: not an error, just weak — + // the orchestrator falls back to retrieval on status == poor. + status := StatusOK + if drill.chunkPtrs == 0 { + status = StatusPoor + } + content := res.Text + if len(content) > 8000 { + content = content[:8000] + } + evidenceIDs := res.DocIDs + if len(evidenceIDs) == 0 && len(docIDs) > 0 { + evidenceIDs = docIDs + } + return ToolOutcome{ + Payload: []any{map[string]any{"kind": "navigate_structure", "doc_id": firstOr(docIDs, ""), "content": content}}, + EvidenceIDs: evidenceIDs, + Status: status, + Reason: ReasonNone, + Metrics: metrics, + }, nil +} + +// navRouter returns the navigation-tree router navigateTree and navigateStructure +// share (mirrors Python's _NAV_TREE_ROUTER = "chunk_agg"; a nil retrieval backend +// degrades to the nav-row router, which needs no backend). +func (e *searchExecutor) navRouter() NavTreeRouter { + if e.deps.NavRouter != nil { + return e.deps.NavRouter + } + if e.deps.Backend != nil { + return nav.NewChunkAggRouter( + chunkAggRetrieveFrom(e.deps.Backend), + nav.ChunkAggSummarize(), + ) + } + return nav.NewNavServiceRouter() +} + +func firstOr(xs []string, def string) string { + if len(xs) > 0 { + return xs[0] + } + return def +} + +// argString reads a string arg, treating an absent key or an explicit JSON null +// as empty. fmt.Sprint(nil) yields "", so the presence check must come +// first — otherwise a missing arg silently becomes the literal "". +func argString(args map[string]any, key string) string { + raw, ok := args[key] + if !ok || raw == nil { + return "" + } + s := strings.TrimSpace(fmt.Sprint(raw)) + if s == "" { + return "" + } + return s +} + +// search runs one retrieval call for a tool invocation. +// +// Python's retrieve/search_chunks both funnel into tools/search.py, differing +// only in whether compiled expansion runs (search_chunks expands, retrieve does +// not) and in the accepted query count. +func (e *searchExecutor) search(ctx context.Context, name string, args map[string]any) (ToolOutcome, error) { + queries := toolQueries(args) + if len(queries) == 0 { + // Python _arg_query_list yields [] for a missing/blank query and + // _run_search simply admits nothing: _search_outcome([], ...) is + // MISS/no_doc (action_session.py:_search_outcome), NOT a bad-args error. + return ToolOutcome{ + Payload: []any{}, + EvidenceIDs: nil, + Status: StatusMiss, + Reason: ReasonNoDoc, + Metrics: map[string]any{"hits": 0, "new_evidence": 0}, + }, nil + } + // Python's retrieval tools run against tools.kbinfos, and _seed_evidence + // (action_session.py:_admit_evidence) CREATES it when absent — so every search has a + // (possibly empty) pool to admit into. Mirror that instead of bailing out: + // the search runs and its outcome is decided by what it actually admitted. + if e.deps.KB == nil { + e.deps.KB = &Kbinfos{} + } + + // Max queries per tool call mirrors Python action_session.execute_tool + // (_arg_query_list): retrieve=3, search_chunks=2. grep_search/grep_chunks + // are Go-internal tools (Python exposes no such session tool), so they are + // left uncapped. + maxQ := len(queries) + switch name { + case "retrieve": + maxQ = 3 + case "search_chunks": + maxQ = 2 + } + if len(queries) > maxQ { + queries = queries[:maxQ] + } + + var payload []any + var evidenceIDs []string + newChunks := 0 + // Per-call admittance state, mirroring Python _run_search/_admit_evidence + // (action_session.py:_run_search): `seen` dedups chunks ACROSS the queries of + // this one call; kbSeen holds the shared pool's existing identities + // (Python `kb_seen`). + seen := map[string]bool{} + kbSeen := make(map[string]bool, len(e.deps.KB.Chunks)) + for _, c := range e.deps.KB.Chunks { + kbSeen[chunkKey(c)] = true + } + for _, q := range queries { + // Per-tool top_n (mirrors Python action_session: retrieve=10, + // search_chunks=20). They were previously collapsed onto e.req.TopN, + // so search_chunks returned far fewer candidates than Python. + topN := 10 + if name == "search_chunks" { + topN = 20 + } + // Python dispatches these tools to genuinely different search functions + // (action_session.py:_exec_retrieve :751): retrieve/grep_* → grep_search + // (keyword-only), search_chunks → hybrid_search (vector leg when an + // embedder is configured). Each is now its own Go function so a single + // global switch can no longer disable the semantic leg. + // + // Python's search_chunks tool ALWAYS enables compiled-structure expansion + // (action_session.py:execute_tool passes use_compiled=True); retrieve/grep_search + // never do. So Go mirrors that: compiled is on for search_chunks and off + // for every other retrieve-family tool, independent of e.req.UseCompiled + // (which gates the L1 direct retrieve, not the action_session tool loop). + var searchFn func(context.Context, SearchDeps, SearchParams) ([]map[string]any, []map[string]any) + useCompiled := name == "search_chunks" + if useCompiled { + searchFn = HybridSearch + } else { + searchFn = GrepSearch + } + // Keywords mirror the two Python executors exactly: + // - retrieve → grep_search(keywords=nav_hint or None). In Python the + // nav hint is an explicit PARAMETER of _exec_retrieve and is passed + // ONLY by the navigation ladder (action_session.py:_run_drill_merge); the model's + // own retrieve dispatch (:1022) passes none, in which case grep_search + // falls back to the query's own extracted terms (search.py:grep_search) — + // that fallback lives in GrepSearch, which turns them into the BM25 + // hint. The session run keywords (req.Keywords) are never forwarded. + // - search_chunks → _exec_search_chunks (:751) takes no keywords at all, + // so hybrid_search's _narrow_or_keep is a no-op. + var kws string + if !useCompiled { + kws = argString(args, "nav_hint") + } + // doc_scope is honoured by the retrieve family only: Python's + // _exec_retrieve reads args["doc_scope"], while + // _exec_search_chunks (:751) takes no doc_scope at all and its + // hybrid_search call is unscoped. Gating on useCompiled keeps that split. + var docScope []string + if !useCompiled { + docScope = toolDocScope(args) + } + // Python _run_search reads only res["chunks"], but the aggregations it + // drops are what the answer's document/reference list is built from — + // this tool is their only writer. + chunks, aggs := searchFn(ctx, e.deps, SearchParams{ + Question: q, + Keywords: kws, + UseCompiled: useCompiled, + TopN: topN, + KbIDs: e.req.DatasetIDs, + DocScope: docScope, + }) + if len(chunks) == 0 { + continue + } + // Only the first snippetsPerQuery (4) hits of each query are considered + // (Python cands[:_SNIPPETS_PER_QUERY]). + if len(chunks) > snippetsPerQuery { + chunks = chunks[:snippetsPerQuery] + } + // Admittance mirrors _admit_evidence exactly: per-call dedup by chunk + // id, the chunk ID as the evidence reference (Python's `ids` holds ids, + // not pool positions), and only chunks NEW to the shared pool appended + // to it — so REDUNDANT means "nothing new", not "nothing returned". + for _, c := range chunks { + cid := ChunkIDOf(c) + if seen[cid] { + continue + } + seen[cid] = true + evidenceIDs = append(evidenceIDs, cid) + payload = append(payload, passageFromChunk(c)) + // Pool identity uses chunkKey (Go's stable key): Python's _chunk_key + // falls back to id(ck) — the dict's address — so an equivalent + // re-retrieved chunk never matches and is appended again. + key := chunkKey(c) + if !kbSeen[key] { + kbSeen[key] = true + e.deps.KB.Chunks = append(e.deps.KB.Chunks, c) + newChunks++ + } + } + // Pool this search's doc_aggs (skipped when it returned no chunks, like + // _merge_kbinfos). + e.deps.KB.MergeDocAggs(aggs) + } + + if len(payload) == 0 { + return ToolOutcome{ + Payload: []any{}, + EvidenceIDs: nil, + Status: StatusMiss, + Reason: ReasonNoDoc, + Metrics: map[string]any{"hits": 0, "new_evidence": 0}, + }, nil + } + // Zero new evidence (every hit was already in the pool) is REDUNDANT, not + // OK. Python _search_outcome still returns the + // FULL payload here — the model sees the passages AND a redundant status, so + // it knows the ground is already covered. The session tool node appends the + // "ALREADY in your evidence" note on StatusRedundant, + // which is what stops the re-issue; dropping the payload (as an earlier port + // did) hid the evidence the model needs and is the divergence from Python. + if newChunks == 0 { + return ToolOutcome{ + Payload: payload, + EvidenceIDs: evidenceIDs, + Status: StatusRedundant, + Reason: ReasonNone, + Metrics: map[string]any{"hits": len(payload), "new_evidence": 0}, + }, nil + } + return ToolOutcome{ + Payload: payload, + EvidenceIDs: evidenceIDs, + Status: StatusOK, + Reason: ReasonNone, + Metrics: map[string]any{"hits": len(payload), "new_evidence": newChunks}, + }, nil +} + +// calculate mirrors Python's calculate tool (action_session.py:_exec_calculate): derive a +// number the evidence does not state outright, by having the model write ONE +// expression and evaluating it against the AST whitelist (see arithmetic.go). +// +// The computed value is returned as evidence, so a later answer step can cite it +// without re-deriving. Nothing derivable is POOR/no_doc, not an error — the model +// then answers from the facts it already has. +func (e *searchExecutor) calculate(ctx context.Context, args map[string]any) (ToolOutcome, error) { + // Python validates NOTHING here: an absent question or fact list flows into + // compute_from_facts, whose own `if not question or not facts` guard returns + // None — a POOR/no_doc "nothing derivable", never a bad-args error. There is + // no fallback to the run question either. + question := argString(args, "question") + facts := make([]string, 0, 8) + for _, f := range toolStringList(args, "facts") { + if s := strings.TrimSpace(f); s != "" { + facts = append(facts, s) + } + } + if e.deps.Model == nil { + // Python :946-948 — no chat model is an INFRA failure, checked BEFORE any + // derivation, with the payload Python emits verbatim. + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "calculate", + "error": "no model", + }}, + Status: StatusError, + Reason: ReasonInfra, + Metrics: map[string]any{}, + }, nil + } + cf := ComputeFromFacts(ctx, e.deps.Model, question, facts, 0) + if cf == nil { + // Nothing derivable is POOR/no_doc (Python :954-960), with Python's note. + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "calculate", + "expression": nil, + "note": "no numeric answer derivable from given facts; answer directly or retrieve more numbers.", + }}, + Status: StatusPoor, + Reason: ReasonNoDoc, + Metrics: map[string]any{}, + }, nil + } + // Python :961 — the success payload is exactly {"kind","expression","result"}; + // the label/uses the model returned are deliberately NOT echoed back. + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "calculate", + "expression": cf.Expression, + "result": cf.Value, + }}, + Status: StatusOK, + Reason: ReasonNone, + Metrics: map[string]any{}, + }, nil +} + +// toolStringList reads a string-list arg, tolerating []any, []string, and a +// single string (models emit all three). +func toolStringList(args map[string]any, key string) []string { + raw, ok := args[key] + if !ok || raw == nil { + return nil + } + switch v := raw.(type) { + case []string: + return v + case []any: + out := make([]string, 0, len(v)) + for _, item := range v { + if item == nil { + continue + } + out = append(out, fmt.Sprint(item)) + } + return out + case string: + return []string{v} + } + return nil +} +func toolQueries(args map[string]any) []string { + raw, ok := args["query"] + if !ok || raw == nil { + // Absent (or an explicit null, which JSON models emit) falls back to the + // `q` alias before giving up. + if q, ok := args["q"].(string); ok && strings.TrimSpace(q) != "" { + return []string{strings.TrimSpace(q)} + } + return nil + } + switch v := raw.(type) { + case string: + if strings.TrimSpace(v) == "" { + return nil + } + return []string{v} + case []any: + out := make([]string, 0, len(v)) + for _, item := range v { + if s := strings.TrimSpace(fmt.Sprint(item)); s != "" { + out = append(out, s) + } + } + return out + case []string: + out := make([]string, 0, len(v)) + for _, s := range v { + if strings.TrimSpace(s) != "" { + out = append(out, s) + } + } + return out + } + return nil +} + +// toolDocScope reads the optional doc_scope restriction — the tool argument +// Python parses in exactly two dispatchers: retrieve (action_session.py:execute_tool) +// and graph_explore (:977). Both do +// +// [str(d) for d in (args.get("doc_scope") or []) if str(d).strip()] +// +// so ONLY the "doc_scope" key is honoured: there is deliberately NO "doc_ids" +// alias and NO bare-string coercion (Python would iterate a string char-wise; +// no tool schema advertises either key, so both cases are unreachable). The +// other tools that used to call this — search_chunks, navigate_tree, +// navigate_structure — must NOT read a scope: Python's _exec_search_chunks, +// _exec_navigate_tree and _exec_navigate_structure never thread args["doc_scope"] +// into their impls. +func toolDocScope(args map[string]any) []string { + raw, ok := args["doc_scope"] + if !ok { + return nil + } + var items []string + switch v := raw.(type) { + case []string: + items = v + case []any: + items = make([]string, 0, len(v)) + for _, item := range v { + items = append(items, fmt.Sprint(item)) + } + default: + return nil + } + out := make([]string, 0, len(items)) + for _, s := range items { + if s = strings.TrimSpace(s); s != "" { + out = append(out, s) + } + } + return out +} + +// passageFromChunk renders one chunk as the passage dict the model sees: the keys +// of Python _admit_evidence (:667-673) — {"id", "content", "doc_id"}, no title and +// no query. The id must stay under "id": the drill merge reads it as entry["id"], +// so a "chunk_id" key silently disables the drill's structure_path attachment. +func passageFromChunk(c map[string]any) map[string]any { + // Table chunks pass through un-truncated: the 1200-char cap would hide rows + // mid/late in a long standings table. + var content string + if IsTableChunk(c) { + content = ChunkTextOf(c) + } else { + // Python _admit_evidence: content = _ct[:1200], a plain slice (no trim, + // no ellipsis). + content = truncateRunes(ChunkTextOf(c), 1200) + } + return map[string]any{ + "id": ChunkIDOf(c), + "content": content, + "doc_id": DocIDOf(c), + } +} + +// PublishReferences writes the accumulated evidence into the canvas state so the +// agent's post-stream citation grounding can read it. +// +// Chunk and aggregation shapes match runtime's referenceChunksFromRetrieval / +// referenceDocAggsFromRetrieval (which dual-write both Python and Go field +// names), so no translation is needed by the consumer. Exported because the +// caller sits in the parent advanced_rag package (agentic_rag.go), not +// inside harness. +func PublishReferences(ctx context.Context, kb *Kbinfos) { + state, _, err := runtime.GetStateFromContext[*runtime.CanvasState](ctx) + if err != nil || state == nil { + return + } + chunks := make([]map[string]any, 0, len(kb.Chunks)) + for idx, c := range kb.Chunks { + chunkID := ChunkIDOf(c) + docID := DocIDOf(c) + name := DocTitleOf(c) + content := ChunkTextOf(c) + datasetID := DatasetIDOf(c) + chunks = append(chunks, map[string]any{ + "id": fmt.Sprint(idx), + "chunk_id": chunkID, + "content": content, + "content_with_weight": content, + "document_id": docID, + "doc_id": docID, + "document_name": name, + "docnm_kwd": name, + "dataset_id": datasetID, + "kb_id": datasetID, + }) + } + state.SetRetrievalReferences(chunks, kb.DocAggs) +} + +// RuntimeRetriever adapts runtime.GetRetrievalService() to the harness Retriever +// interface. The service is read on every call (not captured at construction) +// because the server installs it during boot, which may happen after a harness +// component was built. +// +// This is the only place in the harness that knows about internal/agent/runtime; +// it lives in the harness root package (not a sub-package) so the runtime +// dependency does not leak into the harness's testable core. +// RuntimeRetriever is the production harness retriever. It mirrors Python's +// settings.retriever: it runs the backend search and returns the normalised +// chunks. Child-fragment promotion (retrieval_by_children) is NOT done here — +// it is entry-point specific (only hybrid_search / RAGTools.retrieve do it in +// Python, search.py:_normalize / agentic_rag.py:RAGTools.retrieve), so it lives in runSearch, gated +// by searchOpts.promoteChildren, and this Backend stays caller-agnostic. +type RuntimeRetriever struct{} + +func (r *RuntimeRetriever) Retrieve(ctx context.Context, req RetrieveRequest) ([]map[string]any, error) { + svc := runtime.GetRetrievalService() + chunks, err := svc.Search(ctx, nil, runtime.RetrievalRequest{ + Query: req.Query, + DatasetIDs: req.DatasetIDs, + DocScope: req.DocScope, + TopN: req.TopN, + TopK: req.TopK, + RerankCandidatesCount: req.RerankCandidatesCount, + SimilarityThreshold: &req.SimilarityThreshold, + KeywordsSimilarityWeight: &req.KeywordsSimilarityWeight, + TenantID: req.TenantID, + RankFeature: req.RankFeature, + // ExcludeCompiled maps Python hybrid_search's + // must_not={"exists":"compile_kwd"} onto the runtime request's + // OnlyOriginalText (the "no compile_kwd" exclusion). + OnlyOriginalText: req.ExcludeCompiled, + }) + if err != nil { + return nil, err + } + return chunksToMaps(chunks), nil +} + +// chunksToMaps normalises runtime.RetrievalChunk values into the harness chunk +// shape (the keys the rest of the harness expects: chunk_id / content / doc_id +// / docnm_kwd / ...). +func chunksToMaps(chunks []runtime.RetrievalChunk) []map[string]any { + out := make([]map[string]any, 0, len(chunks)) + for _, c := range chunks { + out = append(out, map[string]any{ + "chunk_id": c.ID, + "content": c.Content, + "doc_id": c.DocumentID, + "docnm_kwd": c.DocumentName, + "dataset_id": c.DatasetID, + "kb_id": c.DatasetID, + "mom_id": c.MomID, + "similarity": c.Score, + "image_id": c.ImageID, + "url": c.URL, + "positions": c.Positions, + "chunk_order_int": c.ChunkIndex, + "page_num_int": c.PageNum, + "score": c.Score, + "term_similarity": c.TermSimilarity, + "vector_similarity": c.VectorSimilarity, + }) + } + return out +} + +// TenantIDFromContext returns the tenant id bound on the canvas context, used as +// a fallback for SearchDeps.TenantID when the caller's SearchRequest leaves it +// empty. The harness stays independent of the tool registry, so it reads only +// what CanvasState.GetVar exposes. Exported so the advanced_rag package's Run can call +// it. +func TenantIDFromContext(ctx context.Context) string { + state, _, err := runtime.GetStateFromContext[*runtime.CanvasState](ctx) + if err != nil || state == nil { + return "" + } + if tid, err := state.GetVar("tenant_id"); err == nil { + if s, _ := tid.(string); s != "" { + return s + } + } + return "" +} diff --git a/internal/rag/advanced_rag/harness/tool_executor_test.go b/internal/rag/advanced_rag/harness/tool_executor_test.go new file mode 100644 index 00000000000..2af207ce097 --- /dev/null +++ b/internal/rag/advanced_rag/harness/tool_executor_test.go @@ -0,0 +1,762 @@ +// +// 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. +// +// 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. + +package harness + +import ( + "bytes" + "context" + "fmt" + "log" + "strings" + "testing" + + "gorm.io/gorm" + "ragflow/internal/agent/runtime" + "ragflow/internal/engine" +) + +// stubRetrievalService returns a fixed set of child chunks so the harness +// retireval path can be exercised without a live search backend. +type stubRetrievalService struct { + chunks []runtime.RetrievalChunk +} + +func (s stubRetrievalService) Search(_ context.Context, _ *gorm.DB, _ runtime.RetrievalRequest) ([]runtime.RetrievalChunk, error) { + return s.chunks, nil +} + +// stubDocEngine implements engine.DocEngine by only serving GetChunk; the rest +// of the (large) interface is promoted from a nil field and never called by +// this test. +type stubDocEngine struct { + engine.DocEngine + parents map[string]map[string]any +} + +func (s stubDocEngine) GetChunk(_ context.Context, _, chunkID string, _ []string) (interface{}, error) { + if p, ok := s.parents[chunkID]; ok { + return p, nil + } + return nil, fmt.Errorf("parent %s not found", chunkID) +} + +// TestRuntimeRetrieverPromotesChildrenToParent verifies that +// RuntimeRetriever.Retrieve threads child chunks through retrieval_by_children: +// two child fragments sharing a mom_id collapse into the single parent chunk, +// mirroring Python settings.retriever.retrieval_by_children. +func TestRuntimeRetrieverPromotesChildrenToParent(t *testing.T) { + prev := runtime.GetRetrievalService() + runtime.SetRetrievalService(stubRetrievalService{chunks: []runtime.RetrievalChunk{ + {ID: "child-1", Content: "frag one", DatasetID: "kb-1", MomID: "parent-1", Score: 0.6}, + {ID: "child-2", Content: "frag two", DatasetID: "kb-1", MomID: "parent-1", Score: 0.8}, + {ID: "top-1", Content: "standalone", DatasetID: "kb-1", Score: 0.9}, + }}) + t.Cleanup(func() { runtime.SetRetrievalService(prev) }) + + de := stubDocEngine{parents: map[string]map[string]any{ + "parent-1": { + "chunk_id": "parent-1", + "content_with_weight": "the full parent chunk text", + "doc_id": "doc-1", + "docnm_kwd": "doc.pdf", + "kb_id": "kb-1", + "doc_type_kwd": "pdf", + }, + }} + + deps := SearchDeps{ + Backend: &RuntimeRetriever{}, + DocEngine: de, + TenantID: "tenant-1", + } + out, aggs := HybridSearch(context.Background(), deps, SearchParams{ + Question: "q", + KbIDs: []string{"kb-1"}, + }) + _ = aggs + if len(out) == 0 { + t.Fatal("HybridSearch returned no chunks") + } + + // parent-1 (from child-1 + child-2) + top-1 = 2 chunks. + if len(out) != 2 { + t.Fatalf("expected 2 aggregated chunks, got %d: %v", len(out), out) + } + var parent, top map[string]any + for _, c := range out { + if c["chunk_id"] == "parent-1" { + parent = c + } + if c["chunk_id"] == "top-1" { + top = c + } + } + if parent == nil { + t.Fatalf("parent chunk missing from result: %v", out) + } + if top == nil { + t.Fatalf("top-level chunk missing from result: %v", out) + } + // similarity is the average of the two child scores (0.6, 0.8) -> 0.7. + if sim, ok := parent["similarity"].(float64); !ok || sim != 0.7 { + t.Fatalf("expected parent similarity 0.7, got %v", parent["similarity"]) + } + if pw, _ := parent["content_with_weight"].(string); pw != "the full parent chunk text" { + t.Fatalf("expected parent content_with_weight, got %v", parent["content_with_weight"]) + } + if v, ok := parent["mom_id"]; ok && v != "" { + t.Fatalf("aggregated parent should no longer carry a mom_id, got %v", v) + } +} + +// TestHybridSearchSkipsWhenNoChildren verifies that chunks without a mom_id +// pass through unchanged and retrieval_by_children is a no-op for them. +func TestHybridSearchSkipsWhenNoChildren(t *testing.T) { + prev := runtime.GetRetrievalService() + runtime.SetRetrievalService(stubRetrievalService{chunks: []runtime.RetrievalChunk{ + {ID: "top-1", Content: "a", DatasetID: "kb-1", Score: 0.5}, + }}) + t.Cleanup(func() { runtime.SetRetrievalService(prev) }) + + deps := SearchDeps{Backend: &RuntimeRetriever{}, TenantID: "tenant-1"} + out, _ := HybridSearch(context.Background(), deps, SearchParams{Question: "q", KbIDs: []string{"kb-1"}}) + if len(out) != 1 || out[0]["chunk_id"] != "top-1" { + t.Fatalf("expected unchanged single chunk, got %v", out) + } +} + +// TestBM25SearchDoesPromoteChildren verifies that bm25_search (like every other +// entry point) runs retrieval_by_children: a child fragment is lifted to its +// parent chunk. This mirrors Python search.py:bm25_search, which routes +// through _normalize (which calls retrieval_by_children). +func TestBM25SearchDoesPromoteChildren(t *testing.T) { + prev := runtime.GetRetrievalService() + runtime.SetRetrievalService(stubRetrievalService{chunks: []runtime.RetrievalChunk{ + {ID: "child-1", Content: "frag", DatasetID: "kb-1", MomID: "parent-1", Score: 0.6}, + }}) + t.Cleanup(func() { runtime.SetRetrievalService(prev) }) + + // DocEngine is set, so BM25Search promotes the child to its parent. + deps := SearchDeps{Backend: &RuntimeRetriever{}, DocEngine: stubDocEngine{parents: map[string]map[string]any{ + "parent-1": {"chunk_id": "parent-1", "content_with_weight": "the full parent chunk text", "doc_id": "doc-1"}, + }}, TenantID: "tenant-1"} + out, _ := BM25Search(context.Background(), deps, SearchParams{Question: "q", KbIDs: []string{"kb-1"}}) + if len(out) != 1 || out[0]["chunk_id"] != "parent-1" { + t.Fatalf("bm25_search must promote the child to its parent, got %v", out) + } +} + +// TestExecuteLogsFunctionToolLine covers the Python tool_decorator.py:tool_call_async line +// "[Function tool] Running the {name} tool with: {args}", which Python's +// _SCOPED_PREFIXES forwarded into the think block. +func TestExecuteLogsFunctionToolLine(t *testing.T) { + var buf bytes.Buffer + deps := SearchDeps{Logger: log.New(&buf, "", 0)} + ex := NewSearchExecutor(deps, RunRequest{}) + + // "calculate" is a local tool; no backend is configured, so the call may + // fail. The think-log line must be emitted regardless of the outcome. + _, _ = ex.Execute(context.Background(), "calculate", map[string]any{"expr": "1+1"}) + + out := buf.String() + if !strings.Contains(out, "[Function tool] Running the calculate tool with:") { + t.Fatalf("missing [Function tool] line, got:\n%s", out) + } + if !strings.Contains(out, `"expr":"1+1"`) { + t.Errorf("args not rendered, got:\n%s", out) + } +} + +// TestExecuteNoLoggerIsSafe guards the nil-Logger path (Logger is optional). +func TestExecuteNoLoggerIsSafe(t *testing.T) { + ex := NewSearchExecutor(SearchDeps{}, RunRequest{}) + if _, err := ex.Execute(context.Background(), "calculate", map[string]any{"expr": "2+2"}); err == nil { + t.Log("call succeeded; nil logger must not panic") + } +} + +// TestSearchChunksAlwaysUsesCompiled pins fix #2: Python's search_chunks tool +// ALWAYS enables compiled-structure expansion (action_session.py:execute_tool passes +// use_compiled=True); retrieve never does. The Go executor must mirror that and +// NOT gate it on RunRequest.UseCompiled (which controls the L1 direct retrieve). +func TestSearchChunksAlwaysUsesCompiled(t *testing.T) { + // search_chunks must expand (independent of req.UseCompiled). + deps, _ := newTestSearchDeps(&stubRetriever{chunks: []map[string]any{{"content": "hit", "chunk_id": "c1"}}}) + deps.Expand = &stubExpander{} + ex := NewSearchExecutor(deps, RunRequest{DatasetIDs: []string{"kb1"}}) + if _, err := ex.Execute(context.Background(), "search_chunks", map[string]any{"query": "q"}); err != nil { + t.Fatalf("search_chunks: %v", err) + } + if deps.Expand.(*stubExpander).calls != 1 { + t.Errorf("search_chunks compiled expansion calls = %d, want 1", deps.Expand.(*stubExpander).calls) + } + + // retrieve must NOT expand. + deps2, _ := newTestSearchDeps(&stubRetriever{chunks: []map[string]any{{"content": "hit", "chunk_id": "c1"}}}) + deps2.Expand = &stubExpander{} + ex2 := NewSearchExecutor(deps2, RunRequest{DatasetIDs: []string{"kb1"}}) + if _, err := ex2.Execute(context.Background(), "retrieve", map[string]any{"query": "q"}); err != nil { + t.Fatalf("retrieve: %v", err) + } + if deps2.Expand.(*stubExpander).calls != 0 { + t.Errorf("retrieve compiled expansion calls = %d, want 0", deps2.Expand.(*stubExpander).calls) + } + + // An explicit req.UseCompiled=false must NOT disable it for search_chunks. + deps3, _ := newTestSearchDeps(&stubRetriever{chunks: []map[string]any{{"content": "hit", "chunk_id": "c1"}}}) + deps3.Expand = &stubExpander{} + exOff := NewSearchExecutor(deps3, RunRequest{DatasetIDs: []string{"kb1"}, UseCompiled: false}) + if _, err := exOff.Execute(context.Background(), "search_chunks", map[string]any{"query": "q"}); err != nil { + t.Fatalf("search_chunks (UseCompiled=false): %v", err) + } + if deps3.Expand.(*stubExpander).calls != 1 { + t.Errorf("search_chunks with req.UseCompiled=false must still expand, calls = %d, want 1", deps3.Expand.(*stubExpander).calls) + } +} + +func TestRenderToolArgs(t *testing.T) { + if got := renderToolArgs(nil); got != "{}" { + t.Errorf("renderToolArgs(nil) = %q, want {}", got) + } + if got := renderToolArgs(map[string]any{}); got != "{}" { + t.Errorf("renderToolArgs(map{}) = %q, want {}", got) + } + got := renderToolArgs(map[string]any{"q": "hi", "n": 3}) + if !strings.Contains(got, `"q":"hi"`) || !strings.Contains(got, `"n":3`) { + t.Errorf("renderToolArgs = %q, want both keys", got) + } + // Unmarshalable values must degrade to "{}", not blow up the log line. + if got := renderToolArgs(map[string]any{"f": func() {}}); got != "{}" { + t.Errorf("renderToolArgs(func value) = %q, want {}", got) + } +} + +// TestSearchNilKBIsSeeded pins the Python _seed_evidence semantics +// (action_session.py:_admit_evidence): a nil deps.KB is not a caller mistake — the +// executor creates the (empty) pool on first use, so the search RUNS and its +// outcome is decided by what it admitted (OK here), never a forced MISS. The +// executor must also not panic on the nil pool. +func TestSearchNilKBIsSeeded(t *testing.T) { + deps, _ := newTestSearchDeps(&stubRetriever{chunks: []map[string]any{{"content": "hit", "chunk_id": "c1"}}}) + deps.KB = nil + ex := NewSearchExecutor(deps, RunRequest{DatasetIDs: []string{"kb1"}}) + oc, err := ex.Execute(context.Background(), "retrieve", map[string]any{"query": "q"}) + if err != nil { + t.Fatalf("nil KB must not error: %v", err) + } + if oc.Status != StatusOK { + t.Errorf("nil KB retrieve status = %s, want %s", oc.Status, StatusOK) + } + if len(oc.Payload) != 1 { + t.Errorf("nil KB retrieve payload = %v, want 1 passage", oc.Payload) + } +} + +// TestListChunksNilKBIsMiss pins the Python semantics: a nil deps.KB is seeded +// by _seed_evidence, and with no doc-store reader wired the read yields nothing +// — _search_outcome([]) is MISS/no_doc (there is no "graceful OK empty" branch in +// Python). It must never error or panic. +func TestListChunksNilKBIsMiss(t *testing.T) { + deps, _ := newTestSearchDeps(&stubRetriever{}) + deps.KB = nil + ex := &searchExecutor{deps: deps, req: RunRequest{DatasetIDs: []string{"kb1"}}} + oc, err := ex.listChunks(context.Background(), map[string]any{"doc_id": "doc-a"}) + if err != nil { + t.Fatalf("nil KB list_chunks must not error: %v", err) + } + if oc.Status != StatusMiss || oc.Reason != ReasonNoDoc { + t.Errorf("nil KB list_chunks = (%s,%s), want (miss,no_doc)", oc.Status, oc.Reason) + } + if len(oc.Payload) != 0 { + t.Errorf("nil KB list_chunks payload = %v, want empty", oc.Payload) + } +} + +// TestListChunksDeepReadsDocStore pins the Python-parity deep read: list_chunks +// reads the document off the chunk store (deps.DocChunks, the same reader +// fetch_full_document uses) even when NONE of its chunks are in the evidence +// pool yet, and admits them into the shared pool the model can cite. +func TestListChunksDeepReadsDocStore(t *testing.T) { + deps, kb := newTestSearchDeps(&stubRetriever{}) + deps.DocChunks = docChunksFor("doc-a", 2) // only doc-a is readable + ex := &searchExecutor{deps: deps, req: RunRequest{DatasetIDs: []string{"kb1"}, MaxLength: 8192}} + + oc, err := ex.listChunks(context.Background(), map[string]any{"doc_id": "doc-a"}) + if err != nil { + t.Fatalf("list_chunks: %v", err) + } + if oc.Status != StatusOK { + t.Errorf("status = %s, want %s", oc.Status, StatusOK) + } + if len(oc.Payload) != 2 { + t.Fatalf("payload = %d, want 2 (only doc-a's chunks)", len(oc.Payload)) + } + // Deep-read admitted into the shared evidence pool. + if len(kb.Chunks) != 2 { + t.Errorf("kb.Chunks = %d, want 2 admitted", len(kb.Chunks)) + } + if len(oc.EvidenceIDs) != 2 { + t.Errorf("evidenceIDs = %d, want 2", len(oc.EvidenceIDs)) + } + // Passage shape mirrors _admit_evidence(include_doc_id=False): id + content. + for _, p := range oc.Payload { + m, ok := p.(map[string]any) + if !ok || m["id"] == nil || m["content"] == nil { + t.Fatalf("passage missing id/content: %#v", p) + } + if _, hasDoc := m["doc_id"]; hasDoc { + t.Errorf("list_chunks passage must not carry doc_id: %#v", m) + } + } +} + +// TestListChunksCapsDeepReadAndOutput pins the Python parity: the deep read may +// fetch up to listChunksMaxDeep (80) chunks, but _exec_list_chunks admits only +// the first listChunksMaxOut (30) into the shared pool and shows the model the +// same 30 — so the pool holds 30, not 80. +func TestListChunksCapsDeepReadAndOutput(t *testing.T) { + deps, kb := newTestSearchDeps(&stubRetriever{}) + deps.DocChunks = docChunksFor("doc-a", 100) + ex := &searchExecutor{deps: deps, req: RunRequest{DatasetIDs: []string{"kb1"}, MaxLength: 1 << 20}} + + oc, err := ex.listChunks(context.Background(), map[string]any{"doc_id": "doc-a"}) + if err != nil { + t.Fatalf("list_chunks: %v", err) + } + if len(kb.Chunks) != listChunksMaxOut { + t.Errorf("kb.Chunks = %d, want admitted cap %d (Python _exec_list_chunks [:30])", len(kb.Chunks), listChunksMaxOut) + } + if len(oc.Payload) != listChunksMaxOut { + t.Errorf("payload = %d, want output cap %d", len(oc.Payload), listChunksMaxOut) + } +} + +// TestWebSearchAdmitsToPool pins the web_search parity fix: web results merge +// into the SAME shared evidence pool as corpus hits (Python _exec_web_search → +// _admit_evidence), so downstream formalize/compose can cite them, and the +// outcome is REDUNDANT/OK/MISS like the corpus tools. +func TestWebSearchAdmitsToPool(t *testing.T) { + deps, kb := newTestSearchDeps(&stubRetriever{}) + deps.WebSearch = stubWebSearch{results: []string{"web answer one", "web answer two", "web answer three"}} + oc, err := WebSearchTool(context.Background(), deps, map[string]any{"": []any{"q1", "q2"}}) + if err != nil { + t.Fatalf("web_search: %v", err) + } + if oc.Status != StatusOK { + t.Errorf("status = %s, want %s", oc.Status, StatusOK) + } + if len(oc.Payload) != 3 { + t.Errorf("payload = %d, want 3", len(oc.Payload)) + } + if len(kb.Chunks) != 3 { + t.Errorf("kb.Chunks = %d, want 3 admitted to pool", len(kb.Chunks)) + } + if len(oc.EvidenceIDs) != 3 { + t.Errorf("evidenceIDs = %d, want 3", len(oc.EvidenceIDs)) + } + for _, p := range oc.Payload { + m, ok := p.(map[string]any) + if !ok || m["id"] == nil || m["content"] == nil { + t.Fatalf("passage missing id/content: %#v", p) + } + } +} + +// TestWebSearchDedupsAcrossQueries pins the Python parity: a passage that both +// queries return is admitted/shown only once (Python dedups by chunk_id across +// the two queries via a shared `seen` set). +func TestWebSearchDedupsAcrossQueries(t *testing.T) { + deps, kb := newTestSearchDeps(&stubRetriever{}) + deps.WebSearch = stubWebSearch{results: []string{"dup passage", "unique one", "dup passage"}} + oc, err := WebSearchTool(context.Background(), deps, map[string]any{"": []any{"q1", "q2"}}) + if err != nil { + t.Fatalf("web_search: %v", err) + } + if len(oc.Payload) != 2 { + t.Errorf("payload = %d, want 2 (duplicate collapsed)", len(oc.Payload)) + } + if len(kb.Chunks) != 2 { + t.Errorf("kb.Chunks = %d, want 2 admitted (duplicate not double-merged)", len(kb.Chunks)) + } +} + +// TestListChunksSkipsEmptyChunkID pins Python parity (L3): a deep-read chunk +// with no chunk_id is skipped — neither admitted to the pool nor shown to the +// model (Python _exec_list_chunks: `if not cid: continue`). +func TestListChunksSkipsEmptyChunkID(t *testing.T) { + deps, kb := newTestSearchDeps(&stubRetriever{}) + deps.DocChunks = docChunksWithIDs("doc-a", []string{"", "c1"}) // first has empty chunk_id + ex := &searchExecutor{deps: deps, req: RunRequest{DatasetIDs: []string{"kb1"}, MaxLength: 8192}} + + oc, err := ex.listChunks(context.Background(), map[string]any{"doc_id": "doc-a"}) + if err != nil { + t.Fatalf("list_chunks: %v", err) + } + if len(kb.Chunks) != 1 { + t.Errorf("kb.Chunks = %d, want 1 (empty-id chunk skipped)", len(kb.Chunks)) + } + if len(oc.Payload) != 1 { + t.Fatalf("payload = %d, want 1", len(oc.Payload)) + } + if m, ok := oc.Payload[0].(map[string]any); !ok || m["id"] == "" { + t.Errorf("payload passage must not have empty id: %#v", oc.Payload[0]) + } +} + +// docChunksFor returns a DocChunkLister that serves n chunks for the given doc id +// (filtering by doc id, like the production chunk-store reader). +func docChunksFor(docID string, n int) DocChunkLister { + return docChunksStub{docID: docID, n: n} +} + +type docChunksStub struct { + docID string + n int +} + +func (s docChunksStub) DocChunks(_ context.Context, req DocChunksRequest) ([]map[string]any, error) { + if req.DocID != s.docID { + return nil, nil + } + out := make([]map[string]any, 0, s.n) + for i := 0; i < s.n; i++ { + out = append(out, map[string]any{ + "chunk_id": fmt.Sprintf("c%d", i), + "doc_id": s.docID, + "content": "x", + }) + } + return out, nil +} + +// docChunksWithIDs serves one chunk per id (empty strings stay empty), used to +// exercise the empty-chunk_id skip. +func docChunksWithIDs(docID string, ids []string) DocChunkLister { + return docChunksIDsStub{docID: docID, ids: ids} +} + +type docChunksIDsStub struct { + docID string + ids []string +} + +func (s docChunksIDsStub) DocChunks(_ context.Context, req DocChunksRequest) ([]map[string]any, error) { + if req.DocID != s.docID { + return nil, nil + } + out := make([]map[string]any, 0, len(s.ids)) + for _, id := range s.ids { + out = append(out, map[string]any{ + "chunk_id": id, + "doc_id": s.docID, + "content": "x", + }) + } + return out, nil +} + +type stubWebSearch struct{ results []string } + +func (s stubWebSearch) Search(_ context.Context, _ []string) ([]string, error) { + return s.results, nil +} + +// TestSearchRedundantReturnsFullPayload pins fix #5: when every hit is already +// in the evidence pool the result is StatusRedundant — but Python _search_outcome +// still returns the FULL passages so the model sees what it already has. The Go +// port must not drop the payload to empty (which hid the evidence). +func TestSearchRedundantReturnsFullPayload(t *testing.T) { + chunk := map[string]any{"content": "already known passage", "chunk_id": "c1"} + deps, _ := newTestSearchDeps(&stubRetriever{chunks: []map[string]any{chunk}}) + // Pre-seed the pool with the same chunk so the merge adds nothing new. + deps.KB.Chunks = append(deps.KB.Chunks, chunk) + ex := NewSearchExecutor(deps, RunRequest{DatasetIDs: []string{"kb1"}}) + oc, err := ex.Execute(context.Background(), "retrieve", map[string]any{"query": "q"}) + if err != nil { + t.Fatalf("retrieve: %v", err) + } + if oc.Status != StatusRedundant { + t.Fatalf("status = %s, want %s", oc.Status, StatusRedundant) + } + if len(oc.Payload) != 1 { + t.Fatalf("REDUNDANT payload = %v, want 1 full passage", oc.Payload) + } + p, ok := oc.Payload[0].(map[string]any) + if !ok || p["content"] != "already known passage" { + t.Errorf("REDUNDANT payload[0] = %#v, want the known passage", oc.Payload[0]) + } +} + +func TestNavigateToolsRouteWithinSessionDocScope(t *testing.T) { + for _, tool := range []struct { + name string + args map[string]any + }{ + {"navigate_tree", map[string]any{"query": "topic"}}, + {"navigate_structure", map[string]any{"query": "topic", "kind": "catalog"}}, + } { + router := &stubNavRouter{docs: [][2]string{{"d1", "summary"}}} + ex := &searchExecutor{deps: SearchDeps{ + NavRouter: router, + DocScope: []string{"sess1"}, + KbIDs: []string{"kb1"}, + TenantID: "t1", + }} + if _, err := ex.Execute(context.Background(), tool.name, tool.args); err != nil { + t.Fatalf("%s: %v", tool.name, err) + } + if len(router.scope) != 1 || router.scope[0] != "sess1" { + t.Errorf("%s: router doc scope = %v, want [sess1] (session ceiling)", tool.name, router.scope) + } + } +} + +// TestDocInDatasetsRejectsForeignDocumentViaSubsetVerifier reproduces the +// production DocIDLookup.KnownDocIDs shape: a foreign doc is reported via an +// EMPTY known map (not a false entry). docInDatasets must still reject it +// (mirrors Python _resolve_doc_tenant returning None), not fail open. + +// End-to-end wiring tests: one Run call, with a stubbed retriever and a +// scripted model, must move evidence from the backend into Kbinfos and (when a +// canvas state is attached) into the citation store. + +// corpusRetriever answers every query from a fixed corpus. +type corpusRetriever struct{ calls []string } + +func (c *corpusRetriever) Retrieve(_ context.Context, req RetrieveRequest) ([]map[string]any, error) { + c.calls = append(c.calls, req.Query) + return []map[string]any{{ + "chunk_id": "c1", + "content": "Culdcept was created by OmiyaSoft and released in 1999.", + "doc_id": "doc-culdcept", + "doc_name": "Culdcept History", + "dataset_id": "kb1", + }}, nil +} + +func TestSearchExecutorReportsMissAndRedundancy(t *testing.T) { + kb := &Kbinfos{} + sd := SearchDeps{Backend: &corpusRetriever{}, KbIDs: []string{"kb1"}, KB: kb} + ex := &searchExecutor{deps: sd, req: RunRequest{}} + + // First call: OK with new evidence. + oc, err := ex.Execute(context.Background(), "retrieve", map[string]any{"query": "q1"}) + if err != nil { + t.Fatalf("Execute: %v", err) + } + if oc.Status != StatusOK { + t.Fatalf("first call status = %s, want ok", oc.Status) + } + if len(oc.EvidenceIDs) != 1 { + t.Errorf("evidence ids = %v, want 1", oc.EvidenceIDs) + } + + // Same query again: every hit is already in the pool -> REDUNDANT, not ok. + oc, _ = ex.Execute(context.Background(), "retrieve", map[string]any{"query": "q1"}) + if oc.Status != StatusRedundant { + t.Errorf("repeat call status = %s, want redundant", oc.Status) + } + + // Missing query -> MISS/no_doc, NOT a bad-args error: Python + // _arg_query_list yields [] and _search_outcome([]) is a miss + // (action_session.py:_search_outcome). + oc, _ = ex.Execute(context.Background(), "retrieve", map[string]any{}) + if oc.Status != StatusMiss || oc.Reason != ReasonNoDoc { + t.Errorf("missing query: got (%s,%s), want (miss,no_doc)", oc.Status, oc.Reason) + } + + // A genuinely unwired tool -> miss (valid tool, nothing reached), never an + // error, so the model falls back instead of stalling. + oc, _ = ex.Execute(context.Background(), "wiki_query", map[string]any{"query": "topic"}) + if oc.Status != StatusMiss { + t.Errorf("unwired tool status = %s, want miss", oc.Status) + } +} + +// TestSearchRecordsDocAggsForReferences: the search tools are the only writer of +// kbinfos["doc_aggs"], which the chat pipeline turns into the answer's +// document/reference list. +func TestSearchRecordsDocAggsForReferences(t *testing.T) { + kb := &Kbinfos{} + ex := &searchExecutor{deps: SearchDeps{Backend: &corpusRetriever{}, KbIDs: []string{"kb1"}, KB: kb}, req: RunRequest{}} + + if _, err := ex.Execute(context.Background(), "retrieve", map[string]any{"query": "Culdcept"}); err != nil { + t.Fatalf("Execute: %v", err) + } + if len(kb.DocAggs) != 1 { + t.Fatalf("kb.DocAggs = %v, want the searched document recorded", kb.DocAggs) + } + if got := kb.DocAggs[0]["doc_id"]; got != "doc-culdcept" { + t.Errorf("doc_agg doc_id = %v, want doc-culdcept", got) + } + + // A REDUNDANT repeat (nothing new admitted) must not duplicate the agg. + if _, err := ex.Execute(context.Background(), "retrieve", map[string]any{"query": "Culdcept"}); err != nil { + t.Fatalf("repeat: %v", err) + } + if len(kb.DocAggs) != 1 { + t.Errorf("kb.DocAggs = %v, want 1 (deduped by doc_id)", kb.DocAggs) + } +} + +// fakeWikiRetriever returns a fixed compiled wiki page. +type fakeWikiRetriever struct{} + +func (f *fakeWikiRetriever) SearchWiki(_ context.Context, question string, keywords []string, topN int) ([]WikiPage, error) { + return []WikiPage{{ + ChunkID: "w1", DocID: "wdoc1", DocName: "Synthesis", Title: "Culdcept Overview", + Content: "Culdcept is a board game by OmiyaSoft.", Score: 0.9, + }}, nil +} + +func TestWikiQueryWiredReturnsPages(t *testing.T) { + // When a WikiRetriever is wired, wiki_query returns the parsed page payload + // in the same shape Python's action layer consumes. + ex := &searchExecutor{deps: SearchDeps{WikiRetriever: &fakeWikiRetriever{}}, req: RunRequest{}} + + oc, err := ex.Execute(context.Background(), "wiki_query", map[string]any{"query": "Culdcept overview"}) + if err != nil { + t.Fatalf("Execute: %v", err) + } + if oc.Status != StatusOK { + t.Fatalf("status = %s, want ok", oc.Status) + } + if n, _ := toInt(oc.Metrics["n_hits"]); n != 1 { + t.Errorf("n_hits = %v, want 1", oc.Metrics["n_hits"]) + } + hit, ok := oc.Payload[0].(map[string]any) + if !ok { + t.Fatalf("payload[0] not a map: %T", oc.Payload[0]) + } + for _, key := range []string{"chunk_id", "doc_id", "docnm_kwd", "title", "content", "query"} { + if _, present := hit[key]; !present { + t.Errorf("payload missing key %q", key) + } + } + if hit["content"] != "Culdcept is a board game by OmiyaSoft." { + t.Errorf("content = %v", hit["content"]) + } +} + +func TestWikiQuerySchemaIsUnplugged(t *testing.T) { + // wiki_query is ported as an UNPLUGGED extension seam: the handler exists + // (TestWikiQueryWiredReturnsPages), but it is NOT part of any mode's active + // tool set (removed from allTools) and no SearchWiki backend is wired in + // production, so it must never appear in the advertised surface — mirroring + // Python, which keeps tools/exploration.py::wiki_query but never registers it + // in the action session. + for _, mode := range []string{"medium", "high", "ultra"} { + ts := &Toolset{ThinkingMode: mode} + if spec, ok := findSpec(ts.ActiveToolSpecs(), "wiki_query"); ok { + t.Errorf("wiki_query surfaced in mode %q: %+v", mode, spec) + } + } +} + +// findSpec is a test helper mirroring ActiveToolSpecs lookup. +func findSpec(specs []ToolSpec, name string) (ToolSpec, bool) { + for _, s := range specs { + if s.Function.Name == name { + return s, true + } + } + return ToolSpec{}, false +} + +func TestListChunksReadsFromEvidencePool(t *testing.T) { + // list_chunks deep-reads a document. With no doc-store reader wired it scans + // the accumulated evidence pool; an unknown/missing doc_id is a query-level + // MISS (mirroring Python list_chunks("") → _search_outcome), never a dataset + // EMPTY and never a hard error. + kb := &Kbinfos{Chunks: []map[string]any{ + {"chunk_id": "c1", "doc_id": "doc-a", "content": "first"}, + {"chunk_id": "c2", "doc_id": "doc-b", "content": "other"}, + {"chunk_id": "c3", "doc_id": "doc-a", "content": "second"}, + }} + ex := &searchExecutor{deps: SearchDeps{KB: kb}} + + oc, _ := ex.Execute(context.Background(), "list_chunks", map[string]any{"doc_id": "doc-a"}) + // Already in evidence → REDUNDANT (nothing new admitted), but the passages + // are still returned (mirrors Python _search_outcome). + if oc.Status != StatusRedundant { + t.Fatalf("status = %s, want redundant", oc.Status) + } + if len(oc.Payload) != 2 { + t.Errorf("payload = %d, want 2 chunks of doc-a", len(oc.Payload)) + } + // Evidence ids are the CHUNK ids — Python _admit_evidence does + // `ids.append(cid)`, not a pool position. + if len(oc.EvidenceIDs) != 2 || oc.EvidenceIDs[0] != "c1" || oc.EvidenceIDs[1] != "c3" { + t.Errorf("evidence ids = %v, want [c1 c3]", oc.EvidenceIDs) + } + + oc, _ = ex.Execute(context.Background(), "list_chunks", map[string]any{"doc_id": "doc-zz"}) + if oc.Status != StatusMiss { + t.Errorf("unknown doc status = %s, want miss", oc.Status) + } + // Missing doc_id → MISS (Python list_chunks("") → empty → _search_outcome). + oc, _ = ex.Execute(context.Background(), "list_chunks", map[string]any{}) + if oc.Status != StatusMiss { + t.Errorf("no doc_id: got %s, want miss", oc.Status) + } +} + +func TestToolQueriesAcceptsBothShapes(t *testing.T) { + // Models emit `query` as a string OR a list, per the advertised schema. + if got := toolQueries(map[string]any{"query": "single"}); len(got) != 1 || got[0] != "single" { + t.Errorf("string form = %v", got) + } + if got := toolQueries(map[string]any{"query": []any{"a", "", "b"}}); len(got) != 2 { + t.Errorf("list form = %v, want blanks dropped", got) + } + if got := toolQueries(map[string]any{"query": []string{"a", "b"}}); len(got) != 2 { + t.Errorf("[]string form = %v", got) + } + if got := toolQueries(map[string]any{}); got != nil { + t.Errorf("absent query = %v, want nil", got) + } + // The `q` alias some models emit. + if got := toolQueries(map[string]any{"q": "alias"}); len(got) != 1 || got[0] != "alias" { + t.Errorf("q alias = %v", got) + } +} + +func TestPublishReferencesSkipsWithoutCanvasState(t *testing.T) { + // No canvas state attached: publishing is a silent no-op (best-effort), + // which is what happens in unit tests and non-canvas callers. + kb := &Kbinfos{Chunks: []map[string]any{{"content": "x", "doc_id": "d1"}}} + PublishReferences(context.Background(), kb) // must not panic +} + +func TestPassageFromChunkTruncatesContent(t *testing.T) { + long := strings.Repeat("word ", 500) + p := passageFromChunk(map[string]any{ + "chunk_id": "c1", "doc_id": "d1", "docnm_kwd": "Title", "content": long, + }) + content, _ := p["content"].(string) + // Non-table chunk is cut to 1200 code points (Python _admit_evidence's + // `_ct[:1200]`), a plain slice — so NO trailing ellipsis is added. + if n := len([]rune(content)); n != 1200 { + t.Errorf("content length = %d runes, want 1200", n) + } + if strings.HasSuffix(content, "...") { + t.Errorf("Python _ct[:1200] adds no ellipsis marker: %q", content) + } + // Keys mirror Python _admit_evidence exactly: {"id","content","doc_id"} — the + // id must live under "id", which is what the drill merge reads back. + if p["doc_id"] != "d1" || p["id"] != "c1" { + t.Errorf("passage = %v", p) + } +} diff --git a/internal/rag/advanced_rag/harness/tool_exploration.go b/internal/rag/advanced_rag/harness/tool_exploration.go new file mode 100644 index 00000000000..00502a58bf4 --- /dev/null +++ b/internal/rag/advanced_rag/harness/tool_exploration.go @@ -0,0 +1,962 @@ +// +// 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. +// + +package harness + +import ( + "context" + "encoding/json" + "fmt" + "sort" + "strings" + + "ragflow/internal/dao" + "ragflow/internal/engine" + "ragflow/internal/engine/types" + "ragflow/internal/service" + "ragflow/internal/service/nlp" +) + +// Exploration providers (Go equivalent of Python harness/tools/exploration.py): +// knowledge-graph walks (graph_explore) and wiki page drill-downs (wiki_query), +// plus the open-web search provider seam. +// +// graph_explore walks the compiled knowledge graph (see ExploreGraph): it seeds +// entities by dense similarity, hops out over relations, then asks the model +// whether the subgraph answers the question. wiki_query searches the compiled +// wiki_page_draft rows. Together these mirror the exploration.py module, which +// hosts both graph_explore and wiki_query. +// +// Search seams stay independent of the search backend so the harness core is +// testable without one; the bridge wires concrete implementations (wiki_page_draft +// rows for SearchWiki, an HTTP client for WebSearcher). + +// WebSearcher runs an open-web search and returns result strings. It is the Go +// equivalent of Python's web_search provider path wired into the action session. +type WebSearcher interface { + Search(ctx context.Context, queries []string) ([]string, error) +} + +// WikiPage is one compiled wiki page returned by WikiRetriever, mirroring the +// payload Python wiki_query emits per hit: the parsed page markdown plus the +// originating row identity so the harness can cite/load it. +type WikiPage struct { + ChunkID string + DocID string + DocName string + Title string + // Content is the synthesised page markdown (Python's page_content). + Content string + // Score is the retrieval relevance (higher = better). + Score float64 +} + +// WikiRetriever searches the compiled wiki_page_draft rows for a question and +// returns the most relevant pages. It is the Go equivalent of Python's +// tools/exploration.py::wiki_query, kept as a seam so the harness core stays +// independent of the search backend and remains testable without one. +type WikiRetriever interface { + // SearchWiki returns up to topN compiled wiki pages for the question, + // biased toward the optional keywords. + SearchWiki(ctx context.Context, question string, keywords []string, topN int) ([]WikiPage, error) +} + +// wikiQuery implements the `wiki_query` tool, mirroring Python +// tools/exploration.py::wiki_query + action_session._exec_wiki_query. +// +// It searches the compiled "wiki_page_draft" rows for the question, parses each +// hit's synthesised page markdown out of the row, and returns them in the same +// payload shape Python's action layer consumes: per hit +// +// {chunk_id, doc_id, docnm_kwd, title, content, query} +// +// plus n_hits in Metrics. When no wiki retriever is wired (or the dataset has no +// wiki compilation), it returns a clean MISS so the model falls back to corpus +// tools — mirroring Python's wiki gate. +func (e *searchExecutor) wikiQuery(ctx context.Context, args map[string]any) (ToolOutcome, error) { + if e.deps.WikiRetriever == nil { + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "wiki_query", + "note": "wiki_query is not available for this dataset (no compiled wiki). Use corpus tools (retrieve/search_chunks) for in-document facts.", + }}, + Status: StatusMiss, + Reason: ReasonNoDoc, + Metrics: map[string]any{}, + }, nil + } + + // The wiki_query schema presents a 1-2 element array: [question, keywords?]. + queries := toolQueries(args) + question := strings.TrimSpace(argString(args, "query")) + keywords := toolStringList(args, "keywords") + if question == "" && len(queries) > 0 { + question = queries[0] + if len(queries) > 1 { + keywords = append(keywords, splitComma(queries[1])...) + } + } + if question == "" { + return ToolOutcome{Payload: []any{}, Status: StatusError, Reason: ReasonBadArgs}, nil + } + + topN, _ := toInt(args["top_n"]) + if topN <= 0 { + topN = 12 // Python _WIKI_QUERY_TOP_N = 12 + } + if topN > 30 { + topN = 30 + } + + pages, err := e.deps.WikiRetriever.SearchWiki(ctx, question, keywords, topN) + if err != nil || len(pages) == 0 { + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "wiki_query", + "note": "No compiled wiki page matched the question.", + }}, + Status: StatusMiss, + Reason: ReasonNoDoc, + Metrics: map[string]any{}, + }, nil + } + + passages := make([]any, 0, len(pages)) + for _, p := range pages { + passages = append(passages, map[string]any{ + "chunk_id": p.ChunkID, + "doc_id": p.DocID, + "docnm_kwd": p.DocName, + "title": p.Title, + "content": p.Content, + "query": question, + }) + } + return ToolOutcome{ + Payload: passages, + Status: StatusOK, + Reason: ReasonNone, + Metrics: map[string]any{"n_hits": len(passages)}, + }, nil +} + +// splitComma splits a comma-separated keyword string into a clean slice, +// tolerating spaces. Mirrors Python's kw.strip() loop after split(","). +func splitComma(s string) []string { + if s == "" { + return nil + } + parts := strings.Split(s, ",") + out := make([]string, 0, len(parts)) + for _, p := range parts { + if t := strings.TrimSpace(p); t != "" { + out = append(out, t) + } + } + return out +} + +// graphExplore caps, mirroring Python _exec_graph_explore +// (action_session.py:execute_tool): chunks[:6] and str(content)[:1500]. +const ( + graphExploreMaxChunks = 6 + graphExplorePassageChars = 1500 +) + +// graphExplore explores the compiled knowledge graph for a relational / multi-hop +// answer (ultra only), delegating to ExploreGraph: seed entities for the query, hop +// along their relations, and return either a direct answer or the source passages +// behind the relevant entities. Mirrors Python exploration.py::graph_explore (paired +// with wikiQuery). +// +// The outcome shape mirrors _exec_graph_explore: a +// single-element payload tagged kind="graph_explore" whose body is exactly one of +// answer / note / chunks, at most 6 passages of 1500 chars, and NO pool merge (Python +// never calls _admit_evidence on this path). +// +// Deliberate deviation: Python reads c["id"] / c["content"] while the producer +// _load_chunks_by_ids emits chunk_id / content_with_weight, +// so Python's snippet is always {"id": None, "content": ""} with zero evidence ids — a +// key-mismatch bug. Go reads the keys the loader produces. +func (e *searchExecutor) graphExplore(ctx context.Context, args map[string]any) (ToolOutcome, error) { + query := argString(args, "query") + if query == "" { + query = e.req.Question + } + if query == "" { + return ToolOutcome{Payload: []any{}, Status: StatusError, Reason: ReasonBadArgs}, nil + } + // No keywords: Python calls graph_explore(tools, query, doc_scope=...) with + // keywords defaulting to "" (action_session.py:_exec_graph_explore), so the graph's own + // narrowing is a no-op there. e.req.Keywords must not be injected. + docScope := toolDocScope(args) + if docScope != nil && len(docScope) == 0 { + // An explicitly empty list is Python-falsy: graph_explore reads it as "no + // scope" and scans the bound datasets. (The non-nil empty "match nothing" + // signal only comes from resolveDocScope, downstream of here.) + docScope = nil + } + res, err := ExploreGraph(ctx, e.deps, e.deps.TenantID, e.deps.KbIDs, query, "", docScope) + if err != nil { + // Python :978-982 swallows the exception, sets res = {}, and falls into + // the empty branch below — an infra failure here is reported as a + // dataset-level EMPTY/no_structure, never an ERROR. + _LOG.Printf("[graph_explore] failed: %v", err) + res = ExploreResult{} + } + answer := strings.TrimSpace(res.Answer) + if answer != "" { + // Python :985-986 — a direct answer short-circuits: no passages. + return ToolOutcome{ + Payload: []any{map[string]any{"kind": "graph_explore", "answer": answer}}, + Status: StatusOK, + Reason: ReasonNone, + Metrics: map[string]any{"hits": 0}, + }, nil + } + if len(res.Chunks) == 0 { + // Python :987-997 — no compiled KG in scope is a DATASET-level dead end + // (EMPTY/no_structure), the one class of failure that may disable the tool. + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "graph_explore", + "note": "This dataset has NO compiled knowledge graph (or none in the given scope). graph_explore is unavailable; use search_chunks / navigate_structure / retrieve instead.", + }}, + Status: StatusEmpty, + Reason: ReasonNoStructure, + Metrics: map[string]any{}, + }, nil + } + chunks := res.Chunks + if len(chunks) > graphExploreMaxChunks { + chunks = chunks[:graphExploreMaxChunks] + } + snippet := make([]any, 0, len(chunks)) + for _, c := range chunks { + snippet = append(snippet, map[string]any{ + "id": ChunkIDOf(c), + "content": truncateRunes(ChunkTextOf(c), graphExplorePassageChars), + }) + } + // No EvidenceIDs and no pool merge: Python returns ids=[] here (its c["id"] + // lookup misses every loaded chunk) and never admits the passages to kbinfos. + return ToolOutcome{ + Payload: []any{map[string]any{"kind": "graph_explore", "chunks": snippet}}, + Status: StatusOK, + Reason: ReasonNone, + Metrics: map[string]any{"hits": 0}, + }, nil +} + +// --------------------------------------------------------------------------- +// graph_explore (knowledge-graph walk) — mirrors exploration.py::graph_explore +// --------------------------------------------------------------------------- + +// ExploreGraph walks the compiled knowledge graph: seed entities for the query +// by dense similarity, hop kgHops out over their relations, then ask the model +// whether the resulting subgraph answers the question directly. When it does the +// answer is returned; when it doesn't, the source passages behind the relevant +// nodes are returned so the caller can keep researching. Mirrors Python +// exploration.py::graph_explore (which lives beside wiki_query in exploration.py). +// +// Seeds use the tenant embedding model via service.NavEmbedder (dense KNN, +// similarity >= kgSeedSim, re-ranked by mention_count_int desc); when the +// embedding model is unavailable it degrades to keyword match (mirrors Python +// _kg_search's `embed_mdl is None` path). +const ( + kgScopeDataset = "dataset" + kgScopeDoc = "doc" + + kgSeeds = 2 // top-N entities matched directly to the question + kgSeedPool = 64 // KNN candidate pool before the mention_count_int re-sort + kgSeedSim = 0.8 // dense seed similarity floor (Python _KG_SEED_SIM) + kgHops = 2 // relation hops out from the seeds + kgNeighbors = 128 // cap on neighbour entity rows resolved per hop + kgRelLimit = 32 // relations fetched per endpoint filter +) + +// kgScope is one (kb, tenant, docs) search group, mirroring one entry of +// Python _kg_scopes' return list. When Docs is non-empty the group searches +// within those documents (kgScopeDoc); when nil it searches the whole dataset +// (kgScopeDataset). +type kgScope struct { + KBID string + TenantID string + Docs []string +} + +// resolveKGScope builds the (kb, tenant, docs) search groups, mirroring +// Python _kg_scopes. The session doc_scope ceilings the +// caller's scope first (Python scoped_doc_ids; exploration.py:_kg_scopes). With no scope +// it returns one group per bound dataset (docs=nil => whole-dataset search). +// With a scope and a DocTenantResolver it groups documents by their real owning +// (kb, tenant), which may surface knowledge bases outside datasetIDs; documents +// whose owner cannot be resolved fall back to the caller's datasets. Without a +// resolver it keeps the pre-existing behaviour: each bound dataset is searched +// with the whole scope. +func resolveKGScope(deps SearchDeps, docScope, datasetIDs []string) []kgScope { + // A non-nil empty scope is resolveDocScope's "match nothing" signal (the + // session ceiling removed every requested id). Python's falsy-empty check + // would fall through to whole-dataset scopes; Go keeps the ceiling absolute + // and expands nothing. + if docScope != nil && len(docScope) == 0 { + return nil + } + docScope = scopedDocIDs(deps.DocScope, docScope) + + // Each bound dataset is scanned under its OWN owner tenant (Python + // `[(kb.id, kb.tenant_id, None) for kb in tools.kbs]`); the request tenant is + // only a fallback for a dataset that carries no tenant id. + tenantByKB := make(map[string]string, len(deps.KBs)) + for _, kb := range deps.KBs { + if kb != nil && kb.ID != "" && kb.TenantID != "" { + tenantByKB[kb.ID] = kb.TenantID + } + } + boundTenant := func(kbID string) string { + if t := tenantByKB[kbID]; t != "" { + return t + } + return deps.TenantID + } + + if len(docScope) == 0 { + out := make([]kgScope, 0, len(datasetIDs)) + for _, kbID := range datasetIDs { + out = append(out, kgScope{KBID: kbID, TenantID: boundTenant(kbID), Docs: nil}) + } + return out + } + + byOwner := map[DocTenant][]string{} + if deps.DocTenantResolver != nil { + if owners, err := deps.DocTenantResolver.ResolveDocTenants(context.Background(), docScope); err == nil { + // Walk docScope (not the owners map): Go randomises map iteration, so + // grouping from the map made both the doc order inside a scope and the + // scope order itself vary run to run. + seen := map[string]bool{} + for _, docID := range docScope { + owner, ok := owners[docID] + if !ok || seen[docID] { + continue + } + seen[docID] = true + key := DocTenant{KBID: owner.KBID, TenantID: owner.TenantID} + byOwner[key] = append(byOwner[key], docID) + } + } + } + + if len(byOwner) == 0 { + // No resolver, or it failed: keep the old behaviour — every bound + // dataset searched with the whole DocScope. + out := make([]kgScope, 0, len(datasetIDs)) + for _, kbID := range datasetIDs { + out = append(out, kgScope{KBID: kbID, TenantID: boundTenant(kbID), Docs: docScope}) + } + return out + } + + // Group by real owner, including knowledge bases beyond datasetIDs. + out := make([]kgScope, 0, len(byOwner)) + for owner, docs := range byOwner { + out = append(out, kgScope{KBID: owner.KBID, TenantID: owner.TenantID, Docs: docs}) + } + // Stable scope order too — same reason as above. + sort.Slice(out, func(i, j int) bool { + if out[i].KBID != out[j].KBID { + return out[i].KBID < out[j].KBID + } + return out[i].TenantID < out[j].TenantID + }) + return out +} + +type kgEntity struct { + Name string `json:"name"` + Type string `json:"type"` + Description string `json:"description"` + Aliases []string `json:"aliases"` + SourceChunkIDs []string `json:"source_chunk_ids"` + DocID string `json:"doc_id"` +} + +type kgRelation struct { + ID string `json:"id"` + From string `json:"from"` + To string `json:"to"` + Type string `json:"type"` + SourceChunkIDs []string `json:"source_chunk_ids"` + DocID string `json:"doc_id"` +} + +// ExploreResult is the graph_explore output: exactly one of Answer / Chunks is +// populated, and DocAggs always reflects the returned set. Mirrors Python's +// {"answer", "chunks", "doc_aggs"} return dict. +type ExploreResult struct { + Answer string + Chunks []map[string]interface{} + DocAggs []map[string]interface{} +} + +// ExploreGraph implements graph_explore. +func ExploreGraph(ctx context.Context, deps SearchDeps, tenantID string, datasetIDs []string, query, keywords string, docScope []string) (ExploreResult, error) { + empty := ExploreResult{} + text := strings.TrimSpace(query + " " + keywords) + if text == "" || len(datasetIDs) == 0 { + return empty, nil + } + de := engine.Get() + if de == nil { + return empty, fmt.Errorf("graph_explore: engine not configured") + } + + // Build the (kb, tenant, docs) search groups, mirroring Python + // _kg_scopes: group documents by their real owner (which may include KBs + // outside datasetIDs), or fall back to whole-dataset search. + scopes := resolveKGScope(deps, docScope, datasetIDs) + + var entities []kgEntity + var relations []kgRelation + seenNames := map[string]bool{} + + addEntities := func(new []kgEntity, scopeKey string) []string { + var added []string + for _, e := range new { + key := scopeKey + ":" + strings.ToLower(e.Name) + if seenNames[key] { + continue + } + seenNames[key] = true + entities = append(entities, e) + added = append(added, e.Name) + } + return added + } + + // Encode the seed text ONCE (not per dataset): a single embedding request + // serves every KB. A nil vector means the embedding model is unavailable and + // the seed search falls back to keyword match. + seedVec := encodeSeedVector(ctx, deps, tenantID, text) + + for _, sc := range scopes { + // A scope with Docs searches within those documents; one without + // searches the whole dataset (mirrors Python _kg_scopes returning + // (kb, tenant, docs) where docs is None for the whole-dataset case). + scopeKwd := kgScopeDataset + if len(sc.Docs) > 0 { + scopeKwd = kgScopeDoc + } + // (1) Seeds: dense KNN (similarity>=_KG_SEED_SIM) over the scoped entity + // rows, re-ranked by mention_count_int desc; falls back to keyword match + // when the embedding model is unavailable. + seedRows := kgSeedSearch(ctx, de, sc.TenantID, sc.KBID, sc.Docs, text, scopeKwd, seedVec) + var seeds []kgEntity + for _, r := range seedRows { + if e, ok := kgParseEntity(r); ok { + seeds = append(seeds, e) + } + } + frontier := addEntities(seeds, sc.KBID) + + // (2) Expand kgHops out, collecting relations and neighbour entities. + for hop := 0; hop < kgHops; hop++ { + if len(frontier) == 0 { + break + } + terms := endpointTerms(frontier) + relRows := kgSearch(ctx, de, sc.TenantID, sc.KBID, sc.Docs, "relation", "", kgRelLimit, scopeKwd, + map[string]interface{}{"from_entity_kwd": terms}, "", 0) + relRows = append(relRows, kgSearch(ctx, de, sc.TenantID, sc.KBID, sc.Docs, "relation", "", kgRelLimit, scopeKwd, + map[string]interface{}{"to_entity_kwd": terms}, "", 0)...) + // Dedup keys: Python keeps a relation unless its source row id is + // already seen (rel_rows is a dict keyed by row id), so the same + // endpoint pair from *different* rows survives. Mirror that: prefer + // the row id; only fall back to the from|to|type triple when the + // engine returned no id (so we at least collapse exact duplicates). + seenRel := map[string]bool{} + var hopRelations []kgRelation + for _, r := range relRows { + rel, ok := kgParseRelation(r) + if !ok { + continue + } + k := rel.ID + if k == "" { + k = rel.From + "|" + rel.To + "|" + rel.Type + } + if seenRel[k] { + continue + } + seenRel[k] = true + hopRelations = append(hopRelations, rel) + } + relations = append(relations, hopRelations...) + + // Neighbour entity names not yet visited. + seenLower := map[string]bool{} + for k := range seenNames { + if strings.HasPrefix(k, sc.KBID+":") { + seenLower[strings.TrimPrefix(k, sc.KBID+":")] = true + } + } + neighSet := map[string]string{} + for _, r := range hopRelations { + for _, n := range []string{r.From, r.To} { + n = strings.TrimSpace(n) + if n == "" || seenLower[strings.ToLower(n)] { + continue + } + neighSet[strings.ToLower(n)] = n + } + } + if len(neighSet) == 0 { + break + } + neighFiltered := make([]string, 0, len(neighSet)) + for _, n := range neighSet { + neighFiltered = append(neighFiltered, n) + } + limit := kgNeighbors + if len(neighFiltered) < limit { + limit = len(neighFiltered) + } + neighRows := kgSearch(ctx, de, sc.TenantID, sc.KBID, sc.Docs, "entity", "", limit, scopeKwd, + map[string]interface{}{"name_kwd": endpointTerms(neighFiltered)}, "", 0) + var neighbours []kgEntity + for _, r := range neighRows { + if e, ok := kgParseEntity(r); ok { + neighbours = append(neighbours, e) + } + } + frontier = addEntities(neighbours, sc.KBID) + } + } + + if len(entities) == 0 && len(relations) == 0 { + return empty, nil + } + + // (3) Does the subgraph answer the question? The request-scoped model + // (deps.Model, Python's tools.chat_mdl) is threaded through so the verdict is + // drawn by the same tenant model as the rest of the harness. + answer, relevant := askStructureAnswer(ctx, deps.Model, query, entities, relations) + // (4a) Sufficient — return the answer, no chunks. + if answer != "" { + return ExploreResult{Answer: answer, DocAggs: []map[string]interface{}{}}, nil + } + + // (4b) Insufficient — return source passages behind the relevant nodes, + // narrowed to the sentences that carry the keywords (mirror Python + // exploration.py L359-361). Python's _narrow_by_keywords keeps the whole set + // when keywords is empty (text_processing.py `if not kwds: return chunks`), + // so we gate the strict narrow on a non-empty keyword string to avoid + // emptying the evidence. doc_aggs is computed from the resulting set (L363). + // Iterate the evidence groups in FIRST-SEEN order (Python walks its dict's + // .items()), so the executor's chunks[:6] picks the same passages each run. + evidence := collectEvidenceIDs(entities, relations, relevant) + var chunks []map[string]interface{} + for _, ev := range evidence { + if ev.DocID != "" && len(ev.IDs) > 0 { + chunks = append(chunks, loadChunksByIDs(ctx, indexNameFor(deps.TenantID, deps.IndexName), ev.IDs)...) + } + } + if strings.TrimSpace(keywords) != "" { + chunks = NarrowByKeywords(chunks, keywords) + } + return ExploreResult{Chunks: chunks, DocAggs: DocAggs(chunks)}, nil +} + +// seedEncoder encodes a seed text into a dense vector. It is a package seam so +// the seed search can be exercised without the tenant embedding service, which +// is backed by the database and therefore unavailable in unit tests. +// +// Returning nil is always valid: every caller falls back to keyword matching. +var seedEncoder = defaultSeedEncoder + +// encodeSeedVector encodes the seed text once for the whole ExploreGraph call. +// Returns nil when the tenant embedding model is unavailable (or encoding fails). +// +// An embedder passed in via SearchDeps.Embedder (the external, Python-style +// "tools.embed_mdl" handle) is used when present; otherwise the call falls back +// to the package's internal resolver (defaultSeedEncoder), which needs a +// database and therefore stays self-contained for callers that cannot or do not +// want to supply one. +func encodeSeedVector(ctx context.Context, deps SearchDeps, tenantID, text string) []float64 { + // Mirror Python's "if getattr(tools, 'embed_mdl', None)" guard: without a + // wired database there is no tenant default embedding model, so skip encoding + // and let the caller fall back to keyword matching rather than panicking. + if dao.GetDB() == nil { + return nil + } + if deps.Embedder != nil { + // The external handle may itself panic on a misconfigured model service + // (e.g. nil-DB); degrade to keyword matching like Python's + // `except Exception` around get_vector, never crash the request. + vecs, err := safeEncodeEmbedder(deps.Embedder, ctx, tenantID, text) + if err != nil || len(vecs) == 0 || len(vecs[0]) == 0 { + return nil + } + out := make([]float64, len(vecs[0])) + for i, v := range vecs[0] { + out[i] = float64(v) + } + return out + } + return seedEncoder(ctx, tenantID, text) +} + +// safeEncodeEmbedder calls the embedder and recovers from any panic so a +// misconfigured embedding service degrades to keyword matching instead of +// crashing the request. It mirrors Python's get_vector exception handling. +func safeEncodeEmbedder(emb nlp.NavEmbedder, ctx context.Context, tenantID, text string) ([][]float32, error) { + defer func() { + if r := recover(); r != nil { + _LOG.Printf("[graph_explore] seed encode panicked; falling back to keyword: %v", r) + } + }() + // Seed encoding is a QUERY, not a document: Python's graph_explore and + // navigation seed through settings.retriever.get_vector → encode_queries. + // Prefer the asymmetric query encoding when the embedder exposes it. + if q, ok := emb.(nlp.NavQueryEmbedder); ok { + return q.EncodeQueries(ctx, tenantID, []string{text}) + } + return emb.Encode(ctx, tenantID, []string{text}) +} + +// SetSeedEncoder overrides the seed embedding used by graph exploration. It is +// a testing seam: the default encoder reaches the tenant embedding service, +// which needs a database that unit tests do not have. Pass nil to restore it. +// Returning nil is always valid — callers fall back to keyword matching. +func SetSeedEncoder(fn func(ctx context.Context, tenantID, text string) []float64) { + if fn == nil { + seedEncoder = defaultSeedEncoder + return + } + seedEncoder = fn +} + +func defaultSeedEncoder(ctx context.Context, tenantID, text string) []float64 { + // Mirror Python's "if getattr(tools, 'embed_mdl', None)" guard: when no + // database (and thus no tenant default embedding model) is wired up, skip + // encoding entirely and fall back to keyword matching rather than panicking + // on a nil DB inside the model-provider layer. + if dao.GetDB() == nil { + return nil + } + embedder := service.NewNavEmbedder(service.NewModelProviderService(), "") + // Query-side encoding: the seed is the user's query (Python get_vector → + // encode_queries), not an indexed document. + vecs, err := embedder.EncodeQueries(ctx, tenantID, []string{text}) + if err != nil || len(vecs) == 0 || len(vecs[0]) == 0 { + return nil + } + vec := make([]float64, len(vecs[0])) + for i, v := range vecs[0] { + vec[i] = float64(v) + } + return vec +} + +// kgSeedSearch searches the compiled KG entity rows for seeds (mirrors Python +// _kg_search dense branch): dense KNN over name_kwd with similarity>=0.8, +// re-ranked by mention_count_int desc, top kgSeeds. Falls back to keyword match +// when seedVec is nil (embedding model unavailable). +func kgSeedSearch(ctx context.Context, de engine.DocEngine, tenantID, kbID string, docIDs []string, text, scopeKwd string, seedVec []float64) []map[string]interface{} { + if seedVec != nil { + dense := &types.MatchDenseExpr{ + VectorColumnName: fmt.Sprintf("q_%d_vec", len(seedVec)), + EmbeddingData: seedVec, + EmbeddingDataType: "float", + DistanceType: "cosine", + TopN: kgSeedPool, + ExtraOptions: map[string]interface{}{"similarity": kgSeedSim}, + } + rows := kgSearchRaw(ctx, de, tenantID, kbID, docIDs, "entity", scopeKwd, nil, []interface{}{dense}, "mention_count_int", kgSeedPool) + return topMentionCount(rows, kgSeeds) + } + // Text fallback (mirrors Python _kg_search `embed_mdl is None` path). + return kgSearch(ctx, de, tenantID, kbID, docIDs, "entity", text, kgSeeds, scopeKwd, nil, "mention_count_int", kgSeedPool) +} + +// topMentionCount re-ranks rows by mention_count_int desc and returns topN. +func topMentionCount(rows []map[string]interface{}, topN int) []map[string]interface{} { + sort.SliceStable(rows, func(i, j int) bool { + return mentionCount(rows[i]) > mentionCount(rows[j]) + }) + if len(rows) > topN { + rows = rows[:topN] + } + return rows +} + +func mentionCount(row map[string]interface{}) int { + switch v := row["mention_count_int"].(type) { + case int: + return v + case int64: + return int(v) + case float64: + return int(v) + case float32: + return int(v) + } + return 0 +} + +// kgSearchRaw is the low-level KG row search with explicit match exprs and any +// extra filter keys (e.g. from_entity_kwd/to_entity_kwd/name_kwd). +func kgSearchRaw(ctx context.Context, de engine.DocEngine, tenantID, kbID string, docIDs []string, kind, scopeKwd string, extra map[string]interface{}, matchExprs []interface{}, orderDesc string, limit int) []map[string]interface{} { + idx := fmt.Sprintf("ragflow_%s", tenantID) + condition := map[string]interface{}{"knowledge_graph_kwd": kind} + if scopeKwd != "" { + condition["scope_kwd"] = scopeKwd + } + if len(docIDs) > 0 { + condition["doc_id"] = docIDs + } + for k, v := range extra { + condition[k] = v + } + fields := []string{"id", "content_with_weight", "source_chunk_ids", "doc_id", "docnm_kwd", "name_kwd", "mention_count_int", "from_entity_kwd", "to_entity_kwd"} + req := &types.SearchRequest{ + IndexNames: []string{idx}, + KbIDs: []string{kbID}, + SelectFields: fields, + Filter: condition, + Limit: limit, + MatchExprs: matchExprs, + } + if orderDesc != "" { + req.OrderBy = &types.OrderByExpr{} + req.OrderBy.Desc(orderDesc) + } + res, err := de.Search(ctx, req) + if err != nil { + return nil + } + return res.Chunks +} + +// kgSearch searches the compiled KG rows of one KB (mirrors Python _kg_search), +// using keyword match. It only builds the MatchTextExpr (with the pool-based +// TopN) and delegates the request construction to kgSearchRaw. +func kgSearch(ctx context.Context, de engine.DocEngine, tenantID, kbID string, docIDs []string, kind, text string, topN int, scopeKwd string, extra map[string]interface{}, orderDesc string, pool int) []map[string]interface{} { + var matchExprs []interface{} + if text != "" { + knnTopN := topN + if pool > knnTopN { + knnTopN = pool + } + matchExprs = []interface{}{&types.MatchTextExpr{ + Fields: []string{"content_ltks", "content_sm_ltks"}, + MatchingText: text, + TopN: knnTopN, + }} + } + return kgSearchRaw(ctx, de, tenantID, kbID, docIDs, kind, scopeKwd, extra, matchExprs, orderDesc, topN) +} + +func kgParseEntity(row map[string]interface{}) (kgEntity, bool) { + name := "" + payload := map[string]interface{}{} + if s, ok := row["content_with_weight"].(string); ok { + _ = json.Unmarshal([]byte(s), &payload) + } + if v, ok := payload["name"].(string); ok && v != "" { + name = v + } else if v, ok := payload["term"].(string); ok && v != "" { + name = v + } else if v, ok := payload["title"].(string); ok && v != "" { + name = v + } + name = strings.TrimSpace(name) + if name == "" { + return kgEntity{}, false + } + e := kgEntity{ + Name: name, + Type: strOr(payload["type"], "other"), + Description: strOr(payload["description"], ""), + SourceChunkIDs: strSliceField(row["source_chunk_ids"]), + DocID: strOr(row["doc_id"], ""), + } + if aliases, ok := payload["aliases"].([]interface{}); ok { + for _, a := range aliases { + if s, ok := a.(string); ok && strings.TrimSpace(s) != "" { + e.Aliases = append(e.Aliases, strings.TrimSpace(s)) + } + } + } + return e, true +} + +func kgParseRelation(row map[string]interface{}) (kgRelation, bool) { + src := strings.TrimSpace(strOr(row["from_entity_kwd"], "")) + tgt := strings.TrimSpace(strOr(row["to_entity_kwd"], "")) + if src == "" || tgt == "" { + return kgRelation{}, false + } + typ := "related" + if payload, ok := row["content_with_weight"].(string); ok { + var p map[string]interface{} + if json.Unmarshal([]byte(payload), &p) == nil { + if t, ok := p["type"].(string); ok && t != "" { + typ = t + } else if t, ok := p["relation"].(string); ok && t != "" { + typ = t + } + } + } + return kgRelation{ + ID: strOr(row["id"], ""), + From: src, To: tgt, Type: typ, + SourceChunkIDs: strSliceField(row["source_chunk_ids"]), + DocID: strOr(row["doc_id"], ""), + }, true +} + +// endpointTerms mirrors Python _endpoint_terms: original + lowercased forms, so +// hop queries match both merged (lowercased) and per-doc (original-case) +// endpoint fields. +func endpointTerms(names []string) []string { + set := map[string]bool{} + for _, n := range names { + n = strings.TrimSpace(n) + if n == "" { + continue + } + set[n] = true + set[strings.ToLower(n)] = true + } + out := make([]string, 0, len(set)) + for n := range set { + out = append(out, n) + } + sort.Strings(out) + return out +} + +// kgEvidence is one document's relevant source chunk ids, in FIRST-SEEN order. +// Python's _collect_evidence_ids returns a dict and graph_explore iterates it with +// `evidence.items()` — insertion-ordered, hence deterministic. A Go map would +// randomise the order, and the executor caps the loaded passages at chunks[:6], +// so the SAME query could surface different passages on every run. +type kgEvidence struct { + DocID string + IDs []string +} + +// collectEvidenceIDs mirrors Python _collect_evidence_ids: group source chunk ids +// of relevant entities AND relations by doc, preserving the doc order in which +// each doc is first reached (Python's dict insertion order). +func collectEvidenceIDs(entities []kgEntity, relations []kgRelation, relevantNames []string) []kgEvidence { + wanted := map[string]bool{} + for _, n := range relevantNames { + if s := strings.TrimSpace(n); s != "" { + wanted[strings.ToLower(s)] = true + } + } + byDoc := make([]kgEvidence, 0, 4) + index := map[string]int{} + seen := map[string]bool{} + add := func(docID string, ids []string) { + for _, cid := range ids { + if cid == "" { + continue + } + key := docID + "|" + cid + if seen[key] { + continue + } + seen[key] = true + i, ok := index[docID] + if !ok { + i = len(byDoc) + index[docID] = i + byDoc = append(byDoc, kgEvidence{DocID: docID}) + } + byDoc[i].IDs = append(byDoc[i].IDs, cid) + } + } + for _, e := range entities { + names := map[string]bool{strings.ToLower(e.Name): true} + for _, a := range e.Aliases { + names[strings.ToLower(a)] = true + } + if intersects(names, wanted) { + add(e.DocID, e.SourceChunkIDs) + } + } + for _, r := range relations { + if wanted[strings.ToLower(r.From)] || wanted[strings.ToLower(r.To)] { + add(r.DocID, r.SourceChunkIDs) + } + } + return byDoc +} + +func intersects(a, b map[string]bool) bool { + for k := range a { + if b[k] { + return true + } + } + return false +} + +// askStructureAnswer asks the chat model whether the subgraph answers the query +// (mirrors Python exploration.py::graph_explore calling _ask_structure), +// returning (answer, relevant_names). Delegates to AskStructure +// (structure_qa.go), the shared mirror of Python _ask_structure. `model` is the +// request-scoped chat model (Python's tools.chat_mdl); a nil model simply skips +// the verdict and yields no answer, matching Python's empty-verdict fallback. +func askStructureAnswer(ctx context.Context, model SessionModel, query string, entities []kgEntity, relations []kgRelation) (string, []string) { + ems := make([]map[string]any, 0, len(entities)) + for _, e := range entities { + ems = append(ems, map[string]any{ + "name": e.Name, "type": e.Type, "description": e.Description, + }) + } + rms := make([]map[string]any, 0, len(relations)) + for _, r := range relations { + rms = append(rms, map[string]any{"from": r.From, "to": r.To, "type": r.Type}) + } + return AskStructure(ctx, model, query, "knowledge graph", "Graph exploration", ems, rms) +} + +func strOr(v interface{}, def string) string { + if s, ok := v.(string); ok && s != "" { + return s + } + return def +} + +func strSliceField(v interface{}) []string { + switch x := v.(type) { + case []string: + return x + case []interface{}: + var out []string + for _, item := range x { + if s, ok := item.(string); ok { + out = append(out, s) + } + } + return out + } + return nil +} diff --git a/internal/rag/advanced_rag/harness/tool_navigation.go b/internal/rag/advanced_rag/harness/tool_navigation.go new file mode 100644 index 00000000000..aae882f6209 --- /dev/null +++ b/internal/rag/advanced_rag/harness/tool_navigation.go @@ -0,0 +1,1575 @@ +// +// 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. +// + +package harness + +import ( + "context" + "fmt" + "sort" + "strconv" + "strings" + + "ragflow/internal/engine" + "ragflow/internal/engine/types" +) + +// Compiled-structure navigation: ontology_navigate / mindmap_navigate / +// navigate_tree / wiki_query. +// +// Mirrors Python harness/tools/navigation.py (the structure side of the module): +// structure navigation, the nav-tree router, the compiled-structure reader and +// dataset-tree LLM selection. The knowledge-graph walk (graph_explore) moved to +// exploration.go to match Python's exploration.py, which hosts both graph_explore +// and wiki_query; the shared seams (verdict struct, prompt, load helpers) stay +// here and are reached by those files through the harness package. In Go these +// were spread across several files (navigation / navtools / navservice / +// datasetnav / kg_explore); they are consolidated here. + +// --------------------------------------------------------------------------- +// Structure navigation (ontology_navigate / mindmap_navigate) +// --------------------------------------------------------------------------- + +var catalogKinds = map[string]bool{"tree": true, "timeline": true, "raptor": true, "page_index": true, "pageindex": true} +var mindmapKinds = map[string]bool{"mindmap": true, "mind_map": true} + +const navSystemPrompt = `You are given the {noun} of one or more documents — an outline of entities and their relations — and a question. + +Decide whether that outline alone already answers the question. + +Rules: +1. Answer ONLY from the outline below. Do not invent facts. +2. Set "is_sufficient" to true only when the outline genuinely answers the question; otherwise false with an empty answer. +3. Always fill "relevant_entities" with the exact ` + "`name`" + ` values of the entities most related to the question (up to 10), even when the outline is not sufficient — they are used to pull the underlying source text. + +Output ONLY JSON, no prose, no code fences: +{"is_sufficient": true/false, "answer": "", "relevant_entities": ["", ...]}` + +const ( + maxStructureEntities = 300 + maxStructureRelations = 300 + maxEvidenceChunks = 24 +) + +type structureEntity struct { + Name string `json:"name"` + Type string `json:"type"` + Description string `json:"description"` + SourceChunkIDs []string `json:"source_chunk_ids"` + DocID string `json:"-"` + Vec []float64 `json:"-"` // q__vec row embedding, when the row carries one +} + +type structureNavVerdict struct { + IsSufficient bool `json:"is_sufficient"` + Answer string `json:"answer"` + RelevantEntities []string `json:"relevant_entities"` +} + +// shapeKwds are the knowledge_graph_kwd ROW SHAPES a compiled structure can be +// written as. Reading BOTH the compact "graph" blob and the per-entity / +// per-relation rows is what mirrors Python _load_compiled_structure (which +// issues one query for the graph blob and a second for the per-entity rows and +// merges them). Otherwise navigation silently returns EMPTY for datasets that +// were compiled into per-entity/relation rows rather than a graph blob. +var shapeKwds = []string{"graph", "entity", "relation"} + +// loadStructureGraph reads a document's compiled structure rows and splits them +// into both the entity list and the parent->child relations. Python merges the +// graph-blob and the per-entity/per-relation row shapes and feeds both entities +// and relations into _render_toc_drilldown / _build_toc_tree; mirroring that, +// navigation must carry relations through or the tree hierarchy (children, +// parents, roots, ancestors) collapses. +func loadStructureGraph(ctx context.Context, indexName, docID string, kinds map[string]bool, vecField string) ([]structureEntity, []structureRel) { + de := engine.Get() + if de == nil { + return nil, nil + } + idx := indexName + selectFields := []string{"content_with_weight", "compile_kwd", "compilation_template_kind_kwd", "knowledge_graph_kwd"} + if vecField != "" { + selectFields = append(selectFields, vecField) + } + req := &types.SearchRequest{ + IndexNames: []string{idx}, + Filter: map[string]interface{}{"doc_id": []string{docID}, "knowledge_graph_kwd": shapeKwds}, + SelectFields: selectFields, + Limit: 3000, + } + res, err := de.Search(ctx, req) + if err != nil { + return nil, nil + } + rows := make([]StructureRow, 0, len(res.Chunks)) + for _, row := range res.Chunks { + kg, _ := row["knowledge_graph_kwd"].(string) + sr := StructureRow{ + CompileKwd: fmt.Sprint(row["compile_kwd"]), + TemplateKind: fmt.Sprint(row["compilation_template_kind_kwd"]), + KnowledgeGraphKwd: kg, + Content: fmt.Sprint(row["content_with_weight"]), + } + if vecField != "" { + if vec, ok := parseFloats(row[vecField]); ok { + sr.Vec = vec + } + } + rows = append(rows, sr) + } + kindList := make([]string, 0, len(kinds)) + for k := range kinds { + kindList = append(kindList, k) + } + rawEntities, rawRels := ParseCompiledStructure(rows, kindList) + var out []structureEntity + for _, e := range rawEntities { + name, _ := e["name"].(string) + if strings.TrimSpace(name) == "" { + continue + } + se := structureEntity{ + Name: name, + Type: fmt.Sprint(e["type"]), + Description: fmt.Sprint(e["description"]), + } + if v, ok := e["_vec"].([]float64); ok { + se.Vec = v + } + if ids, ok := e["source_chunk_ids"].([]interface{}); ok { + for _, id := range ids { + if s, ok := id.(string); ok && s != "" { + se.SourceChunkIDs = append(se.SourceChunkIDs, s) + } + } + } + out = append(out, se) + } + var rels []structureRel + for _, r := range rawRels { + p := strings.TrimSpace(fmt.Sprint(r["from"])) + c := strings.TrimSpace(fmt.Sprint(r["to"])) + // Python _build_toc_tree skips empty or self-loop relations. + if p == "" || c == "" || p == c { + continue + } + rels = append(rels, structureRel{ + from: p, + to: c, + relType: fmt.Sprint(r["type"]), + }) + } + return out, rels +} + +// parseFloats normalizes an engine vector cell — a []float64, or a []any of +// numbers (engine decoders may return either) — into []float64. +func parseFloats(v any) ([]float64, bool) { + switch t := v.(type) { + case []float64: + return t, true + case []any: + out := make([]float64, 0, len(t)) + for _, item := range t { + f, ok := item.(float64) + if !ok { + return nil, false + } + out = append(out, f) + } + return out, true + } + return nil, false +} + +func normalizeKind(row map[string]interface{}) string { + if ck, _ := row["compile_kwd"].(string); ck == "raptor_graph" { + return "raptor" + } + kind, _ := row["compilation_template_kind_kwd"].(string) + if kind == "" { + kind, _ = row["compile_kwd"].(string) + } + kind = strings.ToLower(strings.TrimSpace(strings.ReplaceAll(kind, "-", "_"))) + if kind == "pageindex" || kind == "page_index" || kind == "knowledge_graph" { + return "timeline" + } + return kind +} + +func loadChunksByIDs(ctx context.Context, indexName string, ids []string) []map[string]interface{} { + if len(ids) == 0 { + return nil + } + de := engine.Get() + if de == nil { + return nil + } + idx := indexName + limit := maxEvidenceChunks + if len(ids) < limit { + limit = len(ids) + } + req := &types.SearchRequest{ + IndexNames: []string{idx}, + Filter: map[string]interface{}{"id": ids}, + SelectFields: []string{"content_with_weight", "docnm_kwd", "doc_id"}, + Limit: limit, + } + res, err := de.Search(ctx, req) + if err != nil { + return nil + } + var out []map[string]interface{} + for _, row := range res.Chunks { + out = append(out, map[string]interface{}{ + "chunk_id": row["id"], "content_with_weight": row["content_with_weight"], + "docnm_kwd": row["docnm_kwd"], "doc_id": row["doc_id"], + }) + } + return out +} + +func dedupStrings(in []string) []string { + seen := map[string]bool{} + var out []string + for _, s := range in { + if s != "" && !seen[s] { + seen[s] = true + out = append(out, s) + } + } + return out +} + +func orStr(v, def string) string { + if v == "" { + return def + } + return v +} + +// indexNameFor resolves the document/structure search index. Python reads it +// from the dataset's search.index_name (navigation.py:_navigate_structure_impl); the RAGFlow default +// is "ragflow_", so an empty configured name falls back to that — +// keeping Go behaviour identical unless a tenant overrides index_name. +func indexNameFor(tenantID, configured string) string { + if configured != "" { + return configured + } + return "ragflow_" + tenantID +} + +// --------------------------------------------------------------------------- +// The routing seam + NavResult payload +// --------------------------------------------------------------------------- + +// Compiled-navigation tools: locate (dataset tree routing) and drill +// (in-document structure pinpointing). +// +// Mirrors Python harness/tools/navigation.py: +// - _navigate_tree_impl (line 830) +// - _nav_search_titled (line 659) +// - NavResult (line 62) +// - _load_compiled_structure (line 111) +// - _normalize_kind (line 101) +// +// These are the payload builders; the tool dispatch lives in tool_executor.go. + +// Navigation constants (Python navigation.py:_NAV_SEARCH_MAX_DOCS, 656, 773). +const ( + // navSearchMaxDocs is how many documents the hybrid nav search routes to. + navSearchMaxDocs = 12 + // navMinDocScore drops documents below this score. + navMinDocScore = 0.2 + // navTreeMaxDocs caps the documents surfaced by navigate_tree. + navTreeMaxDocs = 8 +) + +// NavResult mirrors Python NavResult: the structured outcome of ONE +// compiled-navigation call. +// +// Text is what the MODEL sees (XML, unchanged). The remaining fields are the +// signals the ORCHESTRATOR routes on: does this dataset have the structure at +// all, did THIS query reach anything, and was the result worth using? Without +// them the caller can only regex the XML — which is how a `count="1" +// entities="0"` empty shell used to read as a successful hit. +type NavResult struct { + // Text is the XML the model consumes. + Text string + // DocIDs are the documents reached (the routing result). + DocIDs []string + // RoutedDocs are (doc_id, summary) pairs — the routed documents WITH their + // overall summaries. The summary is the "hint" fed back into retrieval: nav + // is a hint, not a constraint, so these become a soft boost/rerank signal + // instead of a hard doc_scope filter. + RoutedDocs [][2]string + // Entities are compiled entities discovered across those documents. + Entities []map[string]any + // Relations are compiled relations discovered across those documents. + Relations []map[string]any + // ChunkPaths maps chunk_id -> root→chunk structure path. + ChunkPaths map[string]string + // EmptyReason is "" when the call succeeded, else the machine-readable cause: + // "infra" (no backend), "bad_args" (missing query), "no_structure" + // (dataset-level: no compiled structure of this kind here), "no_doc" + // (query-level: structure exists but THIS query reached nothing). + EmptyReason string +} + +// HasStructure reports whether the dataset has the compiled structure at all. +// A query-level miss is not a structure absence. +func (n NavResult) HasStructure() bool { return n.EmptyReason != ReasonNoStructure } + +// navEmpty returns an empty NavResult with the given reason and matching status. +func navEmpty(reason, label string) NavResult { + return NavResult{EmptyReason: reason} +} + +// --------------------------------------------------------------------------- +// The routing seam +// --------------------------------------------------------------------------- + +// NavTreeRouter descends a dataset's compiled navigation tree and returns the +// routed documents. +// +// Mirrors Python's `search_dataset_layers(kb.id, tenant_id, query, +// "navigation_tree", top_k, doc_scope)` — a hybrid BFS beam descent (vector + +// BM25) from the root clusters down to the nav_doc leaves. +// +// The Go side exposes this through internal/service/nav's NavService.Search, +// which is the same KNN-over-nav-rows capability. It is an interface here (not a +// direct call) for two reasons: the harness must not import the service layer, +// and a dataset without a compiled tree must be distinguishable from a query +// that routed to nothing. +type NavTreeRouter interface { + // Route descends the nav tree for one dataset and returns the routed + // documents with their summaries, ordered by descending score. + // Returns (nil, nil) when the dataset has no compiled tree at all. + Route(ctx context.Context, tenantID, kbID, query string, docScope []string, topK int) ([][2]string, error) +} + +// NavTreeInput is one navigate_tree call. +type NavTreeInput struct { + Query string + Keywords string + DocScope []string + // TenantID and KbIDs bound the datasets to route over. + TenantID string + KbIDs []string +} + +// NavigateTree mirrors Python _navigate_tree_impl: locate the document(s) most +// likely to hold the answer by descending the compiled navigation tree. +// +// This tool ROUTES, it does not retrieve. It deliberately does NOT fetch +// document content: loading full documents here cost ~79 ES queries per document +// only to render a snippet that navigate_structure supersedes — under per-pass +// fan-out that alone was enough to knock ES over. +// +// Each nav row already carries the document's overall summary, so labelling the +// route costs ZERO extra queries. +// +// There is deliberately NO chunk-retrieval fallback: when routing misses, the +// caller falls back to retrieve/search_chunks — the same work, owned by the +// orchestrator instead of hidden inside a "route" call. +func NavigateTree(ctx context.Context, router NavTreeRouter, in NavTreeInput) NavResult { + query := strings.TrimSpace(in.Query) + if query == "" { + return navEmpty(ReasonBadArgs, "query is required") + } + if router == nil { + return navEmpty(ReasonInfra, "no nav tree router") + } + // Descend on the topic + keywords: routing descends on similarity and does + // not require keyword hits, so keywords only enrich the query. + full := strings.TrimSpace(strings.TrimSpace(in.Query) + " " + strings.TrimSpace(in.Keywords)) + + var ( + // ordered keeps the router's ranking: it returns documents in DESCENDING + // score order, and that ordering IS the routing result. Re-sorting by + // doc_id would discard the relevance the descent computed. + ordered [][2]string + seen = map[string]bool{} + anyTree bool + anyError error + ) + for _, kbID := range in.KbIDs { + routed, err := router.Route(ctx, in.TenantID, kbID, full, in.DocScope, navSearchMaxDocs) + if err != nil { + anyError = err + _LOG.Printf("[Dataset navigation search] nav-tree descent failed for kb=%s: %v", kbID, err) + continue + } + if routed == nil { + // No compiled tree for this dataset (distinguished from "routed to + // nothing" by the router returning an empty non-nil slice). + continue + } + anyTree = true + for _, pair := range routed { + did := strings.TrimSpace(pair[0]) + if did == "" || seen[did] { + continue + } + seen[did] = true + ordered = append(ordered, [2]string{did, strings.TrimSpace(pair[1])}) + } + } + if !anyTree { + // Every dataset lacks a compiled tree — a DATASET-level fact, so the + // caller may disable the tool for the session. + return navEmpty(ReasonNoStructure, "no compiled navigation tree") + } + if len(ordered) == 0 { + // Structure exists but THIS query reached nothing: a query-level miss. + // The dataset may still have a tree a better-formed query would hit. + return navEmpty(ReasonNoDoc, "no document routed") + } + _ = anyError + + // Cap after dedup, preserving the score order. + if len(ordered) > navTreeMaxDocs { + ordered = ordered[:navTreeMaxDocs] + } + docs := make([]string, 0, len(ordered)) + for _, pair := range ordered { + docs = append(docs, pair[0]) + } + + var parts []string + parts = append(parts, fmt.Sprintf(``, len(ordered), XMLEscape(query))) + for i, pair := range ordered { + if pair[1] != "" { + parts = append(parts, + fmt.Sprintf(` `, i+1, XMLEscape(pair[0])), + fmt.Sprintf(" %s", XMLEscape(pair[1])), + " ") + } else { + parts = append(parts, fmt.Sprintf(` `, i+1, XMLEscape(pair[0]))) + } + } + parts = append(parts, "") + + return NavResult{ + Text: strings.Join(parts, "\n"), + DocIDs: docs, + RoutedDocs: ordered, + } +} + +// --------------------------------------------------------------------------- +// Compiled-structure reading (in-document) +// --------------------------------------------------------------------------- + +// StructureRow is one compiled-structure row, mirroring the doc-store fields +// Python reads (navigation.py:_load_compiled_structure). +type StructureRow struct { + // CompileKwd distinguishes the COMPILE TYPE (tree / page_index / timeline / + // raptor_graph / ...). NOT knowledge_graph_kwd. + CompileKwd string + // TemplateKind is the template-authored kind (compilation_template_kind_kwd). + TemplateKind string + // KnowledgeGraphKwd selects the ROW SHAPE: + // "graph" → one compact blob whose content is {"entities":[], "relations":[]} + // (written by RAPTOR / tree compilation) + // "entity" → one row per node, content is a single entity dict + // "relation" → one row per edge, content is a single relation dict + // (written by page_index and the pipeline Compiler tree) + KnowledgeGraphKwd string + // Content is the row's JSON payload. + Content string + // Vec is the row's q__vec embedding, when the reader selected it. A + // graph blob row carries the one vector its nested nodes share (RAPTOR); a + // per-entity row carries that node's own vector (page_index). + Vec []float64 +} + +// StructureReader reads a document's compiled structure rows. +// +// Mirrors Python _load_compiled_structure, which issues +// three doc-store queries (graph blob, per-entity/relation rows, raptor_graph) +// and merges the matching buckets. +// +// Go has no doc-store structured-query interface (see runtime.RetrievalService, +// which only exposes Search), so this is a seam: the harness ships the full +// parsing/merging logic below, and the reader is injected. Until a Go-side +// implementation is wired, navigate_structure reports EMPTY/no_structure and the +// navigation ladder falls through to `global` — the same behaviour as a dataset +// with no compiled structures. +type StructureReader interface { + // ReadStructure returns the compiled rows for a document. Returns nil when + // the backend has no compiled-structure support at all. + ReadStructure(ctx context.Context, tenantID, kbID, docID string) ([]StructureRow, error) +} + +// normalizeKind is defined above; rowKind projects a StructureRow into that +// shape. It mirrors Python _normalize_kind: the API's kind normalization +// (page_index / knowledge_graph → timeline), plus the raptor_graph override. +func rowKind(row StructureRow) string { + return normalizeKind(map[string]any{ + "compile_kwd": row.CompileKwd, + "compilation_template_kind_kwd": row.TemplateKind, + }) +} + +// ParseCompiledStructure mirrors Python _load_compiled_structure's merge step +// (navigation.py:_query): keep rows whose compile TYPE is in kinds, then split +// by row shape into entities / relations. +// +// Two row shapes coexist for compiled structures, and a given compile type may +// produce either: +// +// graph blob (knowledge_graph_kwd="graph"): nested entities/relations +// per-entity (knowledge_graph_kwd="entity"): one node per row +// per-relation (knowledge_graph_kwd="relation"): one edge per row +// +// Reading BOTH and merging is what makes navigation work regardless of which +// shape a compile type produced. +func ParseCompiledStructure(rows []StructureRow, kinds []string) ([]map[string]any, []map[string]any) { + want := map[string]bool{} + for _, k := range kinds { + if k != "" { + want[k] = true + } + } + var entities, relations []map[string]any + for _, row := range rows { + kind := rowKind(row) + if len(want) > 0 && !want[kind] { + continue + } + graph, ok := decodeJSONObject(row.Content) + if !ok { + continue + } + attachVec := func(list []map[string]any) { + if len(row.Vec) == 0 { + return + } + for _, m := range list { + m["_vec"] = row.Vec + } + } + switch row.KnowledgeGraphKwd { + case "graph": + es := objectList(graph["entities"]) + rs := objectList(graph["relations"]) + attachVec(es) + attachVec(rs) + entities = append(entities, es...) + relations = append(relations, rs...) + case "entity": + attachVec([]map[string]any{graph}) + entities = append(entities, graph) + case "relation": + attachVec([]map[string]any{graph}) + relations = append(relations, graph) + } + } + return entities, relations +} + +func decodeJSONObject(s string) (map[string]any, bool) { + v := ExtractJSON(s) + m, ok := v.(map[string]any) + return m, ok +} + +func objectList(v any) []map[string]any { + list, _ := v.([]any) + out := make([]map[string]any, 0, len(list)) + for _, item := range list { + if m, ok := item.(map[string]any); ok { + out = append(out, m) + } + } + return out +} + +// --------------------------------------------------------------------------- +// In-document structure drill-down (mirrors navigation.py, distributed helpers) +// --------------------------------------------------------------------------- +// +// These are the Go counterparts of the functions navigation.py DEFINES in its +// own body. Like Python, they reuse primitives imported from elsewhere: cosine / +// appendUnique (compiled_expansion.go, action_session.go), XMLEscape / Snippet / +// ChunkTextOf (chunk_utils.go). They stay here so navigation.go owns the +// navigate-tree / navigate-structure algorithm, mirroring how navigation.py owns +// its orchestration while importing its primitives. + +// Structure drill-down bounds (mirror navigation.py's module-level limits). +const ( + structMaxDepth = 12 // _STRUCT_MAX_DEPTH: stop walking past this depth + structMaxNodes = 300 // _STRUCT_MAX_NODES: cap on nodes kept per level + structBranchK = 12 // _STRUCT_BRANCH_K: children kept per node + structVecBeamRatio = 0.65 // _STRUCT_VEC_BEAM_RATIO: score floor relative to best + structRelevanceMin = 1 // min keyword relevance to keep a node without a vector + structDescSnippet = 300 // snippet length for a node's description in the outline + structMaxChunks = 6 // _STRUCT_MAX_CHUNKS: top chunks exposed per drilled doc + structCatalogKinds = "tree_node|page_index|section" // kinds eligible for catalog outline + + // structTocMaxDepth bounds the ancestor walk in renderTocDrilldown's + // chunk-retrieval and llm_toc branches (Python _STRUCT_TOC_MAX_DEPTH). The + // remaining _STRUCT_TOC_* limits gate the whole-TOC LLM pass, which Python + // leaves off by default; they are not mirrored (they would be unreachable in + // Go). + structTocMaxDepth = 6 + + // Chunk-index selection bounds for structures that cannot score themselves + // (RAPTOR blob path). Mirror _STRUCT_RECALL_TOP_N and _STRUCT_MAX_CHUNK_HITS. + structRecallTopN = 24 // _STRUCT_RECALL_TOP_N: hybrid chunk hits recalled per document + structMaxChunkHits = 8 // _STRUCT_MAX_CHUNK_HITS: retrieved chunks shown per drilled doc +) + +// queryTerms mirrors navigation.py's regex tokenizer: lowercase coarse word +// tokens of length >= 2 (the BM25-ish keyword signal). +func queryTerms(q string) []string { + if q == "" { + return nil + } + lower := strings.ToLower(q) + var out []string + var cur []byte + for i := 0; i < len(lower); i++ { + c := lower[i] + if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' { + cur = append(cur, c) + continue + } + if len(cur) >= 2 { + out = append(out, string(cur)) + } + cur = cur[:0] + } + if len(cur) >= 2 { + out = append(out, string(cur)) + } + return out +} + +// nodeRelevance mirrors navigation.py _node_relevance: how many query terms occur +// in a TOC node's name+description. +func nodeRelevance(terms []string, name, desc string) int { + if len(terms) == 0 { + return 0 + } + text := strings.ToLower(name + " " + desc) + n := 0 + for _, t := range terms { + if strings.Contains(text, t) { + n++ + } + } + return n +} + +// structureNode is a node of a compiled structure hierarchy during drill-down: +// the entity plus its optional embedding vector (for cosine scoring). +type structureNode struct { + name string + nodeType string + desc string + sourceChunkIDs []string + vec []float64 +} + +// structureRel is a parent->child relation of a compiled structure hierarchy. +type structureRel struct { + from string + to string + relType string +} + +// buildTocTree mirrors navigation.py _build_toc_tree: a name->node map, the +// parent->children map, the child->parent map (single parent, last-wins) and the +// root names (tree nodes with no parent; isolated nodes are their own roots). +func buildTocTree(nodes []structureNode, rels []structureRel) (map[string]structureNode, map[string][]string, map[string]string, []string) { + byName := map[string]structureNode{} + for _, n := range nodes { + if n.name != "" { + byName[n.name] = n + } + } + children := map[string][]string{} + parents := map[string]string{} + for _, r := range rels { + p, c := r.from, r.to + if p == "" || c == "" || p == c { + continue + } + if _, ok := children[p]; !ok { + children[p] = []string{} + } + dup := false + for _, x := range children[p] { + if x == c { + dup = true + break + } + } + if !dup { + children[p] = append(children[p], c) + } + parents[c] = p + } + var roots []string + for n := range byName { + if _, has := parents[n]; !has { + roots = append(roots, n) + } + } + if len(roots) == 0 { + for n := range byName { + if _, has := children[n]; !has { + roots = append(roots, n) + } + } + } + if len(roots) == 0 { + for n := range byName { + roots = append(roots, n) + } + } + return byName, children, parents, roots +} + +// chunkPtrs mirrors navigation.py _chunk_ptrs: a bounded, deduped comma-joined +// slice of an item's source chunk ids (<=8, the anchors the model sees). +func chunkPtrs(ids []string) string { + if len(ids) == 0 { + return "" + } + var seen []string + for _, c := range ids { + if c == "" { + continue + } + if !sliceContains(seen, c) { + seen = append(seen, c) + if len(seen) >= 8 { + break + } + } + } + return strings.Join(seen, ",") +} + +func sliceContains(s []string, v string) bool { + for _, x := range s { + if x == v { + return true + } + } + return false +} + +// collectChunkIDs mirrors navigation.py _collect_chunk_ids: a deduped, capped +// union of source chunk ids across a set of nodes. +func collectChunkIDs(nodes []structureNode, capN int) []string { + if capN <= 0 { + capN = 32 + } + var out []string + for _, n := range nodes { + for _, c := range n.sourceChunkIDs { + if c == "" { + continue + } + if sliceContains(out, c) { + continue + } + out = append(out, c) + if len(out) >= capN { + return out + } + } + } + return out +} + +// nodeScore mirrors navigation.py _node_score: cosine when a query vector and the +// node embedding both exist, else keyword relevance. +func nodeScore(qvec []float64, terms []string, n structureNode) float64 { + if len(qvec) > 0 && len(n.vec) > 0 { + return cosine(qvec, n.vec) + } + return float64(nodeRelevance(terms, n.name, n.desc)) +} + +// vecsEqual reports whether two node embeddings are element-wise equal, mirroring +// navigation.py _vecs_equal. Zero-length or differently-sized vectors are unequal. +func vecsEqual(a, b []float64) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +// hasDistinctNodeVectors reports whether the nodes carry per-node embeddings +// rather than one shared vector. Mirrors navigation.py _has_distinct_node_vectors: +// a page_index / per-node tree has distinct node vectors, while a RAPTOR blob +// inherits the blob's one vector for every node. Returns false when fewer than +// two nodes carry a vector or all share the same one. +func hasDistinctNodeVectors(nodes []structureNode) bool { + var first []float64 + haveFirst := false + for _, n := range nodes { + if len(n.vec) == 0 { + continue + } + if !haveFirst { + first = n.vec + haveFirst = true + continue + } + if !vecsEqual(first, n.vec) { + return true + } + } + return false +} + +// nodesCoveringChunks returns the names of nodes whose source_chunk_ids cover any +// of chunkIDs, mirroring navigation.py _nodes_covering_chunks. Used only to give +// retrieved chunks a structural home; a chunk no node covers is still shown. +func nodesCoveringChunks(nodes []structureNode, chunkIDs []string) []string { + if len(chunkIDs) == 0 { + return nil + } + want := make(map[string]bool, len(chunkIDs)) + for _, c := range chunkIDs { + if c != "" { + want[c] = true + } + } + var names []string + for _, n := range nodes { + name := strings.TrimSpace(n.name) + if name == "" { + continue + } + for _, c := range n.sourceChunkIDs { + if c != "" && want[c] { + names = append(names, name) + break + } + } + } + return names +} + +// recallChunkIDsInDoc mirrors navigation.py _recall_chunk_ids_in_doc: for a +// structure whose nodes share one blob vector (RAPTOR) it asks the retrieval +// backend for the document's most relevant ORIGINAL chunks (the backend already +// excludes compiled rows), and returns them as (id, score) hits. A nil +// retriever, empty query, or an error yields no hits. +func recallChunkIDsInDoc(ctx context.Context, retriever Retriever, query, docID, tenantID string, datasetIDs []string, topN int) []chunkHit { + if retriever == nil || query == "" || docID == "" { + return nil + } + if topN <= 0 { + topN = structRecallTopN + } + chunks, err := retriever.Retrieve(ctx, RetrieveRequest{ + Query: query, + DatasetIDs: datasetIDs, + DocScope: []string{docID}, + TopN: topN, + TenantID: tenantID, + }) + if err != nil || len(chunks) == 0 { + return nil + } + hits := make([]chunkHit, 0, len(chunks)) + for _, c := range chunks { + id, _ := c["chunk_id"].(string) + if id == "" { + continue + } + score := 0.0 + if s, ok := c["similarity"].(float64); ok { + score = s + } + hits = append(hits, chunkHit{id: id, score: score}) + } + return hits +} + +// drillKeptNodes mirrors navigation.py _drill_kept_nodes: vector-beam BFS descent +// from the TOC roots, keeping top-K children per level by cosine (relative beam +// threshold) or by keyword relevance (absolute minimum), returning the kept +// nodes, the single-parent map, the kept-name set and the overall best score. +func drillKeptNodes(qvec []float64, terms []string, nodes []structureNode, rels []structureRel) ([]structureNode, map[string]string, map[string]bool, float64) { + byName, children, parents, roots := buildTocTree(nodes, rels) + if len(roots) == 0 { + return nil, nil, nil, 0.0 + } + frontier := roots + keptNames := map[string]bool{} + depth := 0 + bestOverall := 0.0 + for len(frontier) > 0 && depth <= structMaxDepth { + type scored struct { + score float64 + name string + } + var scoredList []scored + for _, n := range frontier { + e, ok := byName[n] + if ok { + scoredList = append(scoredList, scored{nodeScore(qvec, terms, e), n}) + } + } + if len(scoredList) == 0 { + break + } + sort.SliceStable(scoredList, func(i, j int) bool { return scoredList[i].score > scoredList[j].score }) + best := scoredList[0].score + if best > bestOverall { + bestOverall = best + } + if len(qvec) == 0 && best < float64(structRelevanceMin) { + break + } + var top []scored + if len(qvec) > 0 { + for _, s := range scoredList { + if s.score >= best*structVecBeamRatio { + top = append(top, s) + if len(top) >= structBranchK { + break + } + } + } + } else { + for _, s := range scoredList { + if s.score >= float64(structRelevanceMin) { + top = append(top, s) + if len(top) >= structBranchK { + break + } + } + } + } + if len(top) == 0 { + break + } + var next []string + for _, s := range top { + if !keptNames[s.name] { + keptNames[s.name] = true + } + next = append(next, children[s.name]...) + } + frontier = next + depth++ + } + for name := range keptNames { + cur := parents[name] + guard := 0 + for cur != "" && !keptNames[cur] && guard < structMaxDepth { + keptNames[cur] = true + cur = parents[cur] + guard++ + } + } + var kept []structureNode + for n := range keptNames { + if e, ok := byName[n]; ok { + kept = append(kept, e) + } + } + return kept, parents, keptNames, bestOverall +} + +// outlineStats mirrors navigation.py _outline_stats: the entity / chunk-pointer +// counts for the flat fallback outline (no drill happened => top_score 0). +func outlineStats(nodes []structureNode) (nodeCount, ptrCount int) { + count := len(nodes) + if count > structMaxNodes { + count = structMaxNodes + } + ptrs := 0 + for _, n := range nodes[:count] { + ptrs += len(collectChunkIDs([]structureNode{n}, 32)) + } + return count, ptrs +} + +// navTypeOr returns a node type, defaulting to "other" as Python's +// “(e.get("type") or "other")“ does. +func navTypeOr(t string) string { + if t == "" { + return "other" + } + return t +} + +// navOutlineLine renders one "- name (type): desc [chunks: c1,c2]" line. +func navOutlineLine(indent, name, nodeType, desc string, chunks []string) string { + line := indent + "- " + name + " (" + navTypeOr(nodeType) + ")" + if desc != "" { + line += ": " + Snippet(desc, structDescSnippet) + } + if c := chunkPtrs(chunks); c != "" { + line += " [chunks: " + c + "]" + } + return line +} + +// renderOutline mirrors navigation.py _render_outline: a compact flat outline of +// entities then relations (fallback when no query terms are usable). +func renderOutline(nodes []structureNode, rels []structureRel) string { + var lines []string + capE, capR := 40, 40 + for i, n := range nodes { + if i >= capE || n.name == "" { + continue + } + lines = append(lines, navOutlineLine("", n.name, n.nodeType, n.desc, n.sourceChunkIDs)) + } + for i, r := range rels { + if i >= capR || r.from == "" || r.to == "" { + continue + } + rt := r.relType + if rt == "" { + rt = "related_to" + } + lines = append(lines, "- "+r.from+" -["+rt+"]-> "+r.to) + } + return strings.Join(lines, "\n") +} + +// rankChunksByTerms mirrors navigation.py _rank_chunks_by_terms: rank candidate +// chunks by how many query terms overlap with their text. Zero-LLM keyword +// relevance for the precise chunk_ids path. The accessor abstracts reading a +// chunk's text so the harness stays store-agnostic and testable. +func rankChunksByTerms(candidates []chunkWithText, queries []string) []chunkWithText { + terms := make([]string, 0, 8) + for _, q := range queries { + for _, tok := range queryTerms(q) { + if !sliceContains(terms, tok) { + terms = append(terms, tok) + } + } + } + if len(terms) == 0 { + return candidates + } + type scored struct { + hits int + c chunkWithText + } + var scoredList []scored + for _, c := range candidates { + text := strings.ToLower(c.text) + hits := 0 + for _, t := range terms { + if strings.Contains(text, t) { + hits++ + } + } + if hits > 0 { + scoredList = append(scoredList, scored{hits, c}) + } + } + sort.SliceStable(scoredList, func(i, j int) bool { return scoredList[i].hits > scoredList[j].hits }) + out := make([]chunkWithText, 0, len(scoredList)) + for _, s := range scoredList { + out = append(out, s.c) + } + return out +} + +// chunkWithText pairs a chunk id with its text for structure snippet ranking. +type chunkWithText struct { + id string + text string +} + +// structureDrillout is the per-document result of the TOC drill-down, mirroring +// what Python's _render_toc_drilldown returns and the per-doc stats +// _navigate_structure_impl aggregates. selector records which strategy chose the +// nodes: llm_toc / chunk_retrieval / beam (stats["selector"] in Python). +type structureDrillout struct { + outline string + nodes int + chunkPtrs int + topScore float64 + chunkPaths map[string]string + selector string +} + +// chunkHit is a retrieved chunk id with its retrieval score, the input shape of +// the chunk_retrieval strategy (Python chunk_hits: list[(chunk_id, score)]). +type chunkHit struct { + id string + score float64 +} + +// drillWithAncestors pulls the ancestors of names into the kept set so a path +// renders as root -> ... -> node, mirroring _with_ancestors in _render_toc_drilldown. +func drillWithAncestors(names map[string]bool, parents map[string]string) map[string]bool { + for name := range names { + cur := parents[name] + guard := 0 + for cur != "" && !names[cur] && guard < structTocMaxDepth { + names[cur] = true + cur = parents[cur] + guard++ + } + } + return names +} + +// renderTocDrilldown mirrors navigation.py _render_toc_drilldown: it renders a +// query-focused outline of one document's compiled structure, choosing the nodes +// to show by one of three strategies in priority order: +// +// - selected (non-empty): node names picked by the whole-TOC LLM pass, kept +// whole with their ancestors — selector "llm_toc". +// - chunkHits (non-empty): [(id, score)] from chunk retrieval (RAPTOR blob path); +// the chunks are shown as retrieved and the tree only labels where they sit — +// selector "chunk_retrieval". +// - neither: VECTOR BEAM descent toward the query, falling back to keyword +// overlap when no vectors are available — selector "beam". +// +// When no terms/vector and neither selection is provided it falls back to the flat +// outline. loader, when non-nil, fetches chunk texts so short snippets can be +// appended; a nil loader skips the snippet pass. +func renderTocDrilldown(query string, qvec []float64, nodes []structureNode, rels []structureRel, loader func(ids []string) []chunkWithText, chunkHits []chunkHit, selected []string) structureDrillout { + flat := func() structureDrillout { + out := renderOutline(nodes, rels) + n, p := outlineStats(nodes) + return structureDrillout{outline: out, nodes: n, chunkPtrs: p, topScore: 0.0, chunkPaths: map[string]string{}} + } + terms := queryTerms(query) + // Pinned nodes (chunk retrieval / whole-TOC) stand even when the query yields + // no usable terms or vector; bailing out here would discard a valid selection. + if len(chunkHits) == 0 && len(selected) == 0 && len(terms) == 0 && len(qvec) == 0 { + return flat() + } + + byName, _, parents, _ := buildTocTree(nodes, rels) + + var kept []structureNode + var keptNames map[string]bool + var selectedIDs []string + best := 0.0 + selector := "beam" + + switch { + case len(selected) > 0: + names := make(map[string]bool) + for _, n := range selected { + if _, ok := byName[n]; ok { + names[n] = true + } + } + keptNames = drillWithAncestors(names, parents) + for n := range keptNames { + if e, ok := byName[n]; ok { + kept = append(kept, e) + } + } + best = 0.0 + selector = "llm_toc" + case len(chunkHits) > 0: + seen := make(map[string]bool) + for _, h := range chunkHits { + if h.id != "" && !seen[h.id] { + seen[h.id] = true + selectedIDs = append(selectedIDs, h.id) + } + } + covering := nodesCoveringChunks(nodes, selectedIDs) + names := make(map[string]bool) + for _, n := range covering { + if _, ok := byName[n]; ok { + names[n] = true + } + } + keptNames = drillWithAncestors(names, parents) + for n := range keptNames { + if e, ok := byName[n]; ok { + kept = append(kept, e) + } + } + for _, h := range chunkHits { + if h.score > best { + best = h.score + } + } + selector = "chunk_retrieval" + default: + kept, parents, keptNames, best = drillKeptNodes(qvec, terms, nodes, rels) + selector = "beam" + } + if len(kept) == 0 && len(selectedIDs) == 0 { + // A strategy was chosen but kept nothing; still report which one ran. + out := flat() + out.selector = selector + return out + } + // depth_of: node -> number of kept ancestors (rendering indentation). + depthOf := map[string]int{} + for n := range keptNames { + d := 0 + cur := parents[n] + for cur != "" && keptNames[cur] { + d++ + cur = parents[cur] + } + depthOf[n] = d + } + // root -> ... -> node path for each kept node, mapped onto its chunks. + chunkPaths := map[string]string{} + for _, e := range kept { + name := strings.TrimSpace(e.name) + if name == "" { + continue + } + var segs []string + segs = append(segs, name) + cur := parents[name] + guard := 0 + for cur != "" && guard < structMaxDepth { + segs = append(segs, cur) + cur = parents[cur] + guard++ + } + for i, j := 0, len(segs)-1; i < j; i, j = i+1, j-1 { + segs[i], segs[j] = segs[j], segs[i] + } + path := strings.Join(segs, " -> ") + for _, cid := range e.sourceChunkIDs { + if cid != "" { + if _, seen := chunkPaths[cid]; !seen { + chunkPaths[cid] = path + } + } + } + } + var lines []string + count := len(kept) + if count > structMaxNodes { + count = structMaxNodes + } + for _, e := range kept[:count] { + name := strings.TrimSpace(e.name) + if name == "" { + continue + } + indent := strings.Repeat(" ", depthOf[name]) + lines = append(lines, navOutlineLine(indent, name, e.nodeType, e.desc, e.sourceChunkIDs)) + } + // Chunk snippets. When chunk retrieval did the selecting, the hits are shown + // as-is (filtering them back through the nodes would drop chunks no node + // covers); otherwise take the chunks behind the drilled nodes. + wanted := collectChunkIDs(kept, 32) + if len(selectedIDs) > 0 { + wanted = selectedIDs + } + if len(wanted) > 0 && loader != nil { + chunks := loader(wanted) + if len(chunks) > 0 { + var ranked []chunkWithText + limit := structMaxChunks + if len(selectedIDs) > 0 { + // Retrieval order is the relevance order; re-ranking by terms would + // discard the score that selected them. + pos := make(map[string]int, len(selectedIDs)) + for i, id := range selectedIDs { + pos[id] = i + } + ranked = append(ranked, chunks...) + sort.SliceStable(ranked, func(i, j int) bool { return pos[ranked[i].id] < pos[ranked[j].id] }) + limit = structMaxChunkHits + } else { + ranked = rankChunksByTerms(chunks, []string{query}) + } + capN := len(ranked) + if capN > limit { + capN = limit + } + for _, c := range ranked[:capN] { + text := strings.TrimSpace(c.text) + if text == "" { + continue + } + lines = append(lines, "- [chunk "+c.id+"]: "+Snippet(text, 300)) + } + } + } + return structureDrillout{ + outline: strings.Join(lines, "\n"), + nodes: len(kept), + chunkPtrs: len(wanted), + topScore: best, + chunkPaths: chunkPaths, + selector: selector, + } +} + +// --------------------------------------------------------------------------- +// navigate_structure (zero-LLM vector-beam drill-down; mirrors _navigate_structure_impl) +// --------------------------------------------------------------------------- + +// structureKindsFor maps a navigate_structure kind string to the compiled-kinds +// set to read, mirroring navigation.py _structure_kinds_for. Defaults to catalog. +func structureKindsFor(kind string) map[string]bool { + k := strings.TrimSpace(strings.ToLower(kind)) + if k == "" { + k = "catalog" + } + switch k { + case "mindmap", "mind_map", "concept": + out := make(map[string]bool, len(mindmapKinds)) + for kk := range mindmapKinds { + out[kk] = true + } + return out + case "graph", "kg", "entity", "ontology": + return map[string]bool{"graph": true, "ontology": true, "entity": true, "raptor": true} + default: + out := make(map[string]bool, len(catalogKinds)) + for kk := range catalogKinds { + out[kk] = true + } + return out + } +} + +// structureNodesFromEntities converts loaded structure entities into the +// drill-down node shape (no vectors unless filled in by a vector pass). +func structureNodesFromEntities(es []structureEntity) []structureNode { + if len(es) == 0 { + return nil + } + nodes := make([]structureNode, 0, len(es)) + for _, e := range es { + if strings.TrimSpace(e.Name) == "" { + continue + } + nodes = append(nodes, structureNode{ + name: strings.TrimSpace(e.Name), + nodeType: e.Type, + desc: e.Description, + sourceChunkIDs: append([]string(nil), e.SourceChunkIDs...), + vec: e.Vec, + }) + } + return nodes +} + +// structureNodeLoader fetches chunk texts by id for the drill-down snippet pass, +// mirroring the chunk loader _render_toc_drilldown uses. Returns nil when the +// store/engine is not available (outline still renders, minus snippets). +func structureNodeLoader(ctx context.Context, indexName string, ids []string) []chunkWithText { + raw := loadChunksByIDs(ctx, indexName, ids) + if len(raw) == 0 { + return nil + } + out := make([]chunkWithText, 0, len(raw)) + for _, c := range raw { + id := ChunkIDOf(c) + if id == "" { + continue + } + out = append(out, chunkWithText{id: id, text: ChunkTextOf(c)}) + } + return out +} + +// readStructureDocCore reads ONE document's compiled structure of the requested +// kind and vector-beam drills it toward the query. It returns the per-document +// drill data (entities, relations, outline, chunk pointers) rather than the XML, +// so both the single-doc wrapper and the multi-doc router render the same doc as +// a segment. emptyReason == "" means the structure was read. +func readStructureDocCore(ctx context.Context, tenantID, query, docID, kind string, deps SearchDeps) (structureDrillout, []structureNode, []structureRel, string) { + none := structureDrillout{chunkPaths: map[string]string{}} + switch { + case query == "": + return none, nil, nil, ReasonBadArgs + case docID == "": + return none, nil, nil, ReasonNoDoc + } + // Python _load_compiled_structure → _resolve_doc_tenant: a document that is + // not in the bound datasets yields an empty structure rather than an + // unscoped read, so a stale doc_id cannot pull in another dataset's outline. + if belongs, verified := docInDatasets(ctx, deps, docID); verified && !belongs { + return none, nil, nil, ReasonNoStructure + } + kinds := structureKindsFor(kind) + indexName := indexNameFor(tenantID, deps.IndexName) + // Vector-aware load mirrors _read_structures: encode the query first so the + // structure rows can be read with the q__vec field, then judge whether + // the nodes carry per-node embeddings. + var qvec []float64 + var vecField string + if vec := encodeSeedVector(ctx, deps, tenantID, query); vec != nil { + qvec = vec + vecField = "q_" + strconv.Itoa(len(vec)) + "_vec" + } + entities, rels := loadStructureGraph(ctx, indexName, docID, kinds, vecField) + nodes := structureNodesFromEntities(entities) + if len(nodes) == 0 { + return none, nil, nil, ReasonNoStructure + } + loader := func(ids []string) []chunkWithText { return structureNodeLoader(ctx, indexName, ids) } + + // RAPTOR / shared-vector blobs cannot score their nodes against the query, so + // they defer to chunk retrieval for the drill (mirrors Python routing them to + // _recall_chunk_ids_in_doc). Per-node-vector structures keep the beam drill. + var chunkHits []chunkHit + if !hasDistinctNodeVectors(nodes) { + chunkHits = recallChunkIDsInDoc(ctx, deps.Backend, query, docID, tenantID, deps.KbIDs, 0) + } + drill := renderTocDrilldown(query, qvec, nodes, rels, loader, chunkHits, nil) + return drill, nodes, rels, "" +} + +// structureDocSegment renders one element (doc_id / doc_title="" / +// entities / relations plus the outline), mirroring Python +// navigation._navigate_structure_impl where doc_title is always empty. +func structureDocSegment(docID, query, kind string, rank int, nodes []structureNode, rels []structureRel, drill structureDrillout) string { + esc := func(s string) string { return XMLEscape(s) } + var b strings.Builder + fmt.Fprintf(&b, ` `, rank, esc(docID), len(nodes), len(rels)) + if drill.outline != "" { + b.WriteString("\n " + esc(drill.outline) + "") + } + b.WriteString("\n ") + return b.String() +} + +// emptyReasonLabel maps an empty-reason constant to the XML error label Python +// writes into . +func emptyReasonLabel(reason string) string { + switch reason { + case ReasonBadArgs: + return "query is required" + case ReasonNoDoc: + return "no document located" + default: + return "no structure" + } +} + +// navigateStructures renders the compiled structures of MULTIPLE documents into a +// single with one per readable structure, mirroring +// Python _read_structures + _navigate_structure_impl: each document is read and +// drilled independently, documents without a compiled structure of the requested +// kind are skipped, and the resulting outline(s) are merged with per-doc ranks. +// The aggregate drillout carries summed node/pointer counts, the max top score, +// and the union of chunk paths across the documents. +// navigateStructures drills the requested compiled-structure kind across the +// given documents. When docIDs is empty it mirrors Python _navigate_structure_impl +// (:1012): with no doc_id it vector-routes the documents FIRST (search_dataset_layers / +// the nav tree) and then drills those — so a direct call need not rely on its +// caller pre-routing. The Go navigate_structure TOOL already routes before calling +// this, so in the tool path docIDs is non-empty and routing here is a no-op. +func navigateStructures(ctx context.Context, tenantID, query string, docIDs []string, kind string, router NavTreeRouter, deps SearchDeps) (NavResult, structureDrillout) { + agg := structureDrillout{chunkPaths: map[string]string{}} + var segs []string + var docIDsSeen []string + var entities []map[string]any + if len(docIDs) == 0 { + // Python _navigate_structure_impl with an empty doc scope vector-routes + // the documents first; only if that also reaches nothing is it a MISS. + if router != nil { + // DocScope: the session ceiling, mirroring _nav_search_titled + // (navigation.py:_navigate_structure_impl), which _navigate_structure_impl routes + // through when doc_ids is empty (:1012). + routed := NavigateTree(ctx, router, NavTreeInput{ + Query: query, + KbIDs: deps.KbIDs, + TenantID: tenantID, + DocScope: deps.DocScope, + }) + docIDs = dedupStrings(routed.DocIDs) + } + if len(docIDs) == 0 { + return NavResult{ + Text: `` + "\n", + EmptyReason: ReasonNoDoc, + }, agg + } + } + for _, did := range docIDs { + drill, nodes, rels, empty := readStructureDocCore(ctx, tenantID, query, did, kind, deps) + if empty != "" { + // No compiled structure of this kind — Python's per-doc read skips it. + continue + } + segs = append(segs, structureDocSegment(did, query, kind, len(segs)+1, nodes, rels, drill)) + docIDsSeen = append(docIDsSeen, did) + entities = append(entities, entityMaps(nodes)...) + agg.nodes += drill.nodes + agg.chunkPtrs += drill.chunkPtrs + if drill.topScore > agg.topScore { + agg.topScore = drill.topScore + } + for cid, p := range drill.chunkPaths { + if _, ok := agg.chunkPaths[cid]; !ok { + agg.chunkPaths[cid] = p + } + } + } + if len(segs) == 0 { + // doc_ids were given but none carried a compiled structure of this kind — + // Python _navigate_structure_impl sets empty_reason="no_structure" when + // total_entities == 0 (its count="0" carries no + // elements). + return NavResult{ + Text: `` + "\n", + EmptyReason: ReasonNoStructure, + }, agg + } + esc := func(s string) string { return XMLEscape(s) } + parts := append([]string{ + fmt.Sprintf(``, len(segs), esc(query), esc(kind)), + }, segs...) + parts = append(parts, "") + return NavResult{ + Text: strings.Join(parts, "\n"), + DocIDs: docIDsSeen, + Entities: entities, + ChunkPaths: agg.chunkPaths, + EmptyReason: "", + }, agg +} + +// entityMaps renders drill nodes back to the generic maps the orchestrator's +// NavResult.Entities slice carries. +func entityMaps(nodes []structureNode) []map[string]any { + out := make([]map[string]any, 0, len(nodes)) + for _, n := range nodes { + out = append(out, map[string]any{ + "name": n.name, + "type": n.nodeType, + "description": n.desc, + "source_chunk_ids": n.sourceChunkIDs, + }) + } + return out +} diff --git a/internal/rag/advanced_rag/harness/tool_navigation_test.go b/internal/rag/advanced_rag/harness/tool_navigation_test.go new file mode 100644 index 00000000000..197fe23f9c7 --- /dev/null +++ b/internal/rag/advanced_rag/harness/tool_navigation_test.go @@ -0,0 +1,944 @@ +// +// 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. +// + +package harness + +import ( + "context" + "errors" + "strings" + "testing" +) + +// --------------------------------------------------------------------------- +// Compiled-structure rendering / normalization +// --------------------------------------------------------------------------- + +func TestNormalizeKind(t *testing.T) { + cases := []struct { + row map[string]interface{} + want string + }{ + {map[string]interface{}{"compile_kwd": "raptor_graph"}, "raptor"}, + {map[string]interface{}{"compilation_template_kind_kwd": "page_index"}, "timeline"}, + {map[string]interface{}{"compilation_template_kind_kwd": "knowledge_graph"}, "timeline"}, + {map[string]interface{}{"compilation_template_kind_kwd": "mindmap"}, "mindmap"}, + {map[string]interface{}{"compile_kwd": "tree"}, "tree"}, + } + for _, c := range cases { + if got := normalizeKind(c.row); got != c.want { + t.Errorf("normalizeKind(%v) = %q, want %q", c.row, got, c.want) + } + } +} + +func containsAll(s string, subs ...string) bool { + for _, sub := range subs { + if !strings.Contains(s, sub) { + return false + } + } + return true +} + +// --------------------------------------------------------------------------- +// navigate_tree routing +// --------------------------------------------------------------------------- + +type stubRouter struct { + table [][2]string + nilResult bool + emptyResult bool + err error + gotQuery string + gotDocScope []string + gotTopK int +} + +func (s *stubRouter) Route(_ context.Context, _, _, query string, docScope []string, topK int) ([][2]string, error) { + s.gotQuery = query + s.gotDocScope = docScope + s.gotTopK = topK + if s.err != nil { + return nil, s.err + } + if s.nilResult { + return nil, nil + } + if s.emptyResult { + return [][2]string{}, nil + } + return s.table, nil +} + +func TestNavigateTreeRoutesAndRendersXML(t *testing.T) { + router := &stubRouter{table: [][2]string{ + {"doc-c", "Culdcept history and design"}, + {"doc-a", "OmiyaSoft company profile"}, + {"doc-b", ""}, + }} + got := NavigateTree(context.Background(), router, NavTreeInput{ + Query: "Who created Culdcept?", + Keywords: "Culdcept, creator", + KbIDs: []string{"kb1"}, + }) + if got.EmptyReason != "" { + t.Fatalf("empty_reason = %q, want a successful route", got.EmptyReason) + } + if len(got.DocIDs) != 3 { + t.Fatalf("doc_ids = %v, want 3", got.DocIDs) + } + if len(got.RoutedDocs) != 3 { + t.Fatalf("routed_docs = %v, want 3", got.RoutedDocs) + } + if got.RoutedDocs[0][1] != "Culdcept history and design" { + t.Errorf("routed summary = %q", got.RoutedDocs[0][1]) + } + if !strings.Contains(router.gotQuery, "Culdcept, creator") { + t.Errorf("routing query = %q, want topic + keywords", router.gotQuery) + } + if !strings.Contains(got.Text, `count="3"`) { + t.Errorf("XML missing the count: %s", got.Text) + } + if !strings.Contains(got.Text, `doc_id="doc-c"`) { + t.Errorf("XML missing doc ids: %s", got.Text) + } + if !strings.Contains(got.Text, "Culdcept history and design") { + t.Errorf("XML missing the summary: %s", got.Text) + } + if !strings.Contains(got.Text, `doc_id="doc-b"/>`) { + t.Errorf("summary-less doc must be self-closing: %s", got.Text) + } + if !strings.HasSuffix(strings.TrimSpace(got.Text), "") { + t.Errorf("XML not closed: %s", got.Text) + } +} + +func TestNavigateTreeDistinguishesNoStructureFromNoDoc(t *testing.T) { + got := NavigateTree(context.Background(), &stubRouter{nilResult: true}, NavTreeInput{ + Query: "q", KbIDs: []string{"kb1"}, + }) + if got.EmptyReason != ReasonNoStructure { + t.Errorf("no tree: reason = %q, want %q", got.EmptyReason, ReasonNoStructure) + } + if got.HasStructure() { + t.Error("no tree must report HasStructure=false") + } + got = NavigateTree(context.Background(), &stubRouter{emptyResult: true}, NavTreeInput{ + Query: "q", KbIDs: []string{"kb1"}, + }) + if got.EmptyReason != ReasonNoDoc { + t.Errorf("routed to nothing: reason = %q, want %q", got.EmptyReason, ReasonNoDoc) + } + if !got.HasStructure() { + t.Error("a query-level miss must still report HasStructure=true") + } +} + +func TestNavigateTreeBadArgsAndInfra(t *testing.T) { + if got := NavigateTree(context.Background(), &stubRouter{}, NavTreeInput{}); got.EmptyReason != ReasonBadArgs { + t.Errorf("no query: reason = %q, want bad_args", got.EmptyReason) + } + if got := NavigateTree(context.Background(), nil, NavTreeInput{Query: "q"}); got.EmptyReason != ReasonInfra { + t.Errorf("no router: reason = %q, want infra", got.EmptyReason) + } + got := NavigateTree(context.Background(), &stubRouter{err: errors.New("ES down")}, NavTreeInput{ + Query: "q", KbIDs: []string{"kb1"}, + }) + if got.EmptyReason != ReasonNoStructure { + t.Errorf("backend error: reason = %q, want no_structure (no dataset verdict)", got.EmptyReason) + } +} + +func TestNavigateTreeCachesBestPerDocAcrossDatasets(t *testing.T) { + router := &stubRouter{table: [][2]string{ + {"doc-a", "summary from kb1"}, + {"doc-a", "summary from kb2"}, + {"doc-b", "b"}, + }} + got := NavigateTree(context.Background(), router, NavTreeInput{ + Query: "q", KbIDs: []string{"kb1", "kb2"}, + }) + if len(got.DocIDs) != 2 { + t.Fatalf("doc_ids = %v, want 2 (deduped)", got.DocIDs) + } +} + +func TestNavigateTreeCapsAt8(t *testing.T) { + var table [][2]string + for i := 0; i < 20; i++ { + table = append(table, [2]string{string(rune('a'+i%26)) + string(rune('0'+i/26)), "s"}) + } + got := NavigateTree(context.Background(), &stubRouter{table: table}, NavTreeInput{ + Query: "q", KbIDs: []string{"kb1"}, + }) + if len(got.DocIDs) != navTreeMaxDocs { + t.Errorf("doc_ids = %d, want capped at %d", len(got.DocIDs), navTreeMaxDocs) + } +} + +func TestNavigateTreeEscapesXML(t *testing.T) { + router := &stubRouter{table: [][2]string{{"d&<>\"'1", "a < b & c"}}} + got := NavigateTree(context.Background(), router, NavTreeInput{ + Query: `who "made" & that`, KbIDs: []string{"kb1"}, + }) + if strings.Contains(got.Text, "") { + t.Errorf("query not escaped: %s", got.Text) + } + if !strings.Contains(got.Text, "<it>") { + t.Errorf("query not escaped: %s", got.Text) + } + if strings.Contains(got.Text, `doc_id="d&<>\"'1"`) { + t.Errorf("doc_id not escaped: %s", got.Text) + } +} + +// --------------------------------------------------------------------------- +// Compiled-structure parsing +// --------------------------------------------------------------------------- + +func TestParseCompiledStructureGraphBlob(t *testing.T) { + rows := []StructureRow{{ + CompileKwd: "tree", + KnowledgeGraphKwd: "graph", + Content: `{"entities": [{"name": "OmiyaSoft"}, {"name": "Culdcept"}], "relations": [{"src": "OmiyaSoft", "dst": "Culdcept"}]}`, + }} + ents, rels := ParseCompiledStructure(rows, []string{"tree"}) + if len(ents) != 2 || len(rels) != 1 { + t.Fatalf("blob: entities=%d relations=%d, want 2/1", len(ents), len(rels)) + } +} + +func TestParseCompiledStructurePerEntityRows(t *testing.T) { + rows := []StructureRow{ + {CompileKwd: "page_index", KnowledgeGraphKwd: "entity", Content: `{"name": "OmiyaSoft"}`}, + {CompileKwd: "page_index", KnowledgeGraphKwd: "entity", Content: `{"name": "Culdcept"}`}, + {CompileKwd: "page_index", KnowledgeGraphKwd: "relation", Content: `{"src": "OmiyaSoft", "dst": "Culdcept"}`}, + } + ents, rels := ParseCompiledStructure(rows, []string{"timeline"}) + if len(ents) != 2 || len(rels) != 1 { + t.Fatalf("per-row: entities=%d relations=%d, want 2/1", len(ents), len(rels)) + } +} + +func TestParseCompiledStructureKindFilterAndNormalization(t *testing.T) { + rows := []StructureRow{ + {CompileKwd: "page_index", KnowledgeGraphKwd: "entity", Content: `{"name": "A"}`}, + {CompileKwd: "knowledge_graph", KnowledgeGraphKwd: "entity", Content: `{"name": "B"}`}, + {CompileKwd: "tree", KnowledgeGraphKwd: "entity", Content: `{"name": "C"}`}, + {CompileKwd: "raptor_graph", KnowledgeGraphKwd: "graph", Content: `{"entities": [{"name": "D"}]}`}, + } + ents, _ := ParseCompiledStructure(rows, []string{"timeline"}) + if len(ents) != 2 { + t.Errorf("timeline filter = %d entities, want 2 (page_index + knowledge_graph)", len(ents)) + } + ents, _ = ParseCompiledStructure(rows, []string{"raptor"}) + if len(ents) != 1 { + t.Errorf("raptor filter = %d entities, want 1", len(ents)) + } + ents, _ = ParseCompiledStructure([]StructureRow{ + {CompileKwd: "", TemplateKind: "tree", KnowledgeGraphKwd: "entity", Content: `{"name": "E"}`}, + }, []string{"tree"}) + if len(ents) != 1 { + t.Errorf("template_kind fallback = %d, want 1", len(ents)) + } +} + +func TestParseCompiledStructureSkipsMalformed(t *testing.T) { + rows := []StructureRow{ + {CompileKwd: "tree", KnowledgeGraphKwd: "entity", Content: "not json"}, + {CompileKwd: "tree", KnowledgeGraphKwd: "entity", Content: `[1,2,3]`}, + {CompileKwd: "tree", KnowledgeGraphKwd: "unknown_shape", Content: `{"name":"X"}`}, + {CompileKwd: "tree", KnowledgeGraphKwd: "entity", Content: `{"name": "ok"}`}, + } + ents, _ := ParseCompiledStructure(rows, []string{"tree"}) + if len(ents) != 1 { + t.Errorf("entities = %d, want 1 (malformed rows skipped)", len(ents)) + } +} + +func TestParseCompiledStructureEmptyKindsMatchesAll(t *testing.T) { + rows := []StructureRow{ + {CompileKwd: "tree", KnowledgeGraphKwd: "entity", Content: `{"name": "A"}`}, + {CompileKwd: "other", KnowledgeGraphKwd: "entity", Content: `{"name": "B"}`}, + } + ents, _ := ParseCompiledStructure(rows, nil) + if len(ents) != 2 { + t.Errorf("no filter = %d entities, want 2", len(ents)) + } +} + +// --------------------------------------------------------------------------- +// Knowledge-graph exploration +// --------------------------------------------------------------------------- + +// TestExploreGraphShortCircuitsOnEmptyInput verifies the documented contract: +// no query text or no bound datasets yields an empty ExploreResult (no engine +// call). The engine-backed happy path needs a live Infinity backend and is not +// exercised in the unit tier. +func TestExploreGraphShortCircuitsOnEmptyInput(t *testing.T) { + // No query text. + if res, err := ExploreGraph(context.Background(), SearchDeps{}, "t1", []string{"kb1"}, "", "", nil); err != nil || res.Answer != "" || len(res.Chunks) != 0 { + t.Errorf("empty query -> (%+v, %v), want empty result", res, err) + } + // No bound datasets. + if res, err := ExploreGraph(context.Background(), SearchDeps{}, "t1", nil, "OmiyaSoft", "", nil); err != nil || res.Answer != "" || len(res.Chunks) != 0 { + t.Errorf("no datasets -> (%+v, %v), want empty result", res, err) + } +} + +// TestExploreGraphUnconfiguredEngineErrors verifies a missing engine is +// surfaced rather than silently returning empty. +func TestExploreGraphUnconfiguredEngineErrors(t *testing.T) { + if _, err := ExploreGraph(context.Background(), SearchDeps{}, "t1", []string{"kb1"}, "OmiyaSoft", "", nil); err == nil { + t.Error("expected an error when the engine is not configured") + } +} + +// stubTenantResolver is a DocTenantResolver test double that assigns a fixed +// (kb, tenant) to every document id it is asked about. +type stubTenantResolver struct { + owner DocTenant +} + +func (s stubTenantResolver) ResolveDocTenants(ctx context.Context, docIDs []string) (map[string]DocTenant, error) { + out := make(map[string]DocTenant, len(docIDs)) + for _, d := range docIDs { + out[d] = s.owner + } + return out, nil +} + +// TestResolveKGScopeGroupsByOwner mirrors Python _kg_scopes: documents are +// grouped by their real owning (kb, tenant) — which may be a KB outside the +// caller's datasetIDs — rather than every bound dataset being searched with +// the whole DocScope. +func TestResolveKGScopeGroupsByOwner(t *testing.T) { + // No DocScope: one whole-dataset group per bound dataset. + got := resolveKGScope(SearchDeps{TenantID: "t1"}, nil, []string{"kb1", "kb2"}) + if len(got) != 2 { + t.Fatalf("no-docScope scopes = %d, want 2", len(got)) + } + for _, s := range got { + if len(s.Docs) != 0 { + t.Errorf("scope %s has Docs=%v, want nil (whole-dataset)", s.KBID, s.Docs) + } + } + + // DocScope + resolver that maps every doc to a NEW kb outside datasetIDs. + got = resolveKGScope(SearchDeps{ + TenantID: "t1", + DocTenantResolver: stubTenantResolver{owner: DocTenant{KBID: "otherKB", TenantID: "t9"}}, + }, []string{"d1", "d2"}, []string{"kb1"}) + if len(got) != 1 { + t.Fatalf("resolver scopes = %d, want 1 (new kb from resolver)", len(got)) + } + if got[0].KBID != "otherKB" || got[0].TenantID != "t9" { + t.Errorf("scope = %+v, want KBID=otherKB TenantID=t9", got[0]) + } + if len(got[0].Docs) != 2 { + t.Errorf("scope Docs = %v, want [d1 d2]", got[0].Docs) + } + + // DocScope but NO resolver: fall back to old behaviour (each bound dataset + // searched with the whole DocScope). + got = resolveKGScope(SearchDeps{TenantID: "t1"}, []string{"d1"}, []string{"kb1", "kb2"}) + if len(got) != 2 { + t.Fatalf("no-resolver scopes = %d, want 2", len(got)) + } + for _, s := range got { + if len(s.Docs) != 1 || s.Docs[0] != "d1" { + t.Errorf("scope %s Docs=%v, want [d1]", s.KBID, s.Docs) + } + } +} + +// TestResolveKGScopeAppliesSessionDocScopeCeiling verifies Python's +// scoped_doc_ids ceiling (exploration.py:_kg_scopes): the session doc_scope restricts +// whatever scope the caller passed before ownership resolution. +func TestResolveKGScopeAppliesSessionDocScopeCeiling(t *testing.T) { + got := resolveKGScope(SearchDeps{ + TenantID: "t1", + DocScope: []string{"d1", "d2"}, // session ceiling + DocTenantResolver: stubTenantResolver{owner: DocTenant{KBID: "kb1", TenantID: "t1"}}, + }, []string{"d1", "drop", "d2"}, []string{"kb1"}) + if len(got) != 1 || len(got[0].Docs) != 2 { + t.Fatalf("after ceiling scopes = %+v, want 1 scope with [d1 d2]", got) + } + if got[0].Docs[0] != "d1" || got[0].Docs[1] != "d2" { + t.Errorf("docs = %v, want [d1 d2] (drop is outside the session scope)", got[0].Docs) + } +} + +// TestResolveKGScopeNonNilEmptyExpandsNothing pins the resolveDocScope "match +// nothing" signal: a non-nil empty scope must yield no search groups at all +// (not a whole-dataset scan). +func TestResolveKGScopeNonNilEmptyExpandsNothing(t *testing.T) { + if got := resolveKGScope(SearchDeps{TenantID: "t1"}, []string{}, []string{"kb1", "kb2"}); len(got) != 0 { + t.Fatalf("scopes = %+v, want none for an explicit empty (match nothing) scope", got) + } +} + +// --------------------------------------------------------------------------- +// Knowledge-graph row parsing +// --------------------------------------------------------------------------- + +func TestKgParseEntity_NameFallbacks(t *testing.T) { + // name wins. + if e, ok := kgParseEntity(map[string]interface{}{"content_with_weight": `{"name":"OmiyaSoft"}`}); !ok || e.Name != "OmiyaSoft" { + t.Fatalf("name parse = %+v ok=%v", e, ok) + } + // term fallback. + if e, ok := kgParseEntity(map[string]interface{}{"content_with_weight": `{"term":"Culdcept"}`}); !ok || e.Name != "Culdcept" { + t.Fatalf("term fallback = %+v ok=%v", e, ok) + } + // title fallback. + if e, ok := kgParseEntity(map[string]interface{}{"content_with_weight": `{"title":"Rocket"}`}); !ok || e.Name != "Rocket" { + t.Fatalf("title fallback = %+v ok=%v", e, ok) + } + // aliases parsed + doc_id carried. + row := map[string]interface{}{ + "content_with_weight": `{"name":"OmiyaSoft","type":"company","description":"dev","aliases":["Omiya","OS"]}`, + "doc_id": "d1", + "source_chunk_ids": []interface{}{"c1", "c2"}, + } + e, ok := kgParseEntity(row) + if !ok || e.Name != "OmiyaSoft" || e.Type != "company" || e.DocID != "d1" { + t.Fatalf("entity = %+v ok=%v", e, ok) + } + if len(e.Aliases) != 2 || e.Aliases[0] != "Omiya" { + t.Errorf("aliases = %v, want [Omiya OS]", e.Aliases) + } + if len(e.SourceChunkIDs) != 2 { + t.Errorf("source_chunk_ids = %v, want [c1 c2]", e.SourceChunkIDs) + } +} + +func TestKgParseEntityRejectsEmptyName(t *testing.T) { + cases := []string{ + `{"type":"x"}`, // no name + `{"name":""}`, // empty name + `{"name":null}`, // null name + `not json`, // unparsable + `[1,2,3]`, // not an object + } + for _, c := range cases { + if _, ok := kgParseEntity(map[string]interface{}{"content_with_weight": c}); ok { + t.Errorf("content %q should not parse to an entity", c) + } + } +} + +func TestKgParseRelationEndpointsRequired(t *testing.T) { + // Missing from endpoint. + if _, ok := kgParseRelation(map[string]interface{}{"to_entity_kwd": "B"}); ok { + t.Error("relation without from endpoint must be rejected") + } + // Missing to endpoint. + if _, ok := kgParseRelation(map[string]interface{}{"from_entity_kwd": "A"}); ok { + t.Error("relation without to endpoint must be rejected") + } + // Valid: type from content payload takes precedence over default. + row := map[string]interface{}{ + "from_entity_kwd": "A", + "to_entity_kwd": "B", + "content_with_weight": `{"type":"founded"}`, + "doc_id": "d1", + } + r, ok := kgParseRelation(row) + if !ok || r.From != "A" || r.To != "B" || r.Type != "founded" || r.DocID != "d1" { + t.Fatalf("relation = %+v ok=%v", r, ok) + } + // Default type when payload has neither type nor relation. + r2, ok := kgParseRelation(map[string]interface{}{ + "from_entity_kwd": "A", "to_entity_kwd": "B", + "content_with_weight": `{}`, + }) + if !ok || r2.Type != "related" { + t.Errorf("default relation type = %q, want related", r2.Type) + } +} + +// --------------------------------------------------------------------------- +// endpoint terms (original + lowercased, deduped) +// --------------------------------------------------------------------------- + +func TestEndpointTerms(t *testing.T) { + got := endpointTerms([]string{"OmiyaSoft", "omiya", "", "Culdcept"}) + want := map[string]bool{ + "OmiyaSoft": true, "omiyasoft": true, "omiya": true, "Culdcept": true, "culdcept": true, + } + if len(got) != len(want) { + t.Fatalf("endpointTerms = %v, want %v", got, want) + } + for _, g := range got { + if !want[g] { + t.Errorf("unexpected term %q", g) + } + } +} + +// --------------------------------------------------------------------------- +// Evidence collection: relevant entities + relations grouped by doc +// --------------------------------------------------------------------------- + +func TestCollectEvidenceIDsByDocAndAlias(t *testing.T) { + entities := []kgEntity{ + {Name: "OmiyaSoft", Aliases: []string{"Omiya"}, DocID: "d1", SourceChunkIDs: []string{"c1", "c2"}}, + {Name: "Culdcept", DocID: "d2", SourceChunkIDs: []string{"c3"}}, + } + relations := []kgRelation{ + {From: "OmiyaSoft", To: "Culdcept", DocID: "d1", SourceChunkIDs: []string{"c4"}}, + } + // Relevant set includes an alias ("Omiya") and the relation target ("Culdcept"). + byDoc := collectEvidenceIDs(entities, relations, []string{"Omiya", "Culdcept"}) + // Doc order is FIRST-SEEN — Python's dict insertion order (d1 before d2). + if len(byDoc) != 2 || byDoc[0].DocID != "d1" || byDoc[1].DocID != "d2" { + t.Fatalf("doc order = %v, want [d1 d2]", byDoc) + } + if got := byDoc[0].IDs; len(got) != 3 || got[0] != "c1" || got[1] != "c2" || got[2] != "c4" { + t.Errorf("d1 chunks = %v, want [c1 c2 c4]", got) + } + if got := byDoc[1].IDs; len(got) != 1 || got[0] != "c3" { + t.Errorf("d2 chunks = %v, want [c3]", got) + } + // A non-relevant entity must contribute nothing. + byDoc = collectEvidenceIDs(entities, relations, []string{"nobody"}) + if len(byDoc) != 0 { + t.Errorf("non-relevant selection = %v, want empty", byDoc) + } +} + +func TestCollectEvidenceIDsDeduplicatesChunks(t *testing.T) { + entities := []kgEntity{ + {Name: "A", DocID: "d1", SourceChunkIDs: []string{"c1", "c1"}}, + } + rel := []kgRelation{ + {From: "A", To: "B", DocID: "d1", SourceChunkIDs: []string{"c1"}}, + } + byDoc := collectEvidenceIDs(entities, rel, []string{"A", "B"}) + if len(byDoc) != 1 || byDoc[0].DocID != "d1" { + t.Fatalf("byDoc = %v, want a single d1 group", byDoc) + } + seen := map[string]int{} + for _, c := range byDoc[0].IDs { + seen[c]++ + } + if seen["c1"] != 1 { + t.Errorf("chunk c1 counted %d times, want 1 (deduped)", seen["c1"]) + } +} + +// --------------------------------------------------------------------------- +// mention_count re-ranking (the dense-seed re-sort) +// --------------------------------------------------------------------------- + +func TestMentionCountTypeCoercion(t *testing.T) { + cases := []struct { + in interface{} + want int + }{ + {int(5), 5}, + {int64(7), 7}, + {float64(9), 9}, + {float32(3), 3}, + {nil, 0}, + {"x", 0}, + } + for _, c := range cases { + if got := mentionCount(map[string]interface{}{"mention_count_int": c.in}); got != c.want { + t.Errorf("mentionCount(%T(%v)) = %d, want %d", c.in, c.in, got, c.want) + } + } +} + +func TestTopMentionCountSortsAndCaps(t *testing.T) { + rows := []map[string]interface{}{ + {"mention_count_int": 1, "name": "a"}, + {"mention_count_int": 10, "name": "b"}, + {"mention_count_int": 5, "name": "c"}, + } + got := topMentionCount(rows, 2) + if len(got) != 2 || mentionCount(got[0]) != 10 || mentionCount(got[1]) != 5 { + t.Fatalf("topMentionCount = %v, want [10 5]", got) + } +} + +// --------------------------------------------------------------------------- +// String-field helpers +// --------------------------------------------------------------------------- + +func TestStrSliceField(t *testing.T) { + if got := strSliceField([]string{"a", "b"}); len(got) != 2 { + t.Errorf("[]string path lost elements: %v", got) + } + if got := strSliceField([]interface{}{"a", 2, "b"}); len(got) != 2 { + t.Errorf("[]interface{} path must skip non-strings: %v", got) + } + if got := strSliceField(42); got != nil { + t.Errorf("scalar path must yield nil, got %v", got) + } +} + +func TestStrOr(t *testing.T) { + if strOr("x", "def") != "x" { + t.Error("non-empty value must win") + } + if strOr("", "def") != "def" { + t.Error("empty value must fall back") + } + if strOr(nil, "def") != "def" { + t.Error("non-string must fall back") + } +} + +// TestBuildTocTreeHierarchyFromRelations guards the navigate_structure relations +// wiring: when relations are loaded (Python passes them into +// _render_toc_drilldown / _build_toc_tree) the tree must expose the parent→child +// hierarchy and a single root, instead of collapsing to isolated roots the way +// an empty/nil relation list does. Mirrors Python _build_toc_tree. +func TestBuildTocTreeHierarchyFromRelations(t *testing.T) { + nodes := []structureNode{ + {name: "root"}, + {name: "A"}, + {name: "A1"}, + {name: "A2"}, + } + rels := []structureRel{ + {from: "root", to: "A"}, + {from: "A", to: "A1"}, + {from: "A", to: "A2"}, + } + byName, children, parents, roots := buildTocTree(nodes, rels) + if len(byName) != 4 { + t.Fatalf("byName = %d, want 4", len(byName)) + } + if len(roots) != 1 || roots[0] != "root" { + t.Fatalf("roots = %v, want single root \"root\"", roots) + } + if parents["A"] != "root" || parents["A1"] != "A" || parents["A2"] != "A" { + t.Fatalf("parents = %v, want A->root and A1/A2->A", parents) + } + if len(children["A"]) != 2 { + t.Fatalf("children[A] = %v, want [A1 A2]", children["A"]) + } +} + +// TestBuildTocTreeNoRelationsYieldsIsolatedRoots documents the pre-fix shape: a +// nil/empty relation list leaves every node without a parent, so each node is its +// own root and no parent→child hierarchy can be descended. +func TestBuildTocTreeNoRelationsYieldsIsolatedRoots(t *testing.T) { + nodes := []structureNode{ + {name: "root"}, + {name: "A"}, + {name: "A1"}, + } + _, _, _, roots := buildTocTree(nodes, nil) + if len(roots) != 3 { + t.Fatalf("roots without relations = %v, want all 3 isolated", roots) + } +} + +// TestStructureDocSegmentFormat locks the per-doc XML shape navigateStructures +// renders for each routed/requested document, mirroring Python's +// element (navigation.py +// _navigate_structure_impl, where doc_title is always empty). +func TestStructureDocSegmentFormat(t *testing.T) { + nodes := []structureNode{{name: "N1"}, {name: "N2"}} + rels := []structureRel{{from: "N0", to: "N1"}} + drill := structureDrillout{outline: "· N1 [chunks: c1]"} + + seg := structureDocSegment("docA", "q", "catalog", 2, nodes, rels, drill) + want := ` ` + if !strings.Contains(seg, want) { + t.Fatalf("segment missing header %q:\n%s", want, seg) + } + if !strings.Contains(seg, "\n · N1 [chunks: c1]") { + t.Fatalf("segment missing structure outline:\n%s", seg) + } + if !strings.Contains(seg, "\n ") { + t.Fatalf("segment missing close:\n%s", seg) + } +} + +// TestEmptyReasonLabel verifies the empty_reason→XML error label mapping used by +// the single- and multi-document renderers. +func TestEmptyReasonLabel(t *testing.T) { + cases := map[string]string{ + ReasonBadArgs: "query is required", + ReasonNoDoc: "no document located", + ReasonNoStructure: "no structure", + } + for in, want := range cases { + if got := emptyReasonLabel(in); got != want { + t.Errorf("emptyReasonLabel(%q) = %q, want %q", in, got, want) + } + } +} + +func TestVecsEqual(t *testing.T) { + if !vecsEqual([]float64{1, 2, 3}, []float64{1, 2, 3}) { + t.Error("identical vectors should be equal") + } + if vecsEqual([]float64{1, 2, 3}, []float64{1, 2, 4}) { + t.Error("differing vectors should not be equal") + } + if vecsEqual([]float64{1, 2}, []float64{1, 2, 3}) { + t.Error("differently-sized vectors should not be equal") + } + if vecsEqual(nil, []float64{1}) { + t.Error("empty vs non-empty should not be equal") + } +} + +func TestHasDistinctNodeVectors(t *testing.T) { + if hasDistinctNodeVectors([]structureNode{{name: "a"}, {name: "b"}}) { + t.Error("no vectors at all -> not distinct") + } + if hasDistinctNodeVectors([]structureNode{{name: "a", vec: []float64{1, 2}}}) { + t.Error("a single vector-bearing node -> not distinct") + } + // RAPTOR: every node inherits the same blob vector. + if hasDistinctNodeVectors([]structureNode{ + {name: "a", vec: []float64{1, 2}}, + {name: "b", vec: []float64{1, 2}}, + }) { + t.Error("all nodes sharing one vector -> not distinct") + } + // page_index: per-node vectors differ. + if !hasDistinctNodeVectors([]structureNode{ + {name: "a", vec: []float64{1, 2}}, + {name: "b", vec: []float64{3, 4}}, + }) { + t.Error("distinct per-node vectors -> distinct") + } + // One vector-bearing among several is treated as not-distinct (Python: <2 distinct). + if hasDistinctNodeVectors([]structureNode{ + {name: "a", vec: []float64{1, 2}}, + {name: "b"}, + }) { + t.Error("one vector-bearing among two -> not distinct") + } +} + +func TestNodesCoveringChunks(t *testing.T) { + nodes := []structureNode{ + {name: "A", sourceChunkIDs: []string{"c1", "c2"}}, + {name: "B", sourceChunkIDs: []string{"c3"}}, + {name: "C"}, + } + got := nodesCoveringChunks(nodes, []string{"c2", "c9"}) + if len(got) != 1 || got[0] != "A" { + t.Errorf("covering = %v, want [A]", got) + } + if got := nodesCoveringChunks(nodes, nil); got != nil { + t.Errorf("nil chunk list -> nil, got %v", got) + } +} + +func renderDrillNodes() ([]structureNode, []structureRel) { + nodes := []structureNode{ + {name: "Root", nodeType: "tree_node", desc: "root entity", sourceChunkIDs: []string{"r1"}}, + {name: "Leaf", nodeType: "tree_node", desc: "leaf entity", sourceChunkIDs: []string{"l1"}}, + } + rels := []structureRel{{from: "Root", to: "Leaf", relType: "contains"}} + return nodes, rels +} + +func drillLoader(ids []string) []chunkWithText { + var out []chunkWithText + for _, id := range ids { + out = append(out, chunkWithText{id: id, text: "chunk content for " + id}) + } + return out +} + +func TestRenderTocDrilloutLLMSelect(t *testing.T) { + nodes, rels := renderDrillNodes() + out := renderTocDrilldown("some query", nil, nodes, rels, drillLoader, nil, []string{"Leaf"}) + if out.selector != "llm_toc" { + t.Errorf("selector = %q, want llm_toc", out.selector) + } + if out.outline == "" { + t.Fatal("outline should be non-empty for a selected leaf") + } + // The selected leaf's parent (Root) must be pulled in as an ancestor. + if !strings.Contains(out.outline, "Root") { + t.Errorf("ancestor Root missing from outline:\n%s", out.outline) + } +} + +func TestRenderTocDrilloutChunkRetrieval(t *testing.T) { + nodes, rels := renderDrillNodes() + hits := []chunkHit{{id: "r1", score: 0.9}, {id: "l1", score: 0.7}} + out := renderTocDrilldown("q", nil, nodes, rels, drillLoader, hits, nil) + if out.selector != "chunk_retrieval" { + t.Errorf("selector = %q, want chunk_retrieval", out.selector) + } + if out.topScore != 0.9 { + t.Errorf("topScore = %v, want 0.9", out.topScore) + } + // Retrieved chunks are surfaced even when they are not a selected node's anchor. + if !strings.Contains(out.outline, "r1") || !strings.Contains(out.outline, "l1") { + t.Errorf("retrieved chunks missing from outline:\n%s", out.outline) + } +} + +func TestRenderTocDrilloutBeamFallback(t *testing.T) { + nodes, rels := renderDrillNodes() + // No selection and no hits, but a query: beam picks by keyword relevance. The + // blank query yields no terms, so it must still return a (flat) outline, not panic. + out := renderTocDrilldown("leaf", nil, nodes, rels, drillLoader, nil, nil) + if out.outline == "" { + t.Fatal("beam path produced an empty outline") + } + if out.selector != "beam" { + t.Errorf("selector = %q, want beam", out.selector) + } +} + +func TestParseCompiledStructureCarriesVec(t *testing.T) { + rows := []StructureRow{{ + CompileKwd: "tree", + KnowledgeGraphKwd: "graph", + Content: `{"entities": [{"name": "A"}, {"name": "B"}], "relations": []}`, + Vec: []float64{1, 2}, + }} + ents, _ := ParseCompiledStructure(rows, []string{"tree"}) + if len(ents) != 2 { + t.Fatalf("entities = %d, want 2", len(ents)) + } + // Both nested entities of the RAPTOR blob inherit its single vector. + for _, e := range ents { + v, _ := e["_vec"].([]float64) + if len(v) != 2 || v[0] != 1 { + t.Errorf("entity %v did not inherit the blob vector", e["name"]) + } + } +} + +func TestNavigationToolsReportEmptyWhenUncompiled(t *testing.T) { + // The Go port has no compiled navigation structures, so navigate_tree / + // navigate_structure report EMPTY/no_structure — the DATASET-level signal + // that lets the ladder fall through to `global` and (after the strikes) + // disable the tool, instead of looping on a rung that cannot succeed. + kb := &Kbinfos{} + ex := &searchExecutor{deps: SearchDeps{KB: kb}} + // No database is wired in this unit test, so defaultSeedEncoder's nil-DB + // guard returns nil and structure navigation falls back to keyword matching + // instead of panicking. + + oc, _ := ex.Execute(context.Background(), "navigate_tree", map[string]any{"query": "topic"}) + if oc.Status != StatusEmpty || oc.Reason != ReasonNoStructure { + t.Errorf("navigate_tree: got (%s,%s), want (empty,no_structure)", oc.Status, oc.Reason) + } + // A note must accompany it, so the model knows to switch tools. + if len(oc.Payload) == 0 { + t.Error("navigate_tree must return an actionable note, not an empty payload") + } + + oc, _ = ex.Execute(context.Background(), "navigate_structure", map[string]any{"doc_id": "d1", "query": "topic"}) + if oc.Status != StatusEmpty || oc.Reason != ReasonNoStructure { + t.Errorf("navigate_structure: got (%s,%s), want (empty,no_structure)", oc.Status, oc.Reason) + } +} + +func TestNavigateStructureDocRejectsForeignDocument(t *testing.T) { + // Python _load_compiled_structure: a doc_id outside the bound datasets + // yields no structure, so nothing from the other dataset is ever read. + res, _ := navigateStructures(context.Background(), "t", "q", []string{"foreign-doc"}, "catalog", nil, SearchDeps{ + KbIDs: []string{"kb"}, + DocIDVerifier: stubVerifier{known: map[string]bool{"mine": true}}, + }) + + if res.EmptyReason != ReasonNoStructure { + t.Fatalf("EmptyReason = %q, want %q", res.EmptyReason, ReasonNoStructure) + } + if len(res.DocIDs) != 0 { + t.Fatalf("DocIDs = %v, want none", res.DocIDs) + } +} + +// TestIndexNameForFallsBackToRagflowPrefix pins the index-name seam fix: Python +// reads search.index_name (navigation.py:_navigate_structure_impl); the RAGFlow default is +// "ragflow_", so an empty configured name falls back to that, while a +// tenant override is honoured verbatim. + +// TestIndexNameForFallsBackToRagflowPrefix pins the index-name seam fix: Python +// reads search.index_name (navigation.py:_navigate_structure_impl); the RAGFlow default is +// "ragflow_", so an empty configured name falls back to that, while a +// tenant override is honoured verbatim. +func TestIndexNameForFallsBackToRagflowPrefix(t *testing.T) { + if got := indexNameFor("tenantA", ""); got != "ragflow_tenantA" { + t.Errorf("empty configured = %q, want ragflow_tenantA", got) + } + if got := indexNameFor("tenantA", "custom_idx"); got != "custom_idx" { + t.Errorf("configured = %q, want custom_idx", got) + } +} + +// TestNavigateStructuresEmptyDocIDsRoutesViaRouter pins the empty-doc_id vector +// routing fix: mirroring Python _navigate_structure_impl(:1012), a direct call +// with no doc_ids routes through the NavTreeRouter first (search_dataset_layers) +// instead of immediately returning MISS. The tool path still passes non-empty +// doc_ids and must NOT consult the router. + +// TestNavigateStructuresEmptyDocIDsRoutesViaRouter pins the empty-doc_id vector +// routing fix: mirroring Python _navigate_structure_impl(:1012), a direct call +// with no doc_ids routes through the NavTreeRouter first (search_dataset_layers) +// instead of immediately returning MISS. The tool path still passes non-empty +// doc_ids and must NOT consult the router. +func TestNavigateStructuresEmptyDocIDsRoutesViaRouter(t *testing.T) { + router := &stubNavRouter{docs: [][2]string{{"d1", "summary"}}} + // Empty doc_ids + router => router consulted (it then returns ReasonNoDoc + // because no engine-backed structure surfaces in the test env, identical to + // the Python post-route empty result). + if _, _ = navigateStructures(context.Background(), "t", "q", []string{}, "catalog", router, SearchDeps{KbIDs: []string{"kb"}}); !router.called { + t.Fatal("empty docIDs should route via NavTreeRouter, but router was not called") + } + + // Non-empty doc_ids => router must NOT be consulted (no double routing). + router2 := &stubNavRouter{docs: [][2]string{{"d1", "summary"}}} + navigateStructures(context.Background(), "t", "q", []string{"foreign-doc"}, "catalog", router2, SearchDeps{ + KbIDs: []string{"kb"}, + DocIDVerifier: stubVerifier{known: map[string]bool{"mine": true}}, + }) + if router2.called { + t.Error("non-empty docIDs should not consult the router") + } +} + +// TestNavigateTreeRoutesWithinSessionDocScope pins that the nav-tree route runs +// inside the session document scope. Python's _exec_navigate_tree does not thread +// args["doc_scope"], but _navigate_tree_impl routes through _nav_search_titled, +// which ceilings with tools.scoped_doc_ids(None) — i.e. the session doc_scope +// (navigation.py:_nav_search_titled). Dropping it routed over the whole dataset. +func TestNavigateTreeRoutesWithinSessionDocScope(t *testing.T) { + router := &stubNavRouter{docs: [][2]string{{"d1", "summary"}}} + NavigateTree(context.Background(), router, NavTreeInput{ + Query: "topic", + TenantID: "t1", + KbIDs: []string{"kb1"}, + DocScope: []string{"d1", "d2"}, + }) + if len(router.scope) != 2 || router.scope[0] != "d1" || router.scope[1] != "d2" { + t.Fatalf("router doc scope = %v, want [d1 d2]", router.scope) + } +} + +// TestNavigateToolsRouteWithinSessionDocScope pins the executor end of the same +// contract: both navigation tools hand the router the SESSION scope +// (deps.DocScope), never the tool argument. diff --git a/internal/rag/advanced_rag/harness/tool_search.go b/internal/rag/advanced_rag/harness/tool_search.go new file mode 100644 index 00000000000..e0743ee8d18 --- /dev/null +++ b/internal/rag/advanced_rag/harness/tool_search.go @@ -0,0 +1,1482 @@ +// +// 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. +// + +package harness + +import ( + "context" + "encoding/json" + "fmt" + "log" + "regexp" + "sort" + "strings" + "sync" + "unicode/utf8" + + "ragflow/internal/engine" + "ragflow/internal/entity" + "ragflow/internal/service/nlp" +) + +// Search tools: the retrieval legs plus the narrowing that runs on top. +// +// Mirrors Python harness/tools/search.py::hybrid_search (with the vector / +// BM25 legs expressed as a weight on the same call, as the Python module does +// for its three entry points). + +// Retrieval defaults. Mirrors Python search.py's _DEFAULT_* constants; callers +// that supply no configuration get exactly these values. +const ( + DefaultSimilarityThreshold = 0.2 + DefaultTopN = 12 + DefaultRerankCandidatesCount = 64 + DefaultTopK = 1024 + // maxEffectiveQueryChars caps the expanded query (Python: [:400]). + maxEffectiveQueryChars = 400 + // maxQueryTerms caps the terms derived from a query (Python + // _query_to_terms: [:16]). + maxQueryTerms = 16 +) + +// Term-splitting pattern for QueryToTerms (Python _query_to_terms). +var ( + // queryMetaRe matches the regex metacharacters Python blanks out before + // splitting a query into its literal terms (search.py:_query_to_terms). The split that + // follows is on WHITE SPACE, never on \w+: Go's RE2 \w is ASCII-only, so + // tokenizing "关羽 斩杀" with it yields nothing at all and the fan-out BM25 + // leg loses the keyed terms it needs to weight the discriminating entity + // (agentic_rag_graph.py:_search_one). + queryMetaRe = regexp.MustCompile(`[.*+?^$()\[\]{}]`) + + // DefaultAgenticVectorWeight is the vector leg's weight when agentic + // retrieval runs keyword-only: zero. + // + // This mirrors Python's RAGTools.retrieve, which takes + // `using_embedding: bool = False` (agentic_rag.py:retrieve) and where no caller + // passes True, so `embd_mdl` stays None and the weight it forwards is 0.0 + // (agentic_rag.py:retrieve). The agentic loop therefore runs on keyword + // matches plus reranking; matching that is what keeps Go's recall aligned + // with Python's. SearchDeps.UsingEmbedding is the Go spelling of that flag. + DefaultAgenticVectorWeight = 0.0 + + // DefaultHybridVectorWeight is the vector leg's weight when embedding IS + // used (Python RAGTools.retrieve with using_embedding=True). Python reads it + // from `_setting(self, "vector_similarity_weight", 0.7)` (agentic_rag.py:retrieve); + // 0.7 is the configured default when a caller turns embedding on. + DefaultHybridVectorWeight = 0.7 + + // HybridSearchDefaultVectorWeight is the vector leg's weight for the + // standalone hybrid_search tool (Python search_chunks → hybrid_search). It + // defaults to _DEFAULT_HYBRID_VECTOR_WEIGHT = 0.3 — NOT 0.7 — + // because the tool reads `_setting(tools, "vector_similarity_weight", 0.3)`. + HybridSearchDefaultVectorWeight = 0.3 + + // VectorSearchDefaultSimilarityThreshold is the engine similarity floor for + // the pure-vector entry point (search.py:vector_search, 0.2). + VectorSearchDefaultSimilarityThreshold = 0.2 + // BM25SearchDefaultSimilarityThreshold is the engine similarity floor for + // bm25_search / grep_search (/395: 0.0). + BM25SearchDefaultSimilarityThreshold = 0.0 +) + +// Retriever is the retrieval backend the harness searches through. +// +// Mirrors Python's `settings.retriever.retrieval(...)`, which the harness calls +// as a module-level singleton. The Go version takes it as an interface so the +// session and the orchestrator can be tested without a search backend, and so +// the concrete adapter (the harness root package's RuntimeRetriever) stays the +// only place that knows about the runtime. +type Retriever interface { + // Retrieve runs one search and returns raw chunk maps. The chunks carry at + // least chunk_id / content / doc_id / docnm_kwd so the harness accessors + // (ChunkIDOf, ChunkTextOf, DocIDOf, ...) can read them. + Retrieve(ctx context.Context, req RetrieveRequest) ([]map[string]any, error) +} + +// DocChunkLister returns a document's chunks in reading order, which is what +// the document-level tools need (Python settings.retriever.chunk_list with +// sort_by_position=True, rag/nlp/search.py:_only_strings). +// +// Retrieval cannot express it: RetrieveRequest ranks by relevance to a query, +// while these tools want every chunk of one document, page-ordered, paged. +// Like DocIDVerifier it is injected, so this package needs no document-store +// dependency of its own. Nil means the tools that need it stay unavailable. +type DocChunkLister interface { + // DocChunks returns up to Limit chunks of DocID starting at Offset, ordered + // by reading position. A short page means the document is exhausted. + DocChunks(ctx context.Context, req DocChunksRequest) ([]map[string]any, error) +} + +// DocChunksRequest is one page of one document's chunks. +type DocChunksRequest struct { + DocID string + DatasetIDs []string + TenantID string + Offset int + Limit int +} + +// DocIDVerifier reports which of a candidate document id set are known to the +// session's datasets. Mirrors Python RAGTools._filter_known_doc_ids, whose +// lookup is deliberately left to the caller so this package stays free of a +// database dependency. +type DocIDVerifier interface { + // KnownDocIDs returns the subset of candidates that exist in the given + // datasets. An error or an unavailable backend yields an empty set, which + // the caller treats as "verification unavailable" rather than "no match". + KnownDocIDs(ctx context.Context, datasetIDs, candidates []string) (map[string]bool, error) +} + +// DocTenant is the owning (knowledge base, tenant) pair for one document, as +// returned by DocTenantResolver. Mirrors Python tools._resolve_doc_tenant, +// which yields (kb, tenant) for a document id. +type DocTenant struct { + KBID string + TenantID string +} + +// DocTenantResolver maps document ids to their owning (kb, tenant), mirroring +// Python tools._resolve_doc_tenant (exploration.py:_kg_scopes). Unlike +// DocIDVerifier, the returned KB/tenant may lie OUTSIDE the caller's +// datasetIDs, so graph_explore can group documents by their real owner and +// search knowledge bases that were not in the original search set. The lookup +// is left to the caller (this package stays database-free); an error or a nil +// resolver makes ExploreGraph fall back to the pre-existing behaviour of +// searching each bound dataset with the whole DocScope. +type DocTenantResolver interface { + ResolveDocTenants(ctx context.Context, docIDs []string) (map[string]DocTenant, error) +} + +// RetrieveRequest is one retrieval call. +// +// Weight is the vector-similarity weight: 0.3 hybrid (default), 1.0 vector-only, +// 0.0 keyword-only (BM25). This is how Python's three search entry points +// (hybrid_search / vector_search / bm25_search) differ. +type RetrieveRequest struct { + Query string + DatasetIDs []string + DocScope []string + TopN int + TopK int + RerankCandidatesCount int + SimilarityThreshold float64 + KeywordsSimilarityWeight float64 + TenantID string + // MetaDataFilter restricts retrieval to chunks whose metadata matches + // (Python tools.meta_data_filter). Nil means no filtering. + MetaDataFilter map[string]any + // RankFeature mirrors Python RAGTools.retrieve's `rank_feature` argument + // (agentic_rag.py:retrieve): question-type tags produced by + // label_question(question, self.kbs) that the retriever uses to boost + // matching chunks. The Go engine consumes it as a tag → weight map (matching + // internal/engine/types and the chat pipeline), so it is map[string]float64, + // not a bare list. Nil means no rank feature (Python passes None). + RankFeature map[string]float64 + // ExcludeCompiled excludes compiled-product rows from plain retrieval + // (Python hybrid_search passes must_not={"exists": "compile_kwd"}, + // search.py:hybrid_search). Compiled products have their own expansion step, so the + // base retrieval here should surface ordinary document chunks only. False + // matches Python RAGTools.retrieve, which does not exclude them. + ExcludeCompiled bool +} + +// intOrDef returns v when set, else fallback. +func intOrDef(v, fallback int) int { + if v > 0 { + return v + } + return fallback +} + +// floatOrDef returns v when set, else fallback. Kept separate from the pointer +// form below so both "unset" conventions stay explicit at the call site. +func floatOrDef(v, fallback float64) float64 { + if v > 0 { + return v + } + return fallback +} + +// floatPtrOrDef returns *v when configured, else fallback. A pointer is used so +// a configured 0 is honoured instead of looking like "unset". +func floatPtrOrDef(v *float64, fallback float64) float64 { + if v != nil { + return *v + } + return fallback +} + +// SearchChannel identifies which Python search entry point a call mirrors. Python +// has three genuinely different search functions rather than one with a flag; +// collapsing them let a single global UsingEmbedding switch silently disable the +// vector leg for a tool that never consulted using_embedding. +type SearchChannel int + +const ( + // ChannelGrep mirrors Python grep_search — the `retrieve`, `grep_search` + // and `grep_chunks` session tools (action_session.py:_exec_retrieve :737-741). It is + // keyword-only: grep_search has NO vector leg at all, so the weight is + // unconditionally 0 and UsingEmbedding must not be consulted. + ChannelGrep SearchChannel = iota + // ChannelHybrid mirrors the standalone hybrid_search — the `search_chunks` + // session tool (action_session.py:_exec_search_chunks, search.py:hybrid_search). Its vector + // leg is gated on `tools.embed_mdl` being set + // (`vector_weight = _setting(...) if embd_mdl else 0`), NOT on + // using_embedding; production always supplies an embed model, so it runs. + // Default weight 0.3 (search.py:_DEFAULT_HYBRID_VECTOR_WEIGHT). + ChannelHybrid + // ChannelRetrieve mirrors Python RAGTools.retrieve, + // used by the low/naive direct passes. THIS is the only function that + // honours `using_embedding: bool = False` (:600, :643), which is what + // UsingEmbedding spells. Default weight 0.7 when embedding is on. + ChannelRetrieve +) + +// resolveVectorWeight mirrors the weight each Python entry point computes. The +// gate differs per channel — that is the whole point: +// +// - ChannelGrep: always 0 (grep_search has no vector leg). +// - ChannelHybrid: 0 when no embedder is configured (Python's `if embd_mdl`), +// otherwise VectorSimilarityWeight ?? 0.3. UsingEmbedding is IRRELEVANT +// here: Python's hybrid_search has no such parameter. +// - ChannelRetrieve: 0 unless UsingEmbedding (Python's using_embedding), +// otherwise VectorSimilarityWeight ?? 0.7. +func resolveVectorWeight(deps SearchDeps, ch SearchChannel) float64 { + switch ch { + case ChannelGrep: + return 0 + case ChannelHybrid: + // Python: vector_weight = _setting(...) if embd_mdl else 0. + // HasEmbedder is the Go spelling of `tools.embed_mdl`; the runtime + // retrieval service resolves the actual model, as Python's retriever + // does from embd_mdl. + if !deps.HasEmbedder { + return 0 + } + return floatPtrOrDef(deps.VectorSimilarityWeight, HybridSearchDefaultVectorWeight) + default: + if !deps.UsingEmbedding { + return 0 + } + return floatPtrOrDef(deps.VectorSimilarityWeight, DefaultHybridVectorWeight) + } +} + +// SearchDeps are the dependencies of HybridSearch. +type SearchDeps struct { + // Backend is the retrieval service. + Backend Retriever + // KbIDs are the session's bound dataset ids (Python tools.kb_ids). + KbIDs []string + // SQLKBs are the session's structured (SQL-backed) datasets (Python + // tools.sql_kbs). Python hybrid_search merges them into the target id list + // (search.py:hybrid_search: `tools.kb_ids + [kb.id for kb in tools.sql_kbs]`), so the + // keyword/vector search spans the structured tables too. Go keeps them + // separate on SearchDeps and folds them into targetIDs in runSearch. + SQLKBs []string + // TenantID scopes the retrieval. + TenantID string + // IndexName is the search index that holds the dataset's document/structure + // rows (Python search.index_name; navigation.py:_navigate_structure_impl routes the compiled + // structure read through it). Empty falls back to "ragflow_", the + // RAGFlow default — but a tenant that overrides index_name must surface it + // here or structure/doc reads would hit the wrong index. The earlier Go port + // hardcoded "ragflow_" and ignored per-tenant overrides. + IndexName string + // DocEngine fetches parent chunks during retrieval_by_children (child + // fragments are promoted to their parent chunk). Nil falls back to + // engine.Get(). Kept here so runSearch can promote children for the + // hybrid/retrieve entry points without the Backend guessing which caller + // wants promotion. + DocEngine engine.DocEngine + // KB receives the raw chunks into the lossless memory store BEFORE + // narrowing, and carries the per-request search cache. + KB *Kbinfos + // Expand runs the compiled-structure expansion when UseCompiled is set. + // Nil disables compiled expansion. + Expand CompiledExpander + // NavRouter descends the dataset's compiled navigation tree for the + // navigate_tree tool. Nil falls back to nav.NewNavServiceRouter() (the + // internal/service/nav singleton). + NavRouter NavTreeRouter + // Model is the request-scoped chat model (Python tools.chat_mdl). It drives + // the calculate tool's expression-writing call and the graph_explore + // structure verdict (AskStructure). Required for `calculate`; nil makes the + // model-backed tools report a miss. + Model SessionModel + // Logger is optional; nil uses the default logger. + Logger *log.Logger + // DocIDVerifier resolves which of the caller-supplied document ids actually + // belong to the session's datasets (Python + // RAGTools._filter_known_doc_ids). Nil means "no verification available": + // the doc scope is passed through to the retriever unchanged, which is the + // pre-existing behaviour. + // + // It is injected rather than queried here because resolving document + // ownership is a database lookup this package deliberately does not depend + // on; the caller (internal/rag/advanced_rag) supplies the implementation. + DocIDVerifier DocIDVerifier + // DocChunks pages through one document's chunks for the document-level + // tools (fetch_full_document / summarize_document). Nil leaves both + // unavailable. + DocChunks DocChunkLister + // Embedder is the external embedding handle used by graph/structure seed + // encoding (Python tools.embed_mdl). Nil falls back to this package's + // internal tenant-default resolver, which needs a database and therefore + // stays self-contained for callers that cannot or do not want to supply one. + Embedder nlp.NavEmbedder + // Retrieval tuning (Python RAGTools.retrieve: _setting(self, "top_n"), + // similarity_threshold, vector_similarity_weight, rerank_candidates_count, + // top_k). Zero falls back to this package's Default* constants. + TopN int + SimilarityThreshold float64 + // VectorSimilarityWeight is a pointer so an explicit 0 (keyword-only, the + // agentic default) is distinguishable from "not configured", which falls + // back to DefaultAgenticVectorWeight. + VectorSimilarityWeight *float64 + // UsingEmbedding is the Go spelling of Python RAGTools.retrieve's + // `using_embedding: bool = False` (agentic_rag.py:retrieve). When false (the + // agentic default), the vector leg is disabled and retrieval is keyword-only + // (vector weight 0) — exactly Python's `embd_mdl = None; vector_weight = 0`. + // When true, the embedder is engaged and the vector weight is applied: + // VectorSimilarityWeight if set, else DefaultHybridVectorWeight (0.7, Python + // `_setting(self, "vector_similarity_weight", 0.7)`). Unlike Python, the + // query embedder is supplied by the runtime retrieval service, so Go carries + // the flag rather than an embd_mdl handle on the retrieve call itself. + // + // SCOPE: this flag governs ChannelRetrieve ONLY. Python's using_embedding + // lives on RAGTools.retrieve and nowhere else — hybrid_search (search_chunks) + // has no such parameter, so gating it here is what silently disabled the + // semantic leg. + UsingEmbedding bool + // HasEmbedder is the Go spelling of Python `tools.embed_mdl` being set — + // the gate hybrid_search applies to its vector leg + // (search.py:_setting: `vector_weight = _setting(...) if embd_mdl else 0`). + // Production always supplies one (dialog_service.py:rag_agent embed_mdl=embd_mdl), + // so the semantic leg of search_chunks runs. False keeps callers that have no + // embedding model on keyword-only retrieval, as Python does. + HasEmbedder bool + RerankCandidatesCount int + TopK int + // MetaDataFilter restricts retrieval to matching chunk metadata (Python + // tools.meta_data_filter). Nil means no filtering. + MetaDataFilter map[string]any + // DocScope is the session-wide document restriction (Python + // RAGTools.doc_scope). It is a CEILING applied by scopedDocIDs before any + // search: an explicit caller scope is intersected with it. Empty means + // "search everything". + DocScope []string + // DocTenantResolver maps document ids to their owning (kb, tenant), + // mirroring Python tools._resolve_doc_tenant. Unlike DocIDVerifier (which + // only answers "belongs to the bound datasets?"), this may return KB/tenant + // pairs OUTSIDE the caller's datasetIDs, so graph_explore can search + // documents that belong to other knowledge bases. Nil falls back to the + // pre-existing behaviour: each bound dataset is searched with the whole + // DocScope (no per-document re-grouping). + DocTenantResolver DocTenantResolver + // DoRefer mirrors Python RAGTools.do_refer: when true, summarize_document + // prefixes the citation rules so the model cites the blocks it summarises. + DoRefer bool + // CiteRules is the optional user-defined citation template. Empty falls back + // to the embedded citation_prompt.md (mirrors Python user_defined_prompts). + // summarize_document passes it to the citation header verbatim. + CiteRules string + // WebSearch is the optional open-web provider for the `web_search` tool. Nil + // HIDES the tool from the session surface — Toolset.HasWebSearch is set from + // mode.HasTool("web_search") && WebSearch != nil, mirroring Python's + // provider gate (action_session.py:_disable_tool). Should a call reach the handler + // anyway, it reports StatusError/ReasonInfra with a do-not-retry note, never a + // query-level MISS (WebSearchTool:826). + WebSearch WebSearcher + // WikiRetriever is the optional provider for the `wiki_query` tool. The tool is + // advertised in NO mode: its spec was dropped from ToolMap to match Python, + // which never registers wiki_query either (see action_session.go). The + // handler is kept as an unplugged seam and reports a clean MISS + // (StatusMiss/ReasonNoDoc) when no retriever is wired. + WikiRetriever WikiRetriever + // KBs mirrors Python RAGTools' self.kbs — the resolved + // Knowledgebase objects (carrying parser_config / tenant_id) the agentic + // tools run over. The rank feature is derived from these, exactly as + // Python's retrieve calls label_question(question, self.kbs). Projected + // from RAGTools.KBs when the search deps are built. + KBs []*entity.Knowledgebase + // Tagger mirrors Python RAGTools.retrieve's + // `rank_feature=label_question(question, self.kbs)` (agentic_rag.py:retrieve): it + // classifies the query into question-type tags the retriever boosts on. Nil + // means no tag boost (Python's label_question returning None). The Go + // implementation lives in internal/service (MetadataService.LabelQuestion), + // matching Python's rag.app.tag.label_question which queries the tag service. + Tagger QuestionLabeler +} + +// QuestionLabeler mirrors Python rag.app.tag.label_question(question, kbs) +// (agentic_rag.py:retrieve → tag.py). Given the query and the KB objects (which +// carry parser_config.tag_kb_ids), it returns a map of question-type tag → +// weight the retriever uses to rank results. The production implementation is +// internal/service.MetadataService.LabelQuestion; tests supply a stub. +type QuestionLabeler interface { + LabelQuestion(ctx context.Context, question string, kbs []*entity.Knowledgebase) map[string]float64 +} + +// CompiledExpander enriches a search result with the dataset's compiled +// structure (page index / tree / knowledge graph / wiki synthesis pages). +// +// Mirrors Python tools/compiled_expansion.py::_expand_with_compiled, which +// hybrid_search calls when use_compiled is set. It is a seam rather than a +// direct call so the search leg stays independent of the compiled-structure +// machinery (and testable without a knowledge graph). +type CompiledExpander interface { + Expand(ctx context.Context, kb *Kbinfos, query, keywords string, docScope []string) error +} + +// QueryToTerms mirrors Python _query_to_terms: derive the +// literal terms a query carries. The alternation's segments are split out (capped +// at maxQueryTerms) so the regex locate and the term-based context window fire on +// the same broad set of names; a plain query simply splits on white space. Terms +// shorter than two characters and duplicates are dropped. +// +// Case is PRESERVED, as in Python (it never lowercases): the downstream consumers +// are case-insensitive — NarrowByTerms compiles with "(?i)" +// (grep_sed_narrow.go, Python re.IGNORECASE) and the BM25 keyword leg is +// tokenized server-side — so lowercasing here would only change the text handed +// to them. +func QueryToTerms(query string) []string { + q := strings.TrimSpace(query) + if q == "" { + return nil + } + // Strip the regex decorations Python removes (search.py:_query_to_terms): an inline + // flag prefix plus \b and (?i) markers. + q = strings.TrimPrefix(q, "(?i)") + q = strings.ReplaceAll(q, `\b`, "") + q = strings.ReplaceAll(q, "(?i)", "") + + var ( + out []string + seen = make(map[string]bool, len(q)/2) + ) + for _, part := range strings.Split(q, "|") { + part = strings.TrimSpace(queryMetaRe.ReplaceAllString(part, " ")) + if part == "" { + continue + } + for _, tok := range strings.Fields(part) { + if utf8.RuneCountInString(tok) < 2 || seen[tok] { + continue + } + seen[tok] = true + out = append(out, tok) + } + if len(out) >= maxQueryTerms { + break + } + } + if len(out) > maxQueryTerms { + out = out[:maxQueryTerms] + } + return out +} + +// FanoutKeyedTerms mirrors Python's fan-out term filter +// (agentic_rag_graph.py:_fanout_search): the subset of terms worth keying a BM25 round on. +// Short stopwords and bare numbers are dropped, but a long number (a year, a +// specimen ID) is discriminative and survives. +func FanoutKeyedTerms(terms []string) []string { + var out []string + for _, t := range terms { + digits := isAllDigits(t) + // Python compares t.lower() against the (lowercase) stopword set while the + // terms themselves keep their case (agentic_rag_graph.py:_search_one), so "The" + // must be dropped like "the". + if (utf8.RuneCountInString(t) >= 3 && !IsStopword(strings.ToLower(t)) && !digits) || + (utf8.RuneCountInString(t) >= 4 && digits) { + out = append(out, t) + } + } + return out +} + +// searchOpts carries the per-entry-point differences that in Python live in +// separate functions (hybrid_search / vector_search / bm25_search / grep_search / +// RAGTools.retrieve). In Go each entry point is its own function that builds a +// searchOpts and delegates to runSearch, so the vector-weight gate, similarity +// threshold and compiled-row exclusion are chosen by the CALLER, never by a +// single shared "channel flag" that a global switch could silently corrupt. +type searchOpts struct { + // weight is the VECTOR similarity weight (Python vector_similarity_weight). + weight float64 + // threshold is the engine similarity floor. + threshold float64 + // excludeCompiled mirrors Python hybrid_search's must_not={"exists":"compile_kwd"}. + excludeCompiled bool + // promoteChildren mirrors Python calling settings.retriever.retrieval_by_children + // after search (search.py:_normalize): child fragments are lifted to their + // parent chunk. In Python EVERY entry point does this — hybrid_search (L106), + // vector_search (L239) and bm25_search (L276) all route through _normalize, and + // grep_search builds on bm25_search. So ALL entry points set promoteChildren: + // true (including vector/bm25/grep); only a future non-promoting path would + // leave it false. An empty tenant_id still skips promotion, mirroring Python + // _normalize. + promoteChildren bool + // logLabel / logVerb / logKeywords describe the entry point's own + // "searching" line, Python-exact: + // + // hybrid → [Hybrid search] Searching the knowledge base for "q" (keywords: k) (search.py:hybrid_search) + // vector → [Vector search] Searching by meaning for "q" (keywords: k) (:215) + // bm25 → [BM25 search] Searching by keyword for "q" (keywords: k) (:252) + // grep → [Grep search] Keyword-first locate for "q" (NO keywords) (:418) + // + // Python prints the "(keywords: …)" suffix unconditionally on the three legs + // that carry it; Go prints it only when non-empty (a keyword-less leg is a + // deliberate state — see the fan-out's narrow bypass — + // agentic_rag_graph.py:_search_one — and search_chunks takes no keywords at all, + // action_session.py:execute_tool — so a bare "(keywords: )" reads like a dropped + // argument). logKeywords also keeps grep from growing a suffix Python never + // prints on that leg. + logLabel string + logVerb string + logKeywords bool + // logExtra enables the dedup / compiled-expansion / progress lines. Python + // emits those ONLY inside hybrid_search (:140 / :192 / :203); vector_search + // and bm25_search log nothing but their searching line (plus a debug line Go + // has no equivalent for), and grep_search has its own two lines instead. + logExtra bool + // cache enables the per-request search cache (SearchCacheLoad/Store). Python + // keeps that cache on `tools.search_cache` and touches it ONLY inside + // hybrid_search (:136-141 read, :207 write); vector_search / bm25_search / + // grep_search / RAGTools.retrieve never consult it. Go's cache lives on the + // shared deps.KB, so without this gate a keyword-only leg could be served a + // hybrid result (different vector weight, threshold and compiled policy) + // and vice versa — Go's "enhanced" typing did not make it hybrid-scoped. + cache bool + // narrowLabel tags the narrowing line. Python is NOT self-consistent here: + // hybrid_search passes the snake_case "hybrid_search", while + // vector_search / bm25_search pass their display labels "Vector search" + // (:248) / "BM25 search" (:288). Both forms are reproduced verbatim. + narrowLabel string +} + +// searchLogLine renders a per-leg "searching" line (search.py:hybrid_search/215/252/418): +// both the bracket label and the verb vary by entry point. The keywords suffix +// is appended by the caller, because Python prints it on hybrid/vector/bm25 +// only — grep_search's locate line never carries one. +func searchLogLine(label, verb, question string) string { + return fmt.Sprintf("[%s] %s %q", label, verb, question) +} + +// searchLogger returns the run's logger, falling back to the package logger. +func searchLogger(deps SearchDeps) *log.Logger { + if deps.Logger != nil { + return deps.Logger + } + return _LOG +} + +// runSearch is the shared body of every search entry point. It is deliberately +// dumb about WHICH Python function it mirrors: that is encoded by opts, supplied +// by the calling entry-point function. +func runSearch(ctx context.Context, deps SearchDeps, p SearchParams, opts searchOpts) ([]map[string]any, []map[string]any) { + logger := searchLogger(deps) + // Python retrieve:614-646 — an explicit argument wins, then the caller's + // configuration, then this package's own defaults. + topN := p.TopN + if topN <= 0 { + topN = deps.TopN + } + if topN <= 0 { + topN = DefaultTopN + } + // Python hybrid_search:117 folds the structured (SQL) datasets into the + // target id list: `kb_ids or tools.kb_ids + [kb.id for kb in tools.sql_kbs]`. + // The explicit argument still wins; otherwise the session's kb_ids and + // sql_kbs are merged so the vector/keyword search spans the structured tables. + targetIDs := p.KbIDs + if len(targetIDs) == 0 { + // Python hybrid_search:117 folds sql_kbs into the id list via + // `dict.fromkeys(kb_ids + [kb.id for kb in sql_kbs])` — dict.fromkeys + // de-duplicates. Mirror that here so a KB present in both KbIDs and + // SQLKBs is not searched twice (and likewise dedup KbIDs themselves). + merged := append(append([]string{}, deps.KbIDs...), deps.SQLKBs...) + seen := make(map[string]struct{}, len(merged)) + targetIDs = targetIDs[:0] + for _, id := range merged { + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + targetIDs = append(targetIDs, id) + } + } + if len(targetIDs) == 0 { + return nil, nil + } + if deps.Backend == nil { + return nil, nil + } + docScope := resolveDocScope(ctx, deps, p.DocScope, targetIDs, logger) + + // 2. Effective query. + // + // Mirrors Python search.py:hybrid_search/216/254 — the 400-char cap applies ONLY to the + // retrieval_query branch (entity-weighted expansion appended to the question). + // The keywords and bare-question branches are NOT truncated, matching Python's + // `f"{query} {keywords}".strip()` / `query` forms, which carry no [:400]. + var effectiveQuery string + if strings.TrimSpace(p.RetrievalQuery) != "" { + effectiveQuery = strings.TrimSpace(fmt.Sprintf("%s %s", p.Question, p.RetrievalQuery)) + if len(effectiveQuery) > maxEffectiveQueryChars { + effectiveQuery = effectiveQuery[:maxEffectiveQueryChars] + } + } else if strings.TrimSpace(p.Keywords) != "" { + effectiveQuery = strings.TrimSpace(fmt.Sprintf("%s %s", p.Question, p.Keywords)) + } else { + effectiveQuery = p.Question + } + + // Python's per-leg searching line (search.py:hybrid_search/215/252/418): BOTH the + // bracket label and the verb vary by entry point — "[Hybrid search] + // Searching the knowledge base for", "[Vector search] Searching by meaning + // for", "[BM25 search] Searching by keyword for", "[Grep search] + // Keyword-first locate for" — and only the three keyword-carrying legs + // append the keywords (see searchOpts.logLabel / logVerb / logKeywords). + // The suffix is printed only when non-empty: a keyword-less leg is a + // deliberate state (fan-out Channel B is a narrow bypass, + // agentic_rag_graph.py:_search_one; search_chunks takes no keywords at all, + // action_session.py:execute_tool), so a bare "(keywords: )" reads like a dropped + // argument rather than an intentional empty. + searchLine := searchLogLine(opts.logLabel, opts.logVerb, p.Question) + if kws := strings.TrimSpace(p.Keywords); opts.logKeywords && kws != "" { + searchLine += fmt.Sprintf(" (keywords: %s)", kws) + } + logger.Printf("%s", searchLine) + + // 3. Per-request dedup: an identical query+scope is retrieved at most once, + // so e.g. pre_search and a claim search asking the same question do not + // repeat the round-trip, child fetch and narrowing. Python's cache is + // hybrid-only — both the lookup (:136-141) and the store (:207) sit inside + // hybrid_search — hence opts.cache. + if deps.KB != nil && opts.cache { + if chunks, aggs, ok := deps.KB.SearchCacheLoad(SearchCacheKey(effectiveQuery, targetIDs, topN, docScope)); ok { + logger.Printf("[%s] Already searched this — reusing the %d passage(s) found earlier.", opts.logLabel, len(chunks)) + return chunks, aggs + } + } + + // 4. Retrieve. + // rank_feature (Python retrieve: rank_feature=label_question(question, + // self.kbs), agentic_rag.py:retrieve). Go computes it from the KB objects via the + // injected Tagger; nil Tagger ⇒ no boost (Python's label_question returns + // None). The result is a tag → weight map the engine understands. + var rankFeature map[string]float64 + if deps.Tagger != nil { + rankFeature = deps.Tagger.LabelQuestion(ctx, effectiveQuery, deps.KBs) + } + // The per-query progress line is NOT emitted here: runSearch already logs + // "[] Searching the knowledge base for …" through the run's logger, + // which Rag wraps with the think-log forwarder (see think_log.go). Emitting + // one here as well would show the same search twice in the reasoning block. + chunks, err := deps.Backend.Retrieve(ctx, RetrieveRequest{ + Query: effectiveQuery, + DatasetIDs: targetIDs, + DocScope: docScope, + TopN: topN, + TopK: intOrDef(deps.TopK, DefaultTopK), + RerankCandidatesCount: max(intOrDef(deps.RerankCandidatesCount, DefaultRerankCandidatesCount), topN), + SimilarityThreshold: opts.threshold, + // The field is named for keywords but carries the VECTOR weight, as in + // Python's vector_similarity_weight. Whether the vector leg runs at all + // — and its default — is decided by the calling entry-point function + // (see searchOpts.weight), NOT by a shared channel flag. ExcludeCompiled + // mirrors Python hybrid_search's must_not={"exists":"compile_kwd"} + // (search.py:hybrid_search), which keeps compiled products out of plain retrieval. + KeywordsSimilarityWeight: opts.weight, + TenantID: deps.TenantID, + MetaDataFilter: deps.MetaDataFilter, + RankFeature: rankFeature, + ExcludeCompiled: opts.excludeCompiled, + }) + if err != nil { + // Go-only line: Python lets the retriever's exception propagate untagged. + logger.Printf("[%s] retrieval failed: %v", opts.logLabel, err) + return nil, nil + } + + // 4b. retrieval_by_children: Python promotes child fragments to their parent + // chunk right after retrieval through _normalize (, also reached + // by vector_search L239 and bm25_search L276; grep_search rides on bm25_search; + // RAGTools.retrieve does the same at). ALL entry points do + // this, so every runSearch caller sets promoteChildren: true. The promotion + // lives here (gated by opts.promoteChildren) rather than in the shared Backend + // so a future non-promoting path can opt out; an empty tenant_id skips it, + // mirroring Python _normalize. + if opts.promoteChildren { + de := deps.DocEngine + if de == nil { + de = engine.Get() + } + if de != nil && len(chunks) > 0 { + chunks = nlp.RetrievalByChildren(chunks, []string{deps.TenantID}, de, ctx) + } + } + + // 5. doc_aggs from the FULL retrieved candidate set, computed here and left + // untouched by the narrowing / compiled-expansion steps below — mirroring + // Python, where `_normalize` takes doc_aggs straight from the retriever and + // _narrow_or_keep / _expand_with_compiled only ever replace kbinfos["chunks"]. + aggs := DocAggs(chunks) + + // Memory BEFORE narrowing: the raw corpus may hold a fact the narrowing + // drops, and a gap-driven grep over memory recovers it without re-querying. + if deps.KB != nil { + MemoryAdd(deps.KB, chunks) + } + + // 6. Narrow-or-keep (chunks only; doc_aggs stays as retrieved). + chunks = NarrowOrKeep(chunks, p.Keywords, opts.narrowLabel, logger) + + // 7. Compiled expansion. + if p.UseCompiled && len(chunks) > 0 && deps.Expand != nil { + logger.Printf("[%s] Compiled expansion enabled — enriching with page_index/tree/KG navigation.", opts.logLabel) + if err := deps.Expand.Expand(ctx, deps.KB, p.Question, p.Keywords, docScope); err != nil { + logger.Printf("[%s] compiled expansion failed: %v", opts.logLabel, err) + } + } + + // Python prints this progress line inside hybrid_search only (:203): the + // bm25/vector legs log nothing but their searching line, and grep_search + // has its own two lines (see GrepSearch). Gated so a log diff against + // Python lines up line for line. + if len(chunks) > 0 && opts.logExtra { + logger.Printf("[%s] %q -> %d chunk(s): %s", opts.logLabel, trunc(p.Question, 80), len(chunks), docStatsLine(chunks)) + } + + // 8. Cache the result — hybrid leg only, mirroring Python search.py:hybrid_search. + if deps.KB != nil && opts.cache { + deps.KB.SearchCacheStore(SearchCacheKey(effectiveQuery, targetIDs, topN, docScope), chunks, aggs) + } + return chunks, aggs +} + +// HybridSearch mirrors Python hybrid_search. The vector leg is +// gated on an embedder being configured (Python: vector_weight = _setting(...) +// if embd_mdl else 0); default weight 0.3. Compiled rows are excluded. +func HybridSearch(ctx context.Context, deps SearchDeps, p SearchParams) ([]map[string]any, []map[string]any) { + return runSearch(ctx, deps, p, searchOpts{ + weight: resolveVectorWeight(deps, ChannelHybrid), + threshold: floatOrDef(deps.SimilarityThreshold, DefaultSimilarityThreshold), + excludeCompiled: true, + promoteChildren: true, + logLabel: "Hybrid search", + logVerb: "Searching the knowledge base for", + logKeywords: true, + logExtra: true, // Python's dedup/compiled/progress lines live here only + cache: true, // Python's search_cache is read/written here only (:136/:207) + // Python passes the SNAKE_CASE tag to _narrow_or_keep on this leg + // (search.py:hybrid_search) although its own lines say "Hybrid search" — the + // inconsistency is Python's and is reproduced verbatim. + narrowLabel: "hybrid_search", + }) +} + +// VectorSearch mirrors Python vector_search. It is the pure +// vector entry point: with no embedder it returns nothing (Python bails when +// embd_mdl is unset), otherwise the vector weight is 1.0 and compiled rows are +// excluded. +func VectorSearch(ctx context.Context, deps SearchDeps, p SearchParams) ([]map[string]any, []map[string]any) { + if !deps.HasEmbedder { + return nil, nil + } + return runSearch(ctx, deps, p, searchOpts{ + weight: 1.0, + threshold: VectorSearchDefaultSimilarityThreshold, + excludeCompiled: true, + promoteChildren: true, + logLabel: "Vector search", + logVerb: "Searching by meaning for", + logKeywords: true, + logExtra: false, // Python vector_search logs nothing but its searching line (:215) + narrowLabel: "Vector search", + }) +} + +// BM25Search mirrors Python bm25_search. Keyword-only: the +// vector weight is unconditionally 0, the similarity floor is 0.0, and compiled +// rows are excluded. +func BM25Search(ctx context.Context, deps SearchDeps, p SearchParams) ([]map[string]any, []map[string]any) { + return runSearch(ctx, deps, p, searchOpts{ + weight: 0, + threshold: BM25SearchDefaultSimilarityThreshold, + excludeCompiled: true, + promoteChildren: true, + logLabel: "BM25 search", + logVerb: "Searching by keyword for", + logKeywords: true, + logExtra: false, // Python bm25_search logs nothing but its searching line (:252) + narrowLabel: "BM25 search", + }) +} + +// GrepSearch mirrors Python grep_search: a keyword-first locate +// that runs bm25_search and then narrows the prose candidates to the term-grep +// window (regex locate + short line-context, like Python's _narrow_by_terms). +// +// Behaviour, faithful to Python: +// - BM25 candidate pool built from the query's extracted terms — or the +// explicit keywords hint when one is supplied (search.py:grep_search) — never a +// hard filter: the pool still spans the corpus. +// - Table chunks pass through UN-narrowed (full text): the grep window would +// truncate them to a header-only snippet and hide mid/late-table answer rows. +// - Prose chunks are narrowed via NarrowByTerms with context {before:1, +// after:0}, per-chunk 700-char and total 8000-char caps. +// - When grep matches nothing, the raw BM25 candidates are returned unchanged so +// evidence is never dropped (enumeration / multi-hop must not lose candidates). +func GrepSearch(ctx context.Context, deps SearchDeps, p SearchParams) ([]map[string]any, []map[string]any) { + logger := searchLogger(deps) + query := strings.TrimSpace(p.Question) + // Python logs the locate line BEFORE extracting the terms and before the + // empty-query bail-out (search.py:grep_search). + logger.Printf("%s", searchLogLine("Grep search", "Keyword-first locate for", query)) + if query == "" { + return nil, nil + } + terms := GrepTermsFromQuery(query) + // Python then delegates to bm25_search with an explicit keywords hint + // (search.py:grep_search): `hint = keywords if keywords else " ".join(terms)`. + // A long question buries its proper nouns under stopwords; without the hint + // the noun chunk never enters the candidate pool and grep has nothing to + // locate. It is a SOFT boost — the pool still spans the corpus. Delegating + // (rather than calling runSearch) also reproduces Python's log sequence: + // bm25_search logs "[BM25 search] Searching by keyword for …" and narrows + // under that same tag (:252 / :288), then GrepSearch logs its own two lines. + hint := strings.TrimSpace(p.Keywords) + if hint == "" { + hint = strings.Join(terms, " ") + } + bp := p + bp.Question = query + bp.Keywords = hint + chunks, docAggs := BM25Search(ctx, deps, bp) + // Python: `if not chunks or not terms: return res` (search.py:grep_search). + if len(chunks) == 0 || len(terms) == 0 { + return chunks, docAggs + } + + var table, prose []map[string]any + for _, c := range chunks { + if IsTableChunk(c) { + table = append(table, c) + } else { + prose = append(prose, c) + } + } + if len(prose) == 0 { + return chunks, docAggs + } + + res := NarrowByTerms(prose, terms, nil, query, NarrowContext{Before: 1, After: 0}, + GrepOutCharsPerChunk, GrepOutTotalChars) + kept := res.Kept + if len(kept) == 0 { + // Nothing matched: keep the raw BM25 candidates so evidence is not dropped. + return chunks, docAggs + } + out := make([]map[string]any, 0, len(table)+len(kept)) + out = append(out, table...) + out = append(out, kept...) + // Python logs the post-narrow size and the per-doc breakdown for the + // combined table+prose set (search.py:grep_search / :469) — the grep leg's own two + // lines, which is why runSearch keeps logExtra off for it. + chars := 0 + for _, c := range out { + chars += len(ChunkTextOf(c)) + } + logger.Printf("[Grep search] narrowed %d->%d chunk(s), %.1fK chars.", len(chunks), len(out), float64(chars)/1000.0) + logger.Printf("[Grep search] %q -> %d chunk(s): %s", trunc(query, 80), len(out), docStatsLine(out)) + return out, docAggs +} + +// RetrieveSearch mirrors Python RAGTools.retrieve, the +// low/naive direct pass. Unlike HybridSearch it honours UsingEmbedding and does +// NOT exclude compiled rows (Python's retrieve has no must_not compile_kwd). +func RetrieveSearch(ctx context.Context, deps SearchDeps, p SearchParams) ([]map[string]any, []map[string]any) { + return runSearch(ctx, deps, p, searchOpts{ + weight: resolveVectorWeight(deps, ChannelRetrieve), + threshold: floatOrDef(deps.SimilarityThreshold, DefaultSimilarityThreshold), + excludeCompiled: false, + promoteChildren: true, + // Go-only identity: Python's L1 RAGTools.retrieve + // logs nothing of its own, so there is no Python string to mirror. The + // tag stays human-readable and the extra lines stay on, because this is + // the only trace the low-mode direct pass leaves. + logLabel: "Retrieve", + logVerb: "Searching the knowledge base for", + logKeywords: true, + logExtra: true, + narrowLabel: "retrieve", + }) +} + +// webSearchMaxChunks is the hard ceiling on admitted web passages per call: +// Python action_session._exec_web_search caps each query's chunks at [:8] and +// runs at most two queries, so 16 is the maximum. +const webSearchMaxChunks = 16 + +// WebSearchTool mirrors Python web_search / _exec_web_search +// (action_session.py:_exec_web_search): the `web_search` tool. The web_search tool schema +// takes a 1-2 element array of query strings (see webSearchToolSpec), so args is +// the positional query list, not a key/value object. Results share the RAGFlow +// chunk shape so they merge into the SAME shared evidence pool as corpus hits +// (Python _exec_web_search admits every web chunk via _admit_evidence), and the +// model sees the same REDUNDANT/OK/MISS outcome as the corpus tools. +func WebSearchTool(ctx context.Context, deps SearchDeps, args map[string]any) (ToolOutcome, error) { + if deps.WebSearch == nil { + // Mirror Python action_session._exec_web_search: an absent provider is + // an infra ERROR with an explicit do-not-retry note (returning MISS + // would let the model retry the same dead tool and burn turns), never a + // query-level miss. + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "web_search", + "note": "web_search is not configured in this deployment. Do not use this tool again; use the corpus tools (retrieve / search_chunks / navigate_*) instead.", + }}, + Status: StatusError, + Reason: ReasonInfra, + Metrics: map[string]any{}, + }, nil + } + queries := toolStringList(args, "") + if len(queries) == 0 { + // Fall back to a single positional element pushed under the empty key. + if raw, ok := args[""]; ok { + queries = toolStringList(map[string]any{"q": raw}, "q") + } + } + if len(queries) == 0 { + return ToolOutcome{Payload: []any{}, Status: StatusError, Reason: ReasonBadArgs}, nil + } + // Cap at two queries (Python action_session.execute_tool passes + // _arg_query_list(args, 2) for web_search). + if len(queries) > 2 { + queries = queries[:2] + } + results, err := deps.WebSearch.Search(ctx, queries) + if err != nil || len(results) == 0 { + return ToolOutcome{ + Payload: []any{map[string]any{ + "kind": "web_search", + "note": "No web result returned.", + }}, + Status: StatusMiss, + Reason: ReasonNoDoc, + Metrics: map[string]any{}, + }, nil + } + // Python caps each query's chunks at [:8]; with up to two queries that is a + // hard ceiling of 16 web passages per tool call. + if len(results) > webSearchMaxChunks { + results = results[:webSearchMaxChunks] + } + + // Build RAGFlow-shaped chunk maps and admit them to the shared evidence pool + // (Python _admit_evidence), mirroring the corpus tools' merge + outcome. + // Python de-duplicates web passages across the (up to two) queries by + // chunk_id; the Go provider surfaces raw strings, so de-dup by content to + // keep the same "each distinct passage appears once" behaviour. + var payload []any + var evidenceIDs []string + newChunks := 0 + seen := make(map[string]bool, len(results)) + for i, r := range results { + if r == "" || seen[r] { + continue + } + seen[r] = true + chunkID := fmt.Sprintf("web_%d", i) + c := map[string]any{ + "chunk_id": chunkID, + "content": r, + "doc_id": "web", + } + if deps.KB != nil { + before := len(deps.KB.Chunks) + deps.KB.Merge([]map[string]any{c}, nil) + newChunks += len(deps.KB.Chunks) - before + } + // Evidence references the chunk id (Python ids.append(cid)), not a pool + // position. + evidenceIDs = append(evidenceIDs, chunkID) + // Passage shape from _admit_evidence(include_doc_id=False): {"id","content"}, + // non-table text cut to 1200 code points (plain slice, no ellipsis). + content := r + if !IsTableChunk(c) { + content = truncateRunes(content, 1200) + } + payload = append(payload, map[string]any{"id": chunkID, "content": content}) + } + + if len(payload) == 0 { + return ToolOutcome{Payload: []any{}, Status: StatusMiss, Reason: ReasonNoDoc, Metrics: map[string]any{"hits": 0, "new_evidence": 0}}, nil + } + status := StatusOK + if newChunks == 0 { + status = StatusRedundant + } + return ToolOutcome{ + Payload: payload, + EvidenceIDs: evidenceIDs, + Status: status, + Metrics: map[string]any{"hits": len(payload), "new_evidence": newChunks}, + }, nil +} + +// list_chunks deep-read caps (mirror Python action_session.py / tools/search.py). +const ( + // listChunksMaxDeep caps the deep-read pool admission (Python + // tools/search.py _LIST_CHUNKS_MAX_CHUNKS = 80). + listChunksMaxDeep = 80 + // listChunksMaxOut caps the model-facing passage list (Python + // action_session.py _exec_list_chunks [:30]). + listChunksMaxOut = 30 +) + +// listChunks deep-reads one document's FULL text and admits it to the shared +// evidence pool — the mirror of Python _exec_list_chunks +// → tools.list_chunks → tools.fetch_full_document. +// +// The read goes through deps.DocChunks (the same reader fetch_full_document / +// summarize_document use), not the evidence pool, so navigate_tree can route a +// doc_id whose chunks were never retrieved; when DocChunks is unwired it falls +// back to the pool so the tool still works in unit tests. +// +// Outcome semantics mirror _search_outcome: an empty result (blank doc_id, unknown +// doc, or nothing read) is a MISS — not an error; a non-empty result is REDUNDANT +// when nothing new entered the pool, else OK. The deep read is capped at +// listChunksMaxDeep and the model-facing output at listChunksMaxOut. +func (e *searchExecutor) listChunks(ctx context.Context, args map[string]any) (ToolOutcome, error) { + docID := argString(args, "doc_id") + if docID == "" { + // Mirror Python list_chunks("") → empty → _search_outcome → MISS. + return ToolOutcome{Payload: []any{}, Status: StatusMiss, Reason: ReasonNoDoc, Metrics: map[string]any{"hits": 0}}, nil + } + + var chunks []map[string]any + if e.deps.DocChunks != nil { + // Real doc-store deep read (Python fetch_full_document), budgeted by the + // model window like Python's max_length gate. + deep, _ := fetchFullDocument(ctx, e.deps, docID, e.req.MaxLength) + if len(deep) > listChunksMaxDeep { + deep = deep[:listChunksMaxDeep] + } + chunks = deep + } else if e.deps.KB != nil { + // Fallback: scan the in-memory evidence pool (unit-test / unwired path). + for _, c := range e.deps.KB.Chunks { + if DocIDOf(c) == docID { + chunks = append(chunks, c) + } + } + } + + if len(chunks) == 0 { + // Unknown doc_id / out-of-scope doc, or nothing readable: a query-level + // MISS (Python list_chunks returns {"chunks": []} and _search_outcome + // turns that into MISS/no_doc — there is no "graceful OK empty" branch). + return ToolOutcome{Payload: []any{}, Status: StatusMiss, Reason: ReasonNoDoc, Metrics: map[string]any{"hits": 0, "new_evidence": 0}}, nil + } + + // Python _seed_evidence CREATES the pool when it + // is absent, so the admittance below always has somewhere to write. + if e.deps.KB == nil { + e.deps.KB = &Kbinfos{} + } + + // Python _exec_list_chunks (:809-833) admits only the first listChunksMaxOut + // (30) of the listChunksMaxDeep (80) fetched passages: no-id chunks and in-call + // duplicates are skipped, evidence references the chunk id, and only chunks new + // to the shared pool are appended. + admit := chunks + if len(admit) > listChunksMaxOut { + admit = admit[:listChunksMaxOut] + } + kbSeen := make(map[string]bool, len(e.deps.KB.Chunks)) + for _, c := range e.deps.KB.Chunks { + kbSeen[chunkKey(c)] = true + } + seen := map[string]bool{} + var payload []any + var evidenceIDs []string + newChunks := 0 + for _, c := range admit { + cid := ChunkIDOf(c) + if cid == "" || seen[cid] { + continue + } + seen[cid] = true + evidenceIDs = append(evidenceIDs, cid) + // Shape like _admit_evidence(include_doc_id=False): {"id","content"} with + // non-table text cut to 1200 code points (a plain slice, no ellipsis). + content := ChunkTextOf(c) + if !IsTableChunk(c) { + content = truncateRunes(content, 1200) + } + payload = append(payload, map[string]any{"id": cid, "content": content}) + key := chunkKey(c) + if !kbSeen[key] { + kbSeen[key] = true + e.deps.KB.Chunks = append(e.deps.KB.Chunks, c) + newChunks++ + } + } + + if len(payload) == 0 { + return ToolOutcome{Payload: []any{}, Status: StatusMiss, Reason: ReasonNoDoc, Metrics: map[string]any{"hits": 0, "new_evidence": 0}}, nil + } + status := StatusOK + if newChunks == 0 { + status = StatusRedundant + } + return ToolOutcome{ + Payload: payload, + EvidenceIDs: evidenceIDs, + Status: status, + Reason: ReasonNone, + Metrics: map[string]any{"hits": len(payload), "new_evidence": newChunks}, + }, nil +} + +// SearchCacheKey mirrors Python _search_cache_key: the tuple of what actually +// determines a retrieval result. Scope and limits are part of the key so only a +// genuinely identical query is served from cache. +func SearchCacheKey(effectiveQuery string, targetIDs []string, topN int, docScope []string) string { + query := normalizeSpace(effectiveQuery) + ids := append([]string(nil), targetIDs...) + sort.Strings(ids) + docs := append([]string(nil), docScope...) + sort.Strings(docs) + return fmt.Sprintf("%s|%v|%d|%v", query, ids, topN, docs) +} + +func normalizeSpace(s string) string { + return strings.ToLower(strings.Join(strings.Fields(s), " ")) +} + +// docInDatasets reports whether docID belongs to the datasets being searched, +// mirroring the `kb_id.in_(self.kb_ids)` guard of Python +// RAGTools._resolve_doc_tenant. +// +// The second result is false only when ownership could NOT be determined — no +// verifier injected, or the lookup errored. It is true when the lookup +// completed, including the "document absent from the bound datasets" case: +// KnownDocIDs returns a known-subset map, so a foreign/stale doc_id yields an +// empty map (never an error), and is reported as belongs=false / verified=true +// so the caller rejects it instead of reading it unscoped — exactly as Python +// returns None from _resolve_doc_tenant and refuses to fetch. +func docInDatasets(ctx context.Context, deps SearchDeps, docID string) (belongs, verified bool) { + if deps.DocIDVerifier == nil || docID == "" { + return true, false + } + known, err := deps.DocIDVerifier.KnownDocIDs(ctx, deps.KbIDs, []string{docID}) + if err != nil { + // Fail open only on an actual lookup failure; never on "not found". + return true, false + } + return known[docID], true +} + +// scopedDocIDs mirrors Python RAGTools.scoped_doc_ids, +// the ceiling every search entry point applies before touching the doc store: +// with no session scope the caller's scope passes through; with a session scope +// an absent caller scope falls back to it and an explicit one is INTERSECTED +// with it, so a model-generated doc_scope can never escape the session's +// document restriction. +func scopedDocIDs(sessionScope, scope []string) []string { + if len(sessionScope) == 0 { + return scope + } + if len(scope) == 0 { + return append([]string(nil), sessionScope...) + } + allowed := make(map[string]bool, len(sessionScope)) + for _, d := range sessionScope { + allowed[d] = true + } + out := make([]string, 0, len(scope)) + for _, d := range scope { + if allowed[d] { + out = append(out, d) + } + } + return out +} + +// resolveDocScope mirrors Python retrieve:620-635 — apply the session doc_scope +// ceiling, then keep only the requested document ids that actually belong to the +// session's datasets. +// +// The ceiling is Python's scoped_doc_ids: a None request scope falls back to the +// session's fixed doc_scope (deps.DocScope), and an explicit request scope is +// intersected with it, so a session bound to a fixed document set keeps +// searching within it whichever scope the tool passes. +// +// Three outcomes are tuned to match Python, because the document scope is +// supplied by model-generated tool arguments and must never silently change what +// is searched: +// +// - verification unavailable (no verifier injected, or it errored): the scope +// is passed through unchanged (fail open); +// - every candidate unknown AND a fixed session base scope (self.doc_scope is +// not None): return an EMPTY result (Python retrieve:631-632 returns +// {"chunks": [], "doc_aggs": []}), never unfiltered retrieval; +// - every candidate unknown with NO session base scope: drop the scope and +// search UNFILTERED (Python retrieve:633-635 — doc_scope = None). +// +// The empty-vs-unfiltered distinction is encoded as a non-nil empty slice vs +// nil: the backend treats a nil DocScope as "search everything" and a non-nil +// empty DocScope as "match nothing". +func resolveDocScope(ctx context.Context, deps SearchDeps, scope, kbIDs []string, logger *log.Logger) []string { + scope = scopedDocIDs(deps.DocScope, scope) + if len(scope) == 0 && len(deps.DocScope) > 0 { + // The session ceiling removed every requested id. Python's scoped_doc_ids + // yields an empty list here, which its downstream `if doc_scope:` reads as + // "no filter" and searches unfiltered; Go deliberately keeps the safer + // "match nothing" instead of letting a model-supplied scope escape the + // session's document restriction. + return []string{} + } + if deps.DocIDVerifier == nil { + // No verifier: trust the scope as given (fail open). + return scope + } + candidates := make([]string, 0, len(scope)) + for _, d := range scope { + if d != "" { + candidates = append(candidates, d) + } + } + if len(candidates) == 0 { + // No usable candidate ids (request scope None and no session base scope, + // or only empty strings): Python leaves doc_scope = None and searches + // unfiltered. Return nil, not an empty set, so the backend does not filter + // to zero documents. + return nil + } + known, err := deps.DocIDVerifier.KnownDocIDs(ctx, kbIDs, candidates) + if err != nil { + logger.Printf("[Hybrid search] document-id verification unavailable (%d candidate(s)); searching the scope as given", len(candidates)) + return scope + } + valid := make([]string, 0, len(candidates)) + for _, d := range candidates { + if known[d] { + valid = append(valid, d) + } + } + if len(valid) == 0 { + // Every candidate is unknown. Python retrieve:631-635 distinguishes two + // outcomes by the SESSION base scope: + // - a fixed session doc_scope (self.doc_scope is not None) → return an + // empty result (no documents match); + // - no session base scope → fall back to UNFILTERED retrieval (None). + if len(deps.DocScope) > 0 { + return []string{} + } + logger.Printf("[Hybrid search] every supplied doc ID was unknown; falling back to unfiltered retrieval") + return nil + } + return valid +} + +// DocAggs builds the per-document aggregation from a chunk list: each entry +// carries doc_id (the key direct.py dedups on) plus the counts the reporting layer +// reads. Python gets these from the retriever (retrieval(..., aggs=True)); the Go +// Retriever interface returns only chunks, so they are derived here. +func DocAggs(chunks []map[string]any) []map[string]any { + if len(chunks) == 0 { + return nil + } + type stat struct { + count int + chars int + name string + } + order := make([]string, 0, 8) + stats := map[string]*stat{} + for _, c := range chunks { + if c == nil { + continue + } + id := DocIDOf(c) + if id == "" { + id = DocTitleOf(c) + } + if id == "" { + id = "?" + } + s, ok := stats[id] + if !ok { + s = &stat{name: DocTitleOf(c)} + stats[id] = s + order = append(order, id) + } + s.count++ + s.chars += len(ChunkTextOf(c)) + } + out := make([]map[string]any, 0, len(order)) + for _, id := range order { + s := stats[id] + // Field names match runtime's referenceDocAggsFromRetrieval + // (doc_id / doc_name / count) so these aggregations can be handed + // straight to CanvasState.SetRetrievalReferences without translation. + out = append(out, map[string]any{ + "doc_id": id, + "doc_name": s.name, + "count": s.count, + "char_count": s.chars, + }) + } + return out +} + +// docStatsLine renders the per-document breakdown used by the search log line. +func docStatsLine(chunks []map[string]any) string { + parts := make([]string, 0, 8) + for _, a := range DocAggs(chunks) { + parts = append(parts, fmt.Sprintf("%s:%vchunk(%vchars)", + a["doc_id"], a["count"], a["char_count"])) + } + return strings.Join(parts, "; ") +} + +// Normalisation of web-search payloads. +// +// Mirrors the shaping the Python harness applies to _exec_web_search results so +// they enter kbinfos with the same field names every other chunk carries. + +// normalizeWebResults converts a raw web-search JSON payload into chunk maps. +// Accepts either {"chunks": [...]} or {"results": [...]}; entries without both a +// URL and content are dropped. +func normalizeWebResults(raw []byte) []map[string]any { + var res struct { + Chunks []map[string]any `json:"chunks"` + Results []map[string]any `json:"results"` + } + if err := json.Unmarshal(raw, &res); err != nil { + return nil + } + src := res.Chunks + if len(src) == 0 { + src = res.Results + } + out := make([]map[string]any, 0, len(src)) + for i, c := range src { + url := firstNonEmpty(anyString(c["url"]), anyString(c["link"]), anyString(c["source"])) + if url == "" { + continue + } + content := firstNonEmpty(anyString(c["content"]), anyString(c["raw_content"]), anyString(c["text"])) + if content == "" { + continue + } + docID := anyString(c["doc_id"]) + if docID == "" { + docID = url + } + // doc_id stays the source URL; chunk_id must be UNIQUE per snippet so + // Kbinfos.Merge (dedup by chunkKey) does not collapse several snippets + // from the same URL, or the same URL across two retrieval rounds. + chunkID := fmt.Sprintf("%s#%d", docID, i) + out = append(out, map[string]any{ + "chunk_id": chunkID, + "content_with_weight": content, + "doc_id": docID, + "docnm_kwd": firstNonEmpty(anyString(c["title"]), anyString(c["source"])), + "dataset_id": anyString(c["dataset_id"]), + "url": url, + "source": "web", + }) + } + return out +} + +// firstNonEmpty returns the first argument that is not blank. +func firstNonEmpty(ss ...string) string { + for _, s := range ss { + if strings.TrimSpace(s) != "" { + return s + } + } + return "" +} + +// --------------------------------------------------------------------------- +// Per-request retrieval cache (Python tools.search_cache). +// +// The Python side keeps a dict on the tools object keyed by the search +// parameters; an identical (query, scope, limits) search is served from cache +// instead of hitting the retriever again. Go attaches the same cache to +// Kbinfos and exposes it as methods here so the search tool and its cache live +// in one file, mirroring tools/search.py. +// --------------------------------------------------------------------------- + +// searchCache is the per-request retrieval cache. Mirrors Python +// tools.search_cache (a dict on the tools object). +type searchCache struct { + mu sync.Mutex + entries map[string]cachedSearch +} + +// cachedSearch is one cache entry. Mirrors a Python tools.search_cache value. +type cachedSearch struct { + chunks []map[string]any + aggs []map[string]any +} + +// SearchCacheLoad returns a cached retrieval for key, or (nil, nil, false) when +// the key is absent. Mirrors Python `if cache_key in cache: return cache[cache_key]`. +func (k *Kbinfos) SearchCacheLoad(key string) ([]map[string]any, []map[string]any, bool) { + c := k.ensureCache() + c.mu.Lock() + defer c.mu.Unlock() + e, ok := c.entries[key] + if !ok { + return nil, nil, false + } + return e.chunks, e.aggs, true +} + +// SearchCacheStore records a retrieval under key. Mirrors Python +// `cache[cache_key] = {...}`. +func (k *Kbinfos) SearchCacheStore(key string, chunks, aggs []map[string]any) { + c := k.ensureCache() + c.mu.Lock() + defer c.mu.Unlock() + if c.entries == nil { + c.entries = make(map[string]cachedSearch) + } + c.entries[key] = cachedSearch{chunks: chunks, aggs: aggs} +} + +// ensureCache lazily initialises the per-request cache so a zero-value Kbinfos +// is usable without an explicit setup step. +func (k *Kbinfos) ensureCache() *searchCache { + k.cacheOnce.Do(func() { + if k.cache == nil { + k.cache = &searchCache{} + } + }) + return k.cache +} diff --git a/internal/rag/advanced_rag/harness/tool_search_test.go b/internal/rag/advanced_rag/harness/tool_search_test.go new file mode 100644 index 00000000000..d81a98a12f8 --- /dev/null +++ b/internal/rag/advanced_rag/harness/tool_search_test.go @@ -0,0 +1,1122 @@ +// +// 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. +// + +package harness + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + + "ragflow/internal/entity" +) + +// stubRetriever returns a fixed result and records the requests it received. +type stubRetriever struct { + chunks []map[string]any + err error + requests []RetrieveRequest +} + +func (s *stubRetriever) Retrieve(_ context.Context, req RetrieveRequest) ([]map[string]any, error) { + s.requests = append(s.requests, req) + if s.err != nil { + return nil, s.err + } + return s.chunks, nil +} + +func newTestSearchDeps(r Retriever) (SearchDeps, *Kbinfos) { + kb := &Kbinfos{} + return SearchDeps{ + Backend: r, + KbIDs: []string{"kb1"}, + TenantID: "tenant1", + KB: kb, + }, kb +} + +func TestHybridSearchBailsWithoutDatasetsOrBackend(t *testing.T) { + // No bound datasets -> no search at all (Python returns empty kbinfos). + got, aggs := HybridSearch(context.Background(), SearchDeps{ + Backend: &stubRetriever{chunks: []map[string]any{{"content": "x"}}}, + }, SearchParams{Question: "q"}) + if got != nil || aggs != nil { + t.Error("no datasets must short-circuit to empty") + } + // No backend -> empty. + deps, _ := newTestSearchDeps(nil) + if got, _ := HybridSearch(context.Background(), deps, SearchParams{Question: "q"}); got != nil { + t.Error("no backend must return empty") + } +} + +func TestHybridSearchBuildsEffectiveQuery(t *testing.T) { + // Weighted query wins, and the result is capped at 400 chars. + r := &stubRetriever{chunks: []map[string]any{{"content": "hit"}}} + deps, _ := newTestSearchDeps(r) + long := strings.Repeat("weighted ", 100) + HybridSearch(context.Background(), deps, SearchParams{ + Question: "who made it?", RetrievalQuery: long, + }) + if len(r.requests) != 1 { + t.Fatalf("requests = %d, want 1", len(r.requests)) + } + q := r.requests[0].Query + if !strings.HasPrefix(q, "who made it? weighted") { + t.Errorf("query = %q, want question + weighted query", q) + } + if len(q) != maxEffectiveQueryChars { + t.Errorf("query length = %d, want capped at %d", len(q), maxEffectiveQueryChars) + } + + // No weighted query -> keywords fall into the query text. + r = &stubRetriever{chunks: []map[string]any{{"content": "hit"}}} + deps, _ = newTestSearchDeps(r) + HybridSearch(context.Background(), deps, SearchParams{Question: "who made it?", Keywords: "culdcept"}) + if r.requests[0].Query != "who made it? culdcept" { + t.Errorf("query = %q, want keywords appended", r.requests[0].Query) + } + + // Neither -> the bare question. + r = &stubRetriever{chunks: []map[string]any{{"content": "hit"}}} + deps, _ = newTestSearchDeps(r) + HybridSearch(context.Background(), deps, SearchParams{Question: "who made it?"}) + if r.requests[0].Query != "who made it?" { + t.Errorf("query = %q, want the bare question", r.requests[0].Query) + } +} + +func TestHybridSearchPassesRankFeature(t *testing.T) { + // label_question -> rank_feature must flow into the underlying retrieve + // request (Python retrieve: rank_feature=label_question(question, self.kbs), + // agentic_rag.py:retrieve). A nil Tagger must leave RankFeature empty. + r := &stubRetriever{chunks: []map[string]any{{"content": "hit"}}} + deps, _ := newTestSearchDeps(r) + deps.KBs = []*entity.Knowledgebase{{}} + deps.Tagger = stubTagger{t: t} + HybridSearch(context.Background(), deps, SearchParams{Question: "who made it?"}) + if len(r.requests) != 1 { + t.Fatalf("requests = %d, want 1", len(r.requests)) + } + want := map[string]float64{"definition": 1.0, "entity": 1.0} + if got := r.requests[0].RankFeature; !reflect.DeepEqual(got, want) { + t.Errorf("RankFeature = %v, want %v", got, want) + } + + // Nil Tagger -> empty rank feature (Python label_question None). + r2 := &stubRetriever{chunks: []map[string]any{{"content": "hit"}}} + deps2, _ := newTestSearchDeps(r2) + HybridSearch(context.Background(), deps2, SearchParams{Question: "unique query no rf"}) + if len(r2.requests) != 1 { + t.Fatalf("requests = %d, want 1", len(r2.requests)) + } + if len(r2.requests[0].RankFeature) != 0 { + t.Errorf("RankFeature = %v, want empty for nil Tagger", r2.requests[0].RankFeature) + } +} + +// stubTagger implements QuestionLabeler for TestHybridSearchPassesRankFeature. +type stubTagger struct{ t *testing.T } + +func (s stubTagger) LabelQuestion(_ context.Context, question string, kbs []*entity.Knowledgebase) map[string]float64 { + if question != "who made it?" { + s.t.Errorf("LabelQuestion called with question=%q", question) + } + if len(kbs) != 1 { + s.t.Errorf("LabelQuestion called with %d kbs, want 1", len(kbs)) + } + return map[string]float64{"definition": 1.0, "entity": 1.0} +} + +func TestHybridSearchCachesIdenticalQuery(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{{"content": "hit"}}} + deps, _ := newTestSearchDeps(r) + p := SearchParams{Question: "same question"} + HybridSearch(context.Background(), deps, p) + HybridSearch(context.Background(), deps, p) + if len(r.requests) != 1 { + t.Errorf("backend calls = %d, want 1 (second served from cache)", len(r.requests)) + } + // A different scope is a different retrieval. + HybridSearch(context.Background(), deps, SearchParams{Question: "same question", DocScope: []string{"doc9"}}) + if len(r.requests) != 2 { + t.Errorf("backend calls = %d, want 2 (doc_scope is part of the key)", len(r.requests)) + } + // A different TopN is a different retrieval. + HybridSearch(context.Background(), deps, SearchParams{Question: "same question", TopN: 5}) + if len(r.requests) != 3 { + t.Errorf("backend calls = %d, want 3 (top_n is part of the key)", len(r.requests)) + } +} + +func TestSearchCacheKeyIgnoresOrderAndWhitespace(t *testing.T) { + a := SearchCacheKey(" Who Made It ", []string{"b", "a"}, 12, []string{"d2", "d1"}) + b := SearchCacheKey("who made it", []string{"a", "b"}, 12, []string{"d1", "d2"}) + if a != b { + t.Errorf("cache key not canonical:\n%q\n%q", a, b) + } +} + +func TestHybridSearchStoresMemoryBeforeNarrowing(t *testing.T) { + // The raw chunk must reach memory even when narrowing rewrites the copy + // handed downstream. + r := &stubRetriever{chunks: []map[string]any{{ + "chunk_id": "c1", + "content": "Alpha sentence. Culdcept was made by OmiyaSoft in 1999. Omega sentence.", + "doc_id": "d1", + }}} + deps, kb := newTestSearchDeps(r) + HybridSearch(context.Background(), deps, SearchParams{ + Question: "who made Culdcept?", Keywords: "culdcept", + }) + if MemorySize(kb) != 1 { + t.Fatalf("memory size = %d, want 1", MemorySize(kb)) + } + if strings.Contains(ChunkTextOf(kb.Memory[0]), "") { + t.Error("memory must hold the RAW chunk, not the narrowed/highlighted copy") + } +} + +func TestHybridSearchReturnsEmptyOnBackendError(t *testing.T) { + deps, _ := newTestSearchDeps(&stubRetriever{err: errors.New("ES down")}) + got, aggs := HybridSearch(context.Background(), deps, SearchParams{Question: "q"}) + if len(got) != 0 || len(aggs) != 0 { + t.Errorf("a backend failure must yield empty results, got %d chunks", len(got)) + } +} + +// --------------------------------------------------------------------------- +// Narrowing +// --------------------------------------------------------------------------- + +func TestNarrowOrKeepIsAllOrNothing(t *testing.T) { + chunks := []map[string]any{ + {"content": "Culdcept was made by OmiyaSoft."}, + {"content": "It was released in 1999."}, + } + // Keywords hit -> narrowed subset (the non-matching chunk is dropped). + got := NarrowOrKeep(chunks, "culdcept", "test", nil) + if len(got) != 1 || !strings.Contains(ChunkTextOf(got[0]), "Culdcept") { + t.Errorf("narrowed = %v, want only the matching chunk", got) + } + + // No keyword overlap -> ALL chunks kept (this is the whole point: the + // retriever already ranked them, and dropping everything produced empty + // results and unverified claims). + got = NarrowOrKeep(chunks, "zzz-no-match", "test", nil) + if len(got) != len(chunks) { + t.Errorf("no-match kept %d, want all %d", len(got), len(chunks)) + } + + // Empty keywords -> untouched. + if got := NarrowOrKeep(chunks, "", "test", nil); len(got) != len(chunks) { + t.Error("empty keywords must return chunks unchanged") + } +} + +func TestNarrowContentKeepsNeighboursAndHighlights(t *testing.T) { + content := "Alpha filler. Culdcept was made by OmiyaSoft. Omega filler." + got, ok := NarrowContent(content, []string{"culdcept"}) + if !ok { + t.Fatal("NarrowContent must match") + } + if !strings.Contains(got, "Culdcept") { + t.Errorf("keyword not highlighted: %q", got) + } + // +/-1 neighbour window: Alpha and Omega should be present. + if !strings.Contains(got, "Alpha") || !strings.Contains(got, "Omega") { + t.Errorf("neighbour sentences missing: %q", got) + } + if !strings.HasPrefix(got, "...") || !strings.HasSuffix(got, "...") { + t.Errorf("narrowed text must be wrapped in ellipses: %q", got) + } + if _, ok := NarrowContent("nothing relevant here", []string{"culdcept"}); ok { + t.Error("no match must return false") + } +} + +func TestSplitKeywordsFallsBackToBigrams(t *testing.T) { + // >=3 comma terms -> used as-is, lower-cased. + got := SplitKeywords("Alpha, Beta, Gamma") + if len(got) != 3 || got[0] != "alpha" { + t.Errorf("comma split = %v", got) + } + // <3 terms -> bigrams are more discriminative than single words. + got = SplitKeywords("finale run time") + if len(got) != 2 || got[0] != "finale run" || got[1] != "run time" { + t.Errorf("bigram fallback = %v, want [finale run, run time]", got) + } + if SplitKeywords(" ") != nil { + t.Error("blank keywords must yield no terms") + } +} + +func TestHighlightKeywordsPrefersLongestTerm(t *testing.T) { + // "new york" must win over "york" so the shorter term cannot split it. + got := HighlightKeywords("welcome to New York city", []string{"york", "new york"}) + if !strings.Contains(got, "New York") { + t.Errorf("highlight = %q, want the longest term applied", got) + } + if strings.Contains(got, "york") { + t.Errorf("shorter term must not win: %q", got) + } +} + +// --------------------------------------------------------------------------- +// Doc aggregations +// --------------------------------------------------------------------------- + +func TestDocAggsGroupsByDocument(t *testing.T) { + chunks := []map[string]any{ + {"doc_id": "d1", "docnm_kwd": "Doc One", "content": "aaaa"}, + {"doc_id": "d1", "docnm_kwd": "Doc One", "content": "bb"}, + {"doc_id": "d2", "docnm_kwd": "Doc Two", "content": "c"}, + } + aggs := DocAggs(chunks) + if len(aggs) != 2 { + t.Fatalf("aggs = %d, want 2 documents", len(aggs)) + } + // Order follows first appearance, so the log line is stable. + if aggs[0]["doc_id"] != "d1" || aggs[0]["count"] != 2 { + t.Errorf("d1 agg = %v, want count 2", aggs[0]) + } + if aggs[0]["char_count"] != 6 { + t.Errorf("d1 char_count = %v, want 6 (4+2)", aggs[0]["char_count"]) + } + if aggs[1]["doc_id"] != "d2" || aggs[1]["count"] != 1 { + t.Errorf("d2 agg = %v", aggs[1]) + } + if DocAggs(nil) != nil { + t.Error("no chunks must yield no aggregations") + } +} + +func TestHybridSearchAggregatesAndRespectsScope(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{ + {"doc_id": "d1", "content": "a"}, + {"doc_id": "d2", "content": "b"}, + }} + deps, _ := newTestSearchDeps(r) + chunks, aggs := HybridSearch(context.Background(), deps, SearchParams{ + Question: "q", DocScope: []string{"d1"}, + }) + if len(chunks) != 2 || len(aggs) != 2 { + t.Fatalf("chunks=%d aggs=%d", len(chunks), len(aggs)) + } + // doc_scope must reach the backend. + if len(r.requests[0].DocScope) != 1 || r.requests[0].DocScope[0] != "d1" { + t.Errorf("doc_scope not forwarded: %v", r.requests[0].DocScope) + } + // Explicit kb_ids override the session default. + r.requests = nil + HybridSearch(context.Background(), deps, SearchParams{Question: "q", KbIDs: []string{"kb9"}}) + if len(r.requests[0].DatasetIDs) != 1 || r.requests[0].DatasetIDs[0] != "kb9" { + t.Errorf("kb_ids not honoured: %v", r.requests[0].DatasetIDs) + } +} + +func TestHybridSearchAggsCoverFullRetrievedBeforeNarrowing(t *testing.T) { + // doc_aggs must reflect the FULL pre-narrow retrieved set, mirroring Python + // where _normalize takes doc_aggs from the retriever and _narrow_or_keep only + // replaces kbinfos["chunks"]. Here the keyword narrows the chunks to doc d1, + // but the aggregation still counts both retrieved documents. + r := &stubRetriever{chunks: []map[string]any{ + {"doc_id": "d1", "docnm_kwd": "one", "content": "needle buried here", "id": "c1"}, + {"doc_id": "d2", "docnm_kwd": "two", "content": "nothing relevant", "id": "c2"}, + }} + deps, _ := newTestSearchDeps(r) + chunks, aggs := HybridSearch(context.Background(), deps, SearchParams{ + Question: "q", Keywords: "needle", + }) + if len(chunks) != 1 { + t.Fatalf("narrowed chunks = %d, want 1 (d1 only)", len(chunks)) + } + if len(aggs) != 2 { + t.Fatalf("aggs = %d, want 2 (full pre-narrow set: d1 and d2)", len(aggs)) + } +} + +func TestHybridSearchInvokesCompiledExpansion(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{{"content": "hit"}}} + deps, _ := newTestSearchDeps(r) + exp := &stubExpander{} + deps.Expand = exp + HybridSearch(context.Background(), deps, SearchParams{Question: "q", UseCompiled: true}) + if exp.calls != 1 { + t.Errorf("compiled expansion calls = %d, want 1", exp.calls) + } + // Without UseCompiled it must not run. + exp.calls = 0 + HybridSearch(context.Background(), deps, SearchParams{Question: "other", UseCompiled: false}) + if exp.calls != 0 { + t.Error("compiled expansion must be opt-in") + } +} + +type stubExpander struct{ calls int } + +func (s *stubExpander) Expand(_ context.Context, _ *Kbinfos, _, _ string, _ []string) error { + s.calls++ + return nil +} + +// lastReq returns the most recent RetrieveRequest the stub recorded, failing if +// none was issued. +func (r *stubRetriever) lastReq(t *testing.T) RetrieveRequest { + t.Helper() + if len(r.requests) == 0 { + t.Fatal("expected a retrieve request, got none") + } + return r.requests[len(r.requests)-1] +} + +// TestVectorSearchBailsWithoutEmbedder mirrors Python vector_search: with no +// embedder configured it returns nothing (Python bails when embd_mdl is unset), +// and must NOT even hit the backend. +func TestVectorSearchBailsWithoutEmbedder(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{{"content": "x"}}} + deps, _ := newTestSearchDeps(r) + if got, _ := VectorSearch(context.Background(), deps, SearchParams{Question: "q"}); got != nil { + t.Error("vector search without embedder must be empty") + } + if len(r.requests) != 0 { + t.Errorf("vector search without embedder must not call the backend, got %d calls", len(r.requests)) + } +} + +// TestVectorSearchWeightIsOne mirrors Python vector_search: the pure-vector leg +// carries weight 1.0 and excludes compiled rows. +func TestVectorSearchWeightIsOne(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{{"content": "x"}}} + deps, _ := newTestSearchDeps(r) + deps.HasEmbedder = true + VectorSearch(context.Background(), deps, SearchParams{Question: "q"}) + req := r.lastReq(t) + if req.KeywordsSimilarityWeight != 1.0 { + t.Errorf("vector search weight = %v, want 1.0", req.KeywordsSimilarityWeight) + } + if !req.ExcludeCompiled { + t.Error("vector search must exclude compiled rows") + } +} + +// TestBM25SearchUsesZeroWeight mirrors Python bm25_search: keyword-only, vector +// weight unconditionally 0, threshold 0.0, excludes compiled rows. +func TestBM25SearchUsesZeroWeight(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{{"content": "x"}}} + deps, _ := newTestSearchDeps(r) + BM25Search(context.Background(), deps, SearchParams{Question: "q"}) + req := r.lastReq(t) + if req.KeywordsSimilarityWeight != 0 { + t.Errorf("bm25 search weight = %v, want 0", req.KeywordsSimilarityWeight) + } + if req.SimilarityThreshold != 0 { + t.Errorf("bm25 search threshold = %v, want 0", req.SimilarityThreshold) + } + if !req.ExcludeCompiled { + t.Error("bm25 search must exclude compiled rows") + } +} + +// TestGrepSearchDelegatesToBM25 mirrors Python grep_search: it is bm25_search +// with a keyword-only (weight 0) leg and compiled-row exclusion. +func TestGrepSearchDelegatesToBM25(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{{"content": "x"}}} + deps, _ := newTestSearchDeps(r) + GrepSearch(context.Background(), deps, SearchParams{Question: "q", Keywords: "kw"}) + req := r.lastReq(t) + if req.KeywordsSimilarityWeight != 0 { + t.Errorf("grep search weight = %v, want 0", req.KeywordsSimilarityWeight) + } + if !req.ExcludeCompiled { + t.Error("grep search must exclude compiled rows") + } +} + +// TestGrepTermsFromQuery mirrors Python _grep_terms_from_query: +// bare alnum words of length>=2, deduped (order-preserving) and capped at 10. +func TestGrepTermsFromQuery(t *testing.T) { + // Proper nouns preserved; stopwords/dupes dropped; bare single chars skipped. + got := GrepTermsFromQuery("Where was Culdcept Saga made? culdcept was made by OmiyaSoft.") + want := []string{"Where", "was", "Culdcept", "Saga", "made", "by", "OmiyaSoft"} + if !reflect.DeepEqual(got, want) { + t.Errorf("terms = %v, want %v", got, want) + } + // Leading/trailing punctuation trimmed from each token. + got = GrepTermsFromQuery("apollo.-. 13 mission") + if !reflect.DeepEqual(got, []string{"apollo", "13", "mission"}) { + t.Errorf("terms = %v, want [apollo 13 mission]", got) + } + // Capped at 10. + got = GrepTermsFromQuery("a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11 a12") + if len(got) != GrepTermsMax { + t.Errorf("terms = %d, want capped at %d", len(got), GrepTermsMax) + } + // Empty/blank -> nil. + if GrepTermsFromQuery("") != nil || GrepTermsFromQuery(" ") != nil { + t.Error("blank query must yield nil terms") + } +} + +// TestGrepSearchNarrowsProseViaTermWindow mirrors Python grep_search's two +// narrowing stages: bm25_search narrows by the keywords hint first +// (search.py:grep_search via _narrow_or_keep), then the prose candidates alone are +// narrowed to the term-grep window (search.py:grep_search) while table chunks pass +// through UN-narrowed. +func TestGrepSearchNarrowsProseViaTermWindow(t *testing.T) { + // A long multi-line prose chunk: only the line carrying the term should be + // kept (the long unmatched tail is trimmed by the grep window). + prose := map[string]any{ + "chunk_id": "p1", + "content": "Alpha filler sentence about unrelated weather and clouds.\n" + + "Culdcept was made by OmiyaSoft in 1999 after the original board game.\n" + + strings.Repeat("Omega filler unrelated text about the sea and the sky. ", 20), + } + // A table chunk: >=3 pipe rows must NOT be term-narrowed. + table := map[string]any{ + "chunk_id": "t1", + "content": "team | pts | rank\nA | 10 | 1\nB | 8 | 2\nC | 5 | 3\nD | 2 | 4", + } + r := &stubRetriever{chunks: []map[string]any{prose, table}} + deps, _ := newTestSearchDeps(r) + // The query's own terms become the BM25 keywords hint (there is none here), + // so the prose only survives the FIRST stage if it carries those terms: + // "Culdcept was made" yields the bigrams "culdcept was"/"was made", which + // the prose sentence does. (With "who made Culdcept?" the hint matches the + // table alone and Python drops the prose outright — pinned by + // TestGrepSearchDerivesKeywordsHint.) + chunks, _ := GrepSearch(context.Background(), deps, SearchParams{Question: "Culdcept was made"}) + + // Order: table chunks first, then narrowed prose (Python keeps table+kept). + if len(chunks) != 2 { + t.Fatalf("chunks = %d, want 2 (table + narrowed prose)", len(chunks)) + } + if chunks[0]["chunk_id"] != "t1" { + t.Errorf("first chunk = %v, want table chunk t1", chunks[0]["chunk_id"]) + } + // The table chunk must be returned WHOLE, every row intact: Python's + // pipe-table branch returns "..." + _highlight_keywords(content) + "..." + // (text_processing.py _narrow_content), so the body is unchanged and only + // the wrapper differs from the raw chunk. + if got := ChunkTextOf(chunks[0]); !strings.Contains(got, "team | pts | rank") || !strings.Contains(got, "D | 2 | 4") { + t.Errorf("table chunk was truncated; got %q", got) + } + // The prose chunk must be narrowed to the Culdcept term window. + got := ChunkTextOf(chunks[1]) + if !strings.Contains(got, "Culdcept") { + t.Errorf("prose not narrowed to term: %q", got) + } + if strings.Contains(got, "Omega filler") { + t.Errorf("prose tail should be trimmed by the grep window: %q", got) + } + if len(got) >= len(ChunkTextOf(prose)) { + t.Errorf("prose was not truncated by the grep window: len=%d", len(got)) + } +} + +// TestGrepSearchKeepsRawCandidatesWhenNoMatch mirrors Python grep_search: when +// the term-grep matches nothing, the raw BM25 candidates are returned unchanged +// so evidence is never dropped. +func TestGrepSearchKeepsRawCandidatesWhenNoMatch(t *testing.T) { + prose := map[string]any{ + "chunk_id": "p1", + "content": "A completely unrelated sentence about weather and clouds.", + } + r := &stubRetriever{chunks: []map[string]any{prose}} + deps, _ := newTestSearchDeps(r) + chunks, _ := GrepSearch(context.Background(), deps, SearchParams{Question: "who made Culdcept?"}) + if len(chunks) != 1 || chunks[0]["chunk_id"] != "p1" { + t.Fatalf("chunks = %v, want the raw candidate preserved", chunks) + } + if ChunkTextOf(chunks[0]) != ChunkTextOf(prose) { + t.Error("unmatched prose must be returned whole, not narrowed") + } +} + +// TestGrepSearchDerivesKeywordsHint mirrors Python grep_search:421-424: with no +// explicit hint the BM25 pool is built from "query + the query's own extracted +// terms", so a long question's proper nouns stop hiding under stopwords and the +// keyword-narrowing stage runs even without a nav hint. An explicit hint (the +// nav-routed docs' summary) wins — "nav is a hint, not a constraint". +func TestGrepSearchDerivesKeywordsHint(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{{"content": "hit"}}} + deps, _ := newTestSearchDeps(r) + GrepSearch(context.Background(), deps, SearchParams{Question: "who made Culdcept?"}) + req := r.lastReq(t) + if want := "who made Culdcept? who made Culdcept"; req.Query != want { + t.Errorf("query = %q, want %q (question + derived terms)", req.Query, want) + } + if req.KeywordsSimilarityWeight != 0 || !req.ExcludeCompiled { + t.Error("grep must stay keyword-only (weight 0) and exclude compiled rows") + } + // The derived hint also drives the narrowing stage: a prose candidate whose + // sentences miss those terms is dropped, while a >=3-row pipe table is kept + // whole (Python _narrow_by_keywords + _narrow_content's table branch). + prose := map[string]any{"chunk_id": "p1", "content": "Unrelated sentence about weather."} + table := map[string]any{"chunk_id": "t1", "content": "a | b | c\nd | e | f\ng | h | i"} + r2 := &stubRetriever{chunks: []map[string]any{prose, table}} + deps2, _ := newTestSearchDeps(r2) + got, _ := GrepSearch(context.Background(), deps2, SearchParams{Question: "who made Culdcept?"}) + if len(got) != 1 || got[0]["chunk_id"] != "t1" { + t.Errorf("chunks = %v, want only the table chunk", got) + } + + // An explicit hint wins over the derived terms. + r3 := &stubRetriever{chunks: []map[string]any{{"content": "hit"}}} + deps3, _ := newTestSearchDeps(r3) + GrepSearch(context.Background(), deps3, SearchParams{Question: "who made Culdcept?", Keywords: "nav summary"}) + if got := r3.lastReq(t).Query; got != "who made Culdcept? nav summary" { + t.Errorf("query = %q, want the explicit hint appended", got) + } +} + +// TestSearchCacheIsHybridOnly mirrors Python: tools.search_cache is read and +// written by hybrid_search alone (/ :207). A keyword-only leg +// must neither serve nor be served by it — the key carries no weight, +// threshold or compiled policy, so a shared cache would hand a hybrid result +// (vector weight 0.3) to a BM25/grep call and vice versa. +func TestSearchCacheIsHybridOnly(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{{"content": "hit"}}} + deps, _ := newTestSearchDeps(r) + p := SearchParams{Question: "same query"} + HybridSearch(context.Background(), deps, p) // fills the cache + BM25Search(context.Background(), deps, p) // must not be served from it + GrepSearch(context.Background(), deps, p) // nor must this one + if len(r.requests) != 3 { + t.Fatalf("backend calls = %d, want 3 (the search cache is hybrid-only)", len(r.requests)) + } + // The hybrid leg still dedups its own repeats. + HybridSearch(context.Background(), deps, p) + if len(r.requests) != 3 { + t.Errorf("backend calls = %d, want 3 (hybrid repeat served from cache)", len(r.requests)) + } +} + +// TestHybridSearchExcludesCompiledAndWeightsThreeTenths mirrors Python +// hybrid_search: vector weight 0.3 when an embedder is configured, compiled +// rows excluded. +func TestHybridSearchExcludesCompiledAndWeightsThreeTenths(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{{"content": "x"}}} + deps, _ := newTestSearchDeps(r) + deps.HasEmbedder = true + HybridSearch(context.Background(), deps, SearchParams{Question: "q"}) + req := r.lastReq(t) + if req.KeywordsSimilarityWeight != HybridSearchDefaultVectorWeight { + t.Errorf("hybrid search weight = %v, want %v", req.KeywordsSimilarityWeight, HybridSearchDefaultVectorWeight) + } + if !req.ExcludeCompiled { + t.Error("hybrid search must exclude compiled rows") + } +} + +// TestRetrieveSearchDoesNotExcludeCompiled mirrors Python RAGTools.retrieve: +// unlike hybrid_search it does NOT exclude compiled rows, and honours +// UsingEmbedding (weight 0.7 when on). +func TestRetrieveSearchDoesNotExcludeCompiled(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{{"content": "x"}}} + deps, _ := newTestSearchDeps(r) + deps.UsingEmbedding = true + RetrieveSearch(context.Background(), deps, SearchParams{Question: "q"}) + req := r.lastReq(t) + if req.ExcludeCompiled { + t.Error("retrieve search must NOT exclude compiled rows") + } + if req.KeywordsSimilarityWeight != DefaultHybridVectorWeight { + t.Errorf("retrieve search weight = %v, want %v", req.KeywordsSimilarityWeight, DefaultHybridVectorWeight) + } +} + +// TestHybridSearchMergesSQLKBs verifies that hybrid_search folds the session's +// structured (SQL) datasets into the target id list, mirroring Python +// search.py:hybrid_search (`tools.kb_ids + [kb.id for kb in tools.sql_kbs]`). +func TestHybridSearchMergesSQLKBs(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{{"content": "x"}}} + deps, _ := newTestSearchDeps(r) + deps.SQLKBs = []string{"sqlkb1", "sqlkb2"} + HybridSearch(context.Background(), deps, SearchParams{Question: "q"}) + req := r.lastReq(t) + want := map[string]bool{"kb1": true, "sqlkb1": true, "sqlkb2": true} + if len(req.DatasetIDs) != len(want) { + t.Fatalf("expected %d dataset ids, got %v", len(want), req.DatasetIDs) + } + for _, id := range req.DatasetIDs { + if !want[id] { + t.Errorf("unexpected dataset id %q in %v", id, req.DatasetIDs) + } + } +} + +// TestNormalizeWebResults verifies the web-search payload shaper drops entries +// without a URL or content and keeps chunk_id unique per snippet. +func TestNormalizeWebResults(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var in map[string]any + _ = json.NewDecoder(r.Body).Decode(&in) + out := map[string]any{ + "chunks": []map[string]any{ + {"url": "u1", "content": "c1", "title": "t1"}, + {"url": "", "content": "c2"}, // missing url -> dropped + {"url": "u2", "content": ""}, // missing content -> dropped + {"url": "u3", "content": "c3"}, // kept + {"url": "u1", "content": "c4"}, // same url as u1 -> must keep (unique chunk_id) + }, + } + _ = json.NewEncoder(w).Encode(out) + })) + defer srv.Close() + + resp, _ := http.Post(srv.URL, "application/json", bytes.NewReader([]byte(`{}`))) + raw, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + got := normalizeWebResults(raw) + if len(got) != 3 { + t.Fatalf("got %d chunks, want 3 (u1, u3, u1-second-snippet)", len(got)) + } + + seen := map[string]int{} + for _, c := range got { + id, _ := c["chunk_id"].(string) + seen[id]++ + } + for id, n := range seen { + if n != 1 { + t.Errorf("chunk_id %q appeared %d times, must be unique", id, n) + } + } + + // Filtering of bad entries. + if c := normalizeWebResults([]byte(`{"chunks":[{"content":"no-url"}]}`)); len(c) != 0 { + t.Errorf("entry without url kept: %v", c) + } + if c := normalizeWebResults([]byte(`{"chunks":[{"url":"x"}]}`)); len(c) != 0 { + t.Errorf("entry without content kept: %v", c) + } +} + +// TestQueryToTerms pins Python _query_to_terms on the shapes the +// fan-out prefetch feeds it. The CJK case is the +// regression guard: Go's RE2 \w is ASCII-only, so tokenizing a Chinese fan-out +// with \w+ produced NO terms, leaving the BM25 leg of the fan-out without the +// keyed terms that give the discriminating entity its own score mass +// (agentic_rag_graph.py:_search_one) — the log line then read "keywords: ". +func TestQueryToTerms(t *testing.T) { + for _, c := range []struct { + name string + in string + want []string + }{ + {"cjk sentence", "关羽 斩杀 有姓名 人物 名单", []string{"关羽", "斩杀", "有姓名", "人物", "名单"}}, + // Case is preserved, as in Python (downstream matching is (?i)). + {"ascii sentence", "Culdcept Saga release date", []string{"Culdcept", "Saga", "release", "date"}}, + // Python dedups case-sensitively (tok not in terms), so both survive. + {"case-sensitive dedup", "Saga saga", []string{"Saga", "saga"}}, + {"regex alternation", `(?i)\b关羽|张飞\b`, []string{"关羽", "张飞"}}, + {"tokens below two runes dropped", "a b cd", []string{"cd"}}, + {"empty query", " ", nil}, + } { + t.Run(c.name, func(t *testing.T) { + if got := QueryToTerms(c.in); !reflect.DeepEqual(got, c.want) { + t.Errorf("QueryToTerms(%q) = %v, want %v", c.in, got, c.want) + } + }) + } + + // The fan-out's keyed subset must survive for CJK too: without it the BM25 + // leg runs the bare sentence. + if got := FanoutKeyedTerms(QueryToTerms("关羽 斩杀 有姓名 人物")); len(got) != 1 || got[0] != "有姓名" { + t.Errorf("FanoutKeyedTerms = %v, want [有姓名] (>=3 runes, non-stopword)", got) + } + // Stopwords are compared case-insensitively, so a capitalized one is dropped + // while the discriminative terms keep their case. + if got := FanoutKeyedTerms(QueryToTerms("The Culdcept Saga")); !reflect.DeepEqual(got, []string{"Culdcept", "Saga"}) { + t.Errorf("FanoutKeyedTerms = %v, want [Culdcept Saga]", got) + } + + // The exact fan-out queries of a real high-mode run ("关羽杀了多少有姓名的人?"), + // with the keywords Python's implementation produces for them (verified by + // running rag.advanced_rag.harness.tools.search._query_to_terms plus the keyed + // filter of agentic_rag_graph.py:_search_one). Note the surviving term is a generic + // long word, not the entity: Python's len>=3 rule drops every two-character + // Chinese name (关羽/华雄/颜良/文丑/蔡阳), so this is parity, not a Go bug. + for _, c := range []struct{ in, want string }{ + {"关羽 斩杀 有姓名 人物 名单", "有姓名"}, + {"关羽 斩将 记录 三国演义", "三国演义"}, + {"关羽 杀 将领 三国志", "三国志"}, + } { + if got := strings.Join(FanoutKeyedTerms(QueryToTerms(c.in)), " "); got != c.want { + t.Errorf("fan-out keywords for %q = %q, want %q (Python parity)", c.in, got, c.want) + } + } +} + +func TestAgenticVectorWeightDefaultsToZero(t *testing.T) { + // Python's agentic retrieve runs keyword-only: using_embedding defaults to + // False and no caller passes True (agentic_rag.py:retrieve, 643-646). + got := floatPtrOrDef(nil, DefaultAgenticVectorWeight) + if got != 0 { + t.Fatalf("default vector weight = %v, want 0 (keyword-only, as in Python)", got) + } + if DefaultAgenticVectorWeight != 0 { + t.Fatalf("DefaultAgenticVectorWeight = %v, want 0", DefaultAgenticVectorWeight) + } +} + +func TestVectorWeightHonoursExplicitZero(t *testing.T) { + // A pointer keeps "configured 0" distinct from "unset", so keyword-only can + // be requested explicitly rather than only by omission. + zero := 0.0 + if got := floatPtrOrDef(&zero, DefaultAgenticVectorWeight); got != 0 { + t.Fatalf("got %v, want 0", got) + } + + // Fallback must apply only when unset. + if DefaultAgenticVectorWeight != 0 { + t.Fatal("the fallback itself must stay 0 to match Python") + } +} + +func TestVectorWeightCanEnableHybrid(t *testing.T) { + // Hybrid retrieval stays available, just not by default. + hybrid := 0.3 + if got := floatPtrOrDef(&hybrid, DefaultAgenticVectorWeight); got != 0.3 { + t.Fatalf("got %v, want 0.3 when explicitly configured", got) + } +} + +func TestRetrievalDefaultsUseIntOrDef(t *testing.T) { + if got := intOrDef(0, 12); got != 12 { + t.Fatalf("intOrDef(0) = %d, want the fallback 12", got) + } + if got := intOrDef(5, 12); got != 5 { + t.Fatalf("intOrDef(5) = %d, want 5", got) + } +} + +func TestResolveVectorWeightRetrieveMirrorsUsingEmbedding(t *testing.T) { + // Python RAGTools.retrieve(using_embedding: bool = False). + // Off → keyword-only (weight 0); on → 0.7 default or the configured override. + if got := resolveVectorWeight(SearchDeps{UsingEmbedding: false}, ChannelRetrieve); got != 0 { + t.Fatalf("using_embedding=false → %v, want 0 (keyword-only)", got) + } + if got := resolveVectorWeight(SearchDeps{UsingEmbedding: true}, ChannelRetrieve); got != DefaultHybridVectorWeight { + t.Fatalf("using_embedding=true → %v, want %v", got, DefaultHybridVectorWeight) + } + override := 0.5 + if got := resolveVectorWeight(SearchDeps{UsingEmbedding: true, VectorSimilarityWeight: &override}, ChannelRetrieve); got != 0.5 { + t.Fatalf("using_embedding=true with override → %v, want 0.5", got) + } +} + +func TestResolveVectorWeightHybridDefaultsToThreeTenths(t *testing.T) { + // Python hybrid_search defaults the vector weight to 0.3 + // (_DEFAULT_HYBRID_VECTOR_WEIGHT,), unlike RAGTools.retrieve's 0.7. + if got := resolveVectorWeight(SearchDeps{HasEmbedder: true}, ChannelHybrid); got != HybridSearchDefaultVectorWeight { + t.Fatalf("hybrid → %v, want %v", got, HybridSearchDefaultVectorWeight) + } + if got := resolveVectorWeight(SearchDeps{HasEmbedder: false}, ChannelHybrid); got != 0 { + t.Fatalf("hybrid with no embedder → %v, want 0 (Python: `if embd_mdl`)", got) + } +} + +// TestResolveVectorWeightHybridIgnoresUsingEmbedding is the regression guard for +// the channel-granularity bug: Python's hybrid_search has NO using_embedding +// parameter (search.py:hybrid_search, :143-145), so gating it on that flag disabled the +// semantic leg for search_chunks — losing recall of passages sharing no surface +// words. The gate for this channel is the embedder, nothing else. +func TestResolveVectorWeightHybridIgnoresUsingEmbedding(t *testing.T) { + if got := resolveVectorWeight(SearchDeps{UsingEmbedding: false, HasEmbedder: true}, ChannelHybrid); got != HybridSearchDefaultVectorWeight { + t.Fatalf("hybrid with using_embedding=false → %v, want %v: the vector leg "+ + "must NOT depend on using_embedding", got, HybridSearchDefaultVectorWeight) + } +} + +// TestResolveVectorWeightGrepIsAlwaysZero pins Python grep_search: the retrieve +// and grep_* session tools are keyword-only and have no vector leg at all, so no +// flag can turn one on. +func TestResolveVectorWeightGrepIsAlwaysZero(t *testing.T) { + override := 0.9 + if got := resolveVectorWeight(SearchDeps{UsingEmbedding: true, HasEmbedder: true}, ChannelGrep); got != 0 { + t.Fatalf("grep → %v, want 0 (grep_search has no vector leg)", got) + } + if got := resolveVectorWeight(SearchDeps{UsingEmbedding: true, HasEmbedder: true, VectorSimilarityWeight: &override}, ChannelGrep); got != 0 { + t.Fatalf("grep with override → %v, want 0 (grep_search has no vector leg)", got) + } +} + +// stubVerifier reports a fixed known set, or fails when err is set. +type stubVerifier struct { + known map[string]bool + err error +} + +func (s stubVerifier) KnownDocIDs(_ context.Context, _, _ []string) (map[string]bool, error) { + return s.known, s.err +} + +// subsetVerifier mimics the production DocIDLookup.KnownDocIDs: it returns only +// the candidates that are in knownDocs, so an unknown/foreign document yields +// an empty map rather than a false entry. The fixed-set stubVerifier above +// cannot reproduce that empty-map path, which is exactly where the foreign-doc +// rejection used to regress. +type subsetVerifier struct { + knownDocs map[string]bool +} + +func (s subsetVerifier) KnownDocIDs(_ context.Context, _ []string, candidates []string) (map[string]bool, error) { + out := make(map[string]bool, len(candidates)) + for _, c := range candidates { + if s.knownDocs[c] { + out[c] = true + } + } + return out, nil +} + +func TestResolveDocScopeKeepsKnownIDs(t *testing.T) { + got := resolveDocScope(context.Background(), SearchDeps{ + DocIDVerifier: stubVerifier{known: map[string]bool{"a": true}}, + }, []string{"a", "b"}, []string{"kb"}, _LOG) + + if len(got) != 1 || got[0] != "a" { + t.Fatalf("scope = %v, want [a]", got) + } +} + +func TestResolveDocScopeDropsScopeWhenAllUnknown(t *testing.T) { + // Python retrieve:633-635 — an entirely bogus scope falls back to + // unfiltered retrieval instead of returning nothing. + got := resolveDocScope(context.Background(), SearchDeps{ + DocIDVerifier: stubVerifier{known: map[string]bool{"z": true}}, + }, []string{"a", "b"}, []string{"kb"}, _LOG) + + if got != nil { + t.Fatalf("scope = %v, want nil (unfiltered)", got) + } +} + +func TestResolveDocScopePassthroughWithoutVerifier(t *testing.T) { + scope := []string{"a", "b"} + got := resolveDocScope(context.Background(), SearchDeps{}, scope, []string{"kb"}, _LOG) + + if len(got) != len(scope) { + t.Fatalf("scope = %v, want %v unchanged", got, scope) + } +} + +func TestResolveDocScopePassthroughOnVerifierError(t *testing.T) { + scope := []string{"a"} + got := resolveDocScope(context.Background(), SearchDeps{ + DocIDVerifier: stubVerifier{err: errors.New("db down")}, + }, scope, []string{"kb"}, _LOG) + + if len(got) != 1 { + t.Fatalf("scope = %v, want %v (verification unavailable)", got, scope) + } +} + +func TestDocInDatasetsRejectsForeignDocument(t *testing.T) { + belongs, verified := docInDatasets(context.Background(), SearchDeps{ + DocIDVerifier: stubVerifier{known: map[string]bool{"other": true}}, + }, "doc") + + if !verified || belongs { + t.Fatalf("belongs=%v verified=%v, want false/true (doc outside the datasets)", belongs, verified) + } +} + +func TestDocInDatasetsAcceptsOwnDocument(t *testing.T) { + belongs, verified := docInDatasets(context.Background(), SearchDeps{ + DocIDVerifier: stubVerifier{known: map[string]bool{"doc": true}}, + }, "doc") + + if !verified || !belongs { + t.Fatalf("belongs=%v verified=%v, want true/true", belongs, verified) + } +} + +func TestDocInDatasetsUnverifiedWithoutVerifier(t *testing.T) { + // Without a verifier the caller must keep the previous behaviour instead of + // rejecting the document. + belongs, verified := docInDatasets(context.Background(), SearchDeps{}, "doc") + + if !belongs || verified { + t.Fatalf("belongs=%v verified=%v, want true/false", belongs, verified) + } +} + +func TestDocInDatasetsUnverifiedOnError(t *testing.T) { + belongs, verified := docInDatasets(context.Background(), SearchDeps{ + DocIDVerifier: stubVerifier{err: errors.New("db down")}, + }, "doc") + + if !belongs || verified { + t.Fatalf("belongs=%v verified=%v, want true/false (lookup failed)", belongs, verified) + } +} + +type stubNavRouter struct { + called bool + docs [][2]string + // scope records the doc scope the router was asked to route within. + scope []string +} + +func (s *stubNavRouter) Route(_ context.Context, _, _, _ string, docScope []string, _ int) ([][2]string, error) { + s.called = true + s.scope = append([]string(nil), docScope...) + return s.docs, nil +} + +func TestDocInDatasetsRejectsForeignDocumentViaSubsetVerifier(t *testing.T) { + belongs, verified := docInDatasets(context.Background(), SearchDeps{ + DocIDVerifier: subsetVerifier{knownDocs: map[string]bool{"other": true}}, + KbIDs: []string{"kb"}, + }, "doc") + + if !verified || belongs { + t.Fatalf("belongs=%v verified=%v, want false/true (foreign doc rejected even with empty known map)", belongs, verified) + } +} + +// TestResolveDocScopeDropsScopeWhenAllUnknownViaSubsetVerifier exercises the +// production empty-map path: when every candidate is foreign the verifier +// returns an empty map (no error). The scope must be dropped (unfiltered +// retrieval, mirroring Python retrieve's fall-back), not passed through. +func TestResolveDocScopeDropsScopeWhenAllUnknownViaSubsetVerifier(t *testing.T) { + got := resolveDocScope(context.Background(), SearchDeps{ + DocIDVerifier: subsetVerifier{knownDocs: map[string]bool{"z": true}}, + KbIDs: []string{"kb"}, + }, []string{"a", "b"}, []string{"kb"}, _LOG) + + if got != nil { + t.Fatalf("scope = %v, want nil (unfiltered)", got) + } +} + +// TestResolveDocScopeEmptyWhenCeilingRemovesEveryID pins the ceiling's hard +// edge: when the session doc_scope removes every requested id the result is +// EMPTY (match nothing), never unfiltered. Python's falsy-empty quirk would fall +// through to unfiltered retrieval here; Go deliberately keeps the ceiling +// absolute. +func TestResolveDocScopeEmptyWhenCeilingRemovesEveryID(t *testing.T) { + got := resolveDocScope(context.Background(), SearchDeps{ + DocIDVerifier: subsetVerifier{knownDocs: map[string]bool{"sess1": true}}, + KbIDs: []string{"kb"}, + DocScope: []string{"sess1"}, // fixed session base scope + }, []string{"a", "b"}, []string{"kb"}, _LOG) + + if got == nil || len(got) != 0 { + t.Fatalf("scope = %v, want non-nil empty (ceiling removed every requested id)", got) + } +} + +// TestResolveDocScopeEmptyWhenSessionScopeSetAndAllUnknown pins Python +// retrieve:631-632 — when the session has a fixed base doc_scope and the +// requested ids survive the ceiling but do not resolve, the result is EMPTY, +// never unfiltered. Encoded as a non-nil empty slice. +func TestResolveDocScopeEmptyWhenSessionScopeSetAndAllUnknown(t *testing.T) { + got := resolveDocScope(context.Background(), SearchDeps{ + DocIDVerifier: subsetVerifier{knownDocs: map[string]bool{"elsewhere": true}}, + KbIDs: []string{"kb"}, + DocScope: []string{"sess1"}, // fixed session base scope + }, []string{"sess1", "sess2"}, []string{"kb"}, _LOG) + + if got == nil || len(got) != 0 { + t.Fatalf("scope = %v, want non-nil empty (Python returns empty result, not unfiltered)", got) + } +} + +// TestResolveDocScopeFallsBackToSessionScopeWhenRequestNone pins Python's +// scoped_doc_ids fallback (retrieve:620): a None request scope falls back to the +// session's fixed doc_scope before ownership verification. +func TestResolveDocScopeFallsBackToSessionScopeWhenRequestNone(t *testing.T) { + got := resolveDocScope(context.Background(), SearchDeps{ + DocIDVerifier: subsetVerifier{knownDocs: map[string]bool{"sess1": true}}, + KbIDs: []string{"kb"}, + DocScope: []string{"sess1"}, // fixed session base scope + }, nil, []string{"kb"}, _LOG) // request scope None + + if len(got) != 1 || got[0] != "sess1" { + t.Fatalf("scope = %v, want [sess1] (request None falls back to session scope)", got) + } +} + +// TestResolveDocScopeUnfilteredWhenNoScopeAtAll pins that a nil request scope +// AND no session base scope searches unfiltered (doc_scope = None), encoded as +// nil — never a non-nil empty slice, which the backend would read as +// "match nothing". +func TestResolveDocScopeUnfilteredWhenNoScopeAtAll(t *testing.T) { + got := resolveDocScope(context.Background(), SearchDeps{ + DocIDVerifier: subsetVerifier{knownDocs: map[string]bool{"z": true}}, + KbIDs: []string{"kb"}, + }, nil, []string{"kb"}, _LOG) + + if got != nil { + t.Fatalf("scope = %v, want nil (unfiltered)", got) + } +} + +// TestScopedDocIDsMirrorsPythonCeiling pins RAGTools.scoped_doc_ids +// (agentic_rag.py:scoped_doc_ids): no session scope → the caller's scope as-is; a +// session scope with no caller scope → the session scope; both → the +// intersection. +func TestScopedDocIDsMirrorsPythonCeiling(t *testing.T) { + cases := []struct { + name string + session []string + scope []string + want []string + }{ + {"no session scope passes through", nil, []string{"a", "b"}, []string{"a", "b"}}, + {"session scope with no caller scope", []string{"s1"}, nil, []string{"s1"}}, + {"explicit scope is intersected", []string{"s1", "s2"}, []string{"s2", "x"}, []string{"s2"}}, + {"disjoint ceiling empties the scope", []string{"s1"}, []string{"x"}, []string{}}, + } + for _, c := range cases { + got := scopedDocIDs(c.session, c.scope) + if len(got) != len(c.want) { + t.Fatalf("%s: scopedDocIDs = %v, want %v", c.name, got, c.want) + } + for i := range got { + if got[i] != c.want[i] { + t.Fatalf("%s: scopedDocIDs = %v, want %v", c.name, got, c.want) + } + } + } +} + +// TestResolveDocScopeIntersectsExplicitScopeWithSession pins that a +// model-generated scope can never escape the session's document ceiling: it is +// intersected with it, not used as-is. +func TestResolveDocScopeIntersectsExplicitScopeWithSession(t *testing.T) { + got := resolveDocScope(context.Background(), SearchDeps{ + DocIDVerifier: subsetVerifier{knownDocs: map[string]bool{"sess1": true, "other": true}}, + KbIDs: []string{"kb"}, + DocScope: []string{"sess1"}, // session ceiling + }, []string{"other", "sess1"}, []string{"kb"}, _LOG) + + if len(got) != 1 || got[0] != "sess1" { + t.Fatalf("scope = %v, want [sess1] (explicit scope must be ceilinged by the session scope)", got) + } +} diff --git a/internal/rag/advanced_rag/harness/tool_text_processing.go b/internal/rag/advanced_rag/harness/tool_text_processing.go new file mode 100644 index 00000000000..7438cff69e1 --- /dev/null +++ b/internal/rag/advanced_rag/harness/tool_text_processing.go @@ -0,0 +1,667 @@ +// +// 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. +// + +package harness + +import ( + "crypto/md5" + "fmt" + "log" + "regexp" + "slices" + "sort" + "strings" +) + +// Text processing: keyword narrowing of retrieved chunks. +// +// Mirrors Python harness/tools/text_processing.py (_narrow_or_keep / +// _narrow_by_keywords / _narrow_content / _narrow_by_terms) and the +// compiled-structure grep_sed narrowing (_narrow_content) that sits alongside +// it in the Python module. In Go this lives next to search.go so the only two +// consumers (HybridSearch and the structure-nav grepper) both reach it. + +// NarrowOrKeep mirrors Python text_processing._narrow_or_keep: narrow chunks to +// keyword-bearing sentences, but keep the originals when narrowing would drop +// everything. +// +// The all-or-nothing behaviour is the point: no keyword overlap does NOT mean +// irrelevant. The retriever already ranked these chunks, and a sub-question's +// wording need not contain the parent question's keywords. Dropping them all +// produced empty results, unverified claims and pointless retry cycles. +func NarrowOrKeep(chunks []map[string]any, keywords, label string, logger *log.Logger) []map[string]any { + if strings.TrimSpace(keywords) == "" || len(chunks) == 0 { + return chunks + } + if logger == nil { + logger = _LOG + } + narrowed := NarrowByKeywords(chunks, keywords) + if len(narrowed) > 0 { + logger.Printf("[%s] Kept %d of %d passage(s) that actually mention the keywords.", label, len(narrowed), len(chunks)) + return narrowed + } + logger.Printf("[%s] Keyword narrowing matched nothing — keeping all %d retrieved passage(s).", label, len(chunks)) + return chunks +} + +// NarrowByKeywords narrows each chunk to the sentences mentioning any keyword +// (+/-1 neighbour) and drops keyword-less chunks. +// +// Mirrors Python _narrow_by_keywords. Unlike NarrowOrKeep this is the strict +// form: it may return an empty slice, and callers that must not lose evidence +// should use NarrowOrKeep instead. +func NarrowByKeywords(chunks []map[string]any, keywords string) []map[string]any { + kwds := SplitKeywords(keywords) + // Python _narrow_by_keywords returns the input + // unchanged when there is nothing to narrow on: `if not kwds or not chunks: + // return chunks`. A nil return would wipe the whole evidence pool, so return + // the original chunks verbatim instead. + if len(kwds) == 0 || len(chunks) == 0 { + return chunks + } + out := make([]map[string]any, 0, len(chunks)) + seen := make(map[string]bool, len(chunks)) + for _, c := range chunks { + if c == nil { + continue + } + narrowed, ok := NarrowContent(ChunkTextOf(c), kwds) + if !ok { + continue + } + // Dedup identical narrowed passages (mirrors Python _narrow_by_keywords, + // which drops chunks whose narrowed text hashes the same). + h := md5.Sum([]byte(narrowed)) + key := fmt.Sprintf("%x", h) + if seen[key] { + continue + } + seen[key] = true + cp := make(map[string]any, len(c)+1) + for k, v := range c { + cp[k] = v + } + // Mirror Python _narrow_by_keywords exactly: content_with_weight is + // always overwritten with the narrowed text, "content" is mirrored ONLY + // when the original chunk already carried a "content" key, and the + // pre-narrow "highlight" spans are dropped because they no longer apply. + // (withNarrowedText in grep_sed_narrow.go applies the identical rule for + // the term path; keep the two in lock-step.) + cp["content_with_weight"] = narrowed + if _, ok := cp["content"]; ok { + cp["content"] = narrowed + } + delete(cp, "highlight") + out = append(out, cp) + } + return out +} + +// SplitKeywords normalizes a keyword string into search terms. When fewer than +// 3 comma terms exist, falls back to space-split bigrams — a bare keyword blob +// ("finale run time") is more discriminative as bigrams than as single words. +// Mirrors Python _narrow_by_keywords' term construction. +func SplitKeywords(keywords string) []string { + if strings.TrimSpace(keywords) == "" { + return nil + } + kwds := make([]string, 0, 8) + for _, k := range strings.Split(keywords, ",") { + if k = strings.TrimSpace(k); k != "" { + kwds = append(kwds, strings.ToLower(k)) + } + } + if len(kwds) < 3 { + words := make([]string, 0, 8) + for _, w := range strings.Fields(keywords) { + words = append(words, strings.ToLower(w)) + } + bigrams := make([]string, 0, len(words)) + for i := 0; i+1 < len(words); i++ { + bigrams = append(bigrams, words[i]+" "+words[i+1]) + } + if len(bigrams) > 0 { + return bigrams + } + } + return kwds +} + +// --------------------------------------------------------------------------- +// Stem-aware keyword matching (Python _keyword_forms / _sentence_stems / +// _sentence_matches / _stem). When nltk is unavailable Python falls back to a +// suffix-stripping stemmer; Go always uses that fallback (no nltk dependency), +// so behaviour matches Python's no-nltk path. +// --------------------------------------------------------------------------- + +var wordRe = regexp.MustCompile("[a-z0-9]+") + +// stemSuffixes mirrors Python _STEM_SUFFIXES (longest-first; first match wins). +var stemSuffixes = [][2]string{ + {"ations", ""}, {"ation", ""}, {"ated", ""}, {"ates", ""}, {"ate", ""}, + {"ings", ""}, {"ing", ""}, {"ies", "i"}, {"ied", "i"}, {"ed", ""}, {"es", ""}, {"s", ""}, +} + +func isAlphaOnly(s string) bool { + for _, r := range s { + if !((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z')) { + return false + } + } + return true +} + +// stemmable mirrors Python _stemmable: len>=4 and purely ASCII letters. +func stemmable(token string) bool { return len(token) >= 4 && isAlphaOnly(token) } + +func isVowelRune(r rune) bool { + switch r { + case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U': + return true + } + return false +} + +// fallbackStem mirrors Python _fallback_stem. +func fallbackStem(word string) string { + w := word + for _, suf := range stemSuffixes { + s, rep := suf[0], suf[1] + if strings.HasSuffix(w, s) && len(w)-len(s) >= 3 { + w = w[:len(w)-len(s)] + rep + break + } + } + if len(w) > 3 && strings.HasSuffix(w, "y") { + w = w[:len(w)-1] + "i" + } + if len(w) > 3 && strings.HasSuffix(w, "e") { + w = w[:len(w)-1] + } + if len(w) > 3 { + rb := []rune(w) + if rb[len(rb)-1] == rb[len(rb)-2] && !isVowelRune(rb[len(rb)-1]) { + w = string(rb[:len(rb)-1]) + } + } + return w +} + +// stem is Python _stem: nltk PorterStemmer when available, else fallbackStem. +func stem(word string) string { return fallbackStem(word) } + +// keywordForms mirrors Python _keyword_forms: verbatim keeps forms containing +// any non-stemmable token (matched by substring); stemmed holds all-ASCII-letter +// keyword forms as stem tuples (matched by a contiguous stem sequence). +func keywordForms(kwds []string) (verbatim []string, stemmed [][]string) { + for _, kw := range kwds { + k := strings.ToLower(strings.TrimSpace(kw)) + if k == "" { + continue + } + tokens := wordRe.FindAllString(k, -1) + if len(tokens) > 0 && allStemmable(tokens) { + seq := make([]string, len(tokens)) + for i, t := range tokens { + seq[i] = stem(t) + } + stemmed = append(stemmed, seq) + } else { + verbatim = append(verbatim, k) + } + } + return +} + +func allStemmable(tokens []string) bool { + for _, t := range tokens { + if !stemmable(t) { + return false + } + } + return true +} + +// sentenceStems mirrors Python _sentence_stems. +func sentenceStems(sentence string) []string { + tokens := wordRe.FindAllString(strings.ToLower(sentence), -1) + out := make([]string, len(tokens)) + for i, t := range tokens { + if stemmable(t) { + out[i] = stem(t) + } else { + out[i] = t + } + } + return out +} + +// sentenceMatches mirrors Python _sentence_matches: any verbatim substring OR a +// contiguous stemmed sequence. +func sentenceMatches(low string, stems, verbatim []string, stemmed [][]string) bool { + for _, v := range verbatim { + if strings.Contains(low, v) { + return true + } + } + for _, seq := range stemmed { + width := len(seq) + if width == 0 || width > len(stems) { + continue + } + for start := 0; start+width <= len(stems); start++ { + if slices.Equal(stems[start:start+width], seq) { + return true + } + } + } + return false +} + +// NarrowContent returns the keyword-bearing sentences (+/-2 neighbours) with +// the keywords highlighted, or ("", false) when no keyword occurs. +// Mirrors Python _narrow_content: matching keeps keyword sentences within a +// +/-2 window, AND fact-dense sentences (numbers / years / percentages / proper +// nouns) are kept within a +/-1 window even without a keyword hit, so numeric or +// named-entity answers survive narrowing. Block-level tables and markdown +// pipe-tables (>=3 rows) are returned whole — keyword-window narrowing would +// otherwise truncate them. +func NarrowContent(content string, kwds []string) (string, bool) { + if strings.TrimSpace(content) == "" || len(kwds) == 0 { + return "", false + } + lowContent := strings.ToLower(content) + if strings.Contains(lowContent, "= 2 { + pipeRows++ + } + } + if pipeRows >= 3 { + return "..." + HighlightKeywords(content, kwds) + "...", true + } + sents := SplitSentences(content) + if len(sents) == 0 { + return "", false + } + verbatim, stemmed := keywordForms(kwds) + keep := make(map[int]bool, len(sents)) + matched := false + for i, s := range sents { + low := strings.ToLower(s) + hit := sentenceMatches(low, sentenceStems(s), verbatim, stemmed) + if hit { + matched = true + for j := max(0, i-2); j < min(len(sents), i+3); j++ { + keep[j] = true + } + } else if IsFactDenseSentence(s) { + // Keep fact-dense sentences even without a keyword hit so the answer + // value (a bare figure, a date, a proper noun) is never lost. + for j := max(0, i-1); j < min(len(sents), i+2); j++ { + keep[j] = true + } + } + } + if !matched { + return "", false + } + var b strings.Builder + for i := range sents { + if keep[i] { + b.WriteString(sents[i]) + } + } + return "..." + HighlightKeywords(b.String(), kwds) + "...", true +} + +// HighlightKeywords wraps keyword occurrences in , longest term first so a +// longer keyword is not partially consumed by a shorter one. +func HighlightKeywords(text string, kwds []string) string { + if len(kwds) == 0 { + return text + } + terms := append([]string(nil), kwds...) + // Stem-based highlight terms: a stemmed form that matches in the text is + // wrapped too, mirroring Python _highlight_keywords (which adds stemmed-word + // occurrences so e.g. "nominated" is highlighted for keyword "nominations"). + _, stemmed := keywordForms(kwds) + if len(stemmed) > 0 { + stemSet := make(map[string]bool, 8) + for _, seq := range stemmed { + for _, s := range seq { + stemSet[s] = true + } + } + for _, word := range wordRe.FindAllString(text, -1) { + low := strings.ToLower(word) + if stemmable(low) && stemSet[stem(low)] { + terms = append(terms, low) + } + } + } + sort.SliceStable(terms, func(i, j int) bool { return len(terms[i]) > len(terms[j]) }) + var b strings.Builder + low := strings.ToLower(text) + i := 0 + for i < len(text) { + best := -1 + bestLen := 0 + for _, t := range terms { + if t == "" { + continue + } + if strings.HasPrefix(low[i:], t) && len(t) > bestLen { + best, bestLen = i, len(t) + } + } + if best < 0 { + b.WriteByte(text[i]) + i++ + continue + } + b.WriteString("") + b.WriteString(text[i : i+bestLen]) + b.WriteString("") + i += bestLen + } + return b.String() +} + +// IsFactDenseSentence reports whether a sentence carries a fact-bearing signal: a +// number / year / percentage / magnitude word (_FACT_RE) or a proper noun that is +// not part of an abbreviation run. Mirrors Python _is_fact_dense_sentence +// (text_processing.py:_is_fact_dense_sentence): it keeps only informative sentences when narrowing / +// grepping, so a numeric or entity answer is never dropped just because it lacks +// the query keywords. Unlike the previous port it has NO quoted-span or ≥6-token +// rule and does not treat any bare digit as a fact signal — those widened the +// gate well beyond Python. +func IsFactDenseSentence(s string) bool { + s = strings.TrimSpace(s) + if s == "" { + return false + } + // Python: `_FACT_RE.search(sent) or _FACT_RE.search(sent.lower())`. The regex + // is re.IGNORECASE so a single (?i) search is equivalent. + if factPattern.MatchString(s) { + return true + } + if hasProperNoun(s) { + return true + } + return false +} + +var ( + // factPattern mirrors Python _FACT_RE: a number that + // may carry an ordinal suffix (st/nd/rd/th) or a percent sign and may use + // comma/dot group separators, a 1900-2099 four-digit year, or a magnitude + // word (percent/million/billion/thousand/km/km2/sq km/m above/m). re.IGNORECASE + // makes the words case-insensitive. + factPattern = regexp.MustCompile(`(?i)(?:\d[\d,\.]*(?:st|nd|rd|th)?%?)|(?:19|20)\d{2}|\b(?:percent|percentage|million|billion|thousand|km|km2|sq\s*km|m\s*above|m)\b`) + + // properNounPattern mirrors Python _PROPER_NOUN_RE's word pattern: a + // capitalized word of at least three letters. Python wraps it in the negative + // lookbehind (?= 2 && (s[idx-2] == '.' || s[idx-2] == '!' || s[idx-2] == '?') && s[idx-1] == '.' { + continue + } + return true + } + return false +} + +// --------------------------------------------------------------------------- +// Sentence segmentation (Python tools/text_processing.py::_split_sentences). +// +// The foundation for every narrowing / highlighting / fact-density step in the +// harness. Two properties matter: +// +// 1. terminators (。!?;!?; and a digit-guarded English period) are KEPT on +// their sentence, so "3.14" and "v1.2" do not split; +// 2. block-level HTML elements (table/div/p/ul/li/... — see htmlBlockTags) and +// markdown tables are ATOMIC and never split internally, so a whole table / +// list / block counts as ONE "sentence" for keyword matching (a keyword +// inside one keeps the whole block). This mirrors Python's nesting-aware +// _html_block_spans, not a bare regex. +// +// Go's RE2 lacks lookbehind, so the digit guard is a manual scan rather than a +// regex assertion. +// --------------------------------------------------------------------------- + +// htmlBlockTags are the block-level HTML containers kept atomic during sentence +// splitting. Mirrors Python _HTML_BLOCK_TAGS (inline tags like // are +// deliberately excluded so ordinary prose still splits). +var htmlBlockTags = map[string]bool{ + "table": true, "thead": true, "tbody": true, "tfoot": true, "tr": true, + "td": true, "th": true, "caption": true, "colgroup": true, "ul": true, + "ol": true, "li": true, "dl": true, "dt": true, "dd": true, "div": true, + "p": true, "pre": true, "blockquote": true, "section": true, "article": true, + "aside": true, "nav": true, "main": true, "figure": true, "figcaption": true, + "header": true, "footer": true, "address": true, "details": true, "summary": true, + "form": true, "fieldset": true, "h1": true, "h2": true, "h3": true, "h4": true, + "h5": true, "h6": true, +} + +var htmlTagRe = regexp.MustCompile(`(?i)<(/?)([a-zA-Z][a-zA-Z0-9]*)\b([^>]*)>`) + +// mdTableRe mirrors Python _MD_TABLE: header row with a pipe, a separator row +// of dashes/colons/pipes, then zero+ body rows with a pipe. +var mdTableRe = regexp.MustCompile("(?m)^[ \t]*\\|?[^\n]*\\|[\n][ \t]*\\|?[ \t]*:?-{1,}:?[ \t]*(?:\\|[ \t]*:?-{1,}:?[ \t]*)+\\|?[ \t]*\r?\n(?:[ \t]*\\|?[^\n]*\\|[^\n]*\r?\n?)*") + +// htmlBlockSpans returns outermost balanced block-level HTML element spans +// (nesting-aware) via a tag stack, mirroring Python _html_block_spans. +func htmlBlockSpans(text string) [][2]int { + type stackItem struct { + name string + start int + } + var spans [][2]int + var stack []stackItem + for _, m := range htmlTagRe.FindAllStringSubmatchIndex(text, -1) { + name := strings.ToLower(text[m[4]:m[5]]) + if !htmlBlockTags[name] { + continue + } + closing := m[2] != -1 && m[2] != m[3] // group 1 captured => closing tag + if closing { + for i := len(stack) - 1; i >= 0; i-- { + if stack[i].name == name { + start := stack[i].start + stack = stack[:i] + if len(stack) == 0 { // closed an outermost block + spans = append(spans, [2]int{start, m[1]}) + } + break + } + } + } else { + attrs := text[m[6]:m[7]] + if strings.HasSuffix(strings.TrimSpace(attrs), "/") { + continue // self-closing + } + stack = append(stack, stackItem{name: name, start: m[2]}) + } + } + return spans +} + +// protectedSpans returns non-overlapping atomic (start, end) spans in order, +// covering block-level HTML elements and markdown tables, mirroring Python +// _protected_spans (overlaps are unioned). +func protectedSpans(text string) [][2]int { + spans := htmlBlockSpans(text) + for _, m := range mdTableRe.FindAllStringIndex(text, -1) { + spans = append(spans, [2]int{m[0], m[1]}) + } + sort.Slice(spans, func(i, j int) bool { return spans[i][0] < spans[j][0] }) + var merged [][2]int + lastEnd := -1 + for _, s := range spans { + if s[0] < lastEnd { // overlaps an already-kept span -> union it in + if s[1] > lastEnd { + merged[len(merged)-1][1] = s[1] + lastEnd = s[1] + } + continue + } + merged = append(merged, s) + lastEnd = s[1] + } + return merged +} + +// SplitSentences splits text into sentences, treating each block-level HTML +// element and markdown table as one atomic unit. Mirrors Python _split_sentences. +func SplitSentences(text string) []string { + if text == "" { + return nil + } + spans := protectedSpans(text) + if len(spans) == 0 { + return splitPlainSentences(text) + } + var sents []string + pos := 0 + for _, m := range spans { + if m[0] > pos { + sents = append(sents, splitPlainSentences(text[pos:m[0]])...) + } + if block := text[m[0]:m[1]]; strings.TrimSpace(block) != "" { + sents = append(sents, block) + } + pos = m[1] + } + if pos < len(text) { + sents = append(sents, splitPlainSentences(text[pos:])...) + } + return sents +} + +// splitPlainSentences splits plain text (no table/block spans) into sentences, +// keeping each terminator attached and guarding decimal periods. Operates on +// runes; rune indices == byte indices for the ASCII terminators we emit. +// +// The split is LOSSLESS: inter-sentence whitespace is kept as the prefix of the +// FOLLOWING sentence (only whitespace-only segments are dropped), so +// `"".join(sents)` reproduces the input. Python's _split_plain has the same +// property and _narrow_content depends on it — it rejoins the kept sentences +// with "" (text_processing.py), and trimming each sentence there would collapse +// a multi-line chunk into one line, which the grep term-window (line-based) +// then matches wholesale instead of line by line. Observed as the grep leg +// keeping an entire trailing paragraph Python drops. +func splitPlainSentences(text string) []string { + rs := []rune(text) + var sents []string + start := 0 + for i := 0; i < len(rs); i++ { + r := rs[i] + if !isSentTerminator(r) { + continue + } + // ASCII period guarded against decimals (digit on BOTH sides). + if r == '.' && i > 0 && i+1 < len(rs) && isASCIIDigit(rs[i-1]) && isASCIIDigit(rs[i+1]) { + continue + } + // Consume a run of terminators (e.g. "。!?" or "..."). + j := i + 1 + for j < len(rs) && isSentTerminator(rs[j]) && rs[j] != '.' { + j++ + } + seg := string(rs[start:j]) + if strings.TrimSpace(seg) != "" { + sents = append(sents, seg) + } + start = j + i = j - 1 + } + if start < len(rs) { + if tail := string(rs[start:]); strings.TrimSpace(tail) != "" { + sents = append(sents, tail) + } + } + return sents +} + +func isSentTerminator(r rune) bool { + switch r { + case '。', '!', '?', ';', '!', '?', ';', '.': + return true + } + return false +} + +func isASCIIDigit(r rune) bool { return r >= '0' && r <= '9' } + +// --------------------------------------------------------------------------- +// Keyword compaction (Python tools/text_processing.py::_compact_keywords). +// +// Mirrors RAGTools.extract_keywords' post-processing: dedupe (preserving order) +// and cap the compacted keyword string at compactMaxKeywords terms. The +// extraction prompt asks for 3-10 terms PLUS 2-3 synonyms each, which models +// answer with a 40-60 word redundant synonym run; appending that whole run onto +// the query diluted the vector leg and dragged BM25 onto unrelated docs. This +// keeps the recall terms but drops the redundancy, so keywords stay a compact +// hint instead of a pollution source. +// +// In Python _compact_keywords lives in harness/tools/text_processing.py; the Go +// port keeps it here for the same reason — it is a text-processing primitive of +// the harness, not an agentic-pipe stage. +// --------------------------------------------------------------------------- + +// compactMaxKeywords caps the compacted keyword string. Mirrors Python +// _compact_keywords(max_terms=15). +const compactMaxKeywords = 15 + +// CompactKeywords mirrors Python harness/tools/text_processing.py::_compact_keywords: +// dedupe (preserving order) and cap at compactMaxKeywords. +// +// Accepts both space- and comma-separated input (single-turn extract_keywords +// emits spaces; multi-turn formalize emits commas). +func CompactKeywords(kw string) string { + if strings.TrimSpace(kw) == "" { + return "" + } + var seen []string + for _, t := range regexp.MustCompile(`[,\s]+`).Split(strings.TrimSpace(kw), -1) { + t = strings.TrimSpace(t) + if t == "" || containsStr(seen, t) { + continue + } + seen = append(seen, t) + if len(seen) >= compactMaxKeywords { + break + } + } + return strings.Join(seen, " ") +} diff --git a/internal/rag/advanced_rag/harness/tool_text_processing_test.go b/internal/rag/advanced_rag/harness/tool_text_processing_test.go new file mode 100644 index 00000000000..e6fffef1aa9 --- /dev/null +++ b/internal/rag/advanced_rag/harness/tool_text_processing_test.go @@ -0,0 +1,279 @@ +// +// 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. +// + +package harness + +import ( + "regexp" + "strings" + "testing" + "unicode/utf8" +) + +func TestEscapeTermAsciiWord(t *testing.T) { + got := EscapeTerm("cat") + if got != `\bcat\b` { + t.Errorf("EscapeTerm(cat) = %q, want \\bcat\\b (case-insensitivity is added by TermsToPatterns via (?i))", got) + } + if _, err := regexp.Compile(got); err != nil { + t.Errorf("bad regexp: %v", err) + } +} + +func TestEscapeTermCJK(t *testing.T) { + got := EscapeTerm("机器") + if got != "机器" { + t.Errorf("EscapeTerm(机器) = %q, want bare CJK", got) + } + if _, err := regexp.Compile(got); err != nil { + t.Errorf("bad regexp: %v", err) + } +} + +func TestEscapeTermSymbols(t *testing.T) { + got := EscapeTerm("c++") + // + is regex-special -> escaped to "\+". + if got != `c\+\+` { + t.Errorf("EscapeTerm(c++) = %q, want c\\+\\+", got) + } + re, err := regexp.Compile(got) + if err != nil { + t.Errorf("bad regexp: %v", err) + } + if !re.MatchString("c++") { + t.Error("pattern should match literal c++") + } + if re.MatchString("c--") { + t.Error("pattern should NOT match c--") + } +} + +func TestEscapeTermEmpty(t *testing.T) { + if EscapeTerm("") != "" { + t.Error("empty term must stay empty so TermsToPatterns can skip it") + } +} + +func TestTermsToPatternsCapsAndSkipsEmpty(t *testing.T) { + // 40 terms -> capped at maxGrepTerms (16); empties skipped. + terms := make([]string, 40) + for i := range terms { + terms[i] = "t" + } + pats := TermsToPatterns(terms) + if len(pats) != maxGrepTerms { + t.Errorf("len = %d, want capped at %d", len(pats), maxGrepTerms) + } + // Mixed empties (whitespace) are skipped. + pats = TermsToPatterns([]string{"", " ", ",,,", "cat"}) + if len(pats) != 1 { + t.Errorf("len = %d, want 1 (only 'cat' compiles)", len(pats)) + } +} + +// mustNarrow is a convenience for the full NarrowByTerms signature with the +// default context and caps used by the term path. +func mustNarrow(chunks []map[string]any, terms, fallbackTerms []string, keywords string) NarrowResult { + return NarrowByTerms(chunks, terms, fallbackTerms, keywords, NarrowContext{Before: 2, After: 2}, defaultOutCharsPerChunk, defaultOutTotalChars) +} + +func TestNarrowByTermsKeepsAllChunks(t *testing.T) { + // NarrowByTerms NEVER drops a chunk: short chunks are kept whole, long ones + // are narrowed to the hit window. Only Matched / the returned text vary. + chunks := []map[string]any{ + {"content": "Culdcept was made by OmiyaSoft in 1999."}, + {"content": "The weather is nice today."}, + {"content": "OmiyaSoft released Culdcept."}, + } + res := mustNarrow(chunks, []string{"culdcept", "omiya"}, nil, "") + if len(res.Kept) != len(chunks) { + t.Fatalf("Kept len = %d, want all %d kept", len(res.Kept), len(chunks)) + } + if !res.Stats.Matched { + t.Error("Matched = false, want true (terms hit)") + } + if res.Stats.ChunksKpt != len(chunks) { + t.Errorf("ChunksKpt = %d, want %d", res.Stats.ChunksKpt, len(chunks)) + } +} + +func TestNarrowByTermsFallbackTermsTriedOnNoPrimaryHit(t *testing.T) { + // Primary terms hit nothing -> the fallback term list is tried mechanically. + chunks := []map[string]any{ + {"content": "Culdcept was made by OmiyaSoft."}, + {"content": "The weather is nice today."}, + } + res := mustNarrow(chunks, []string{"zzzz"}, []string{"culdcept"}, "") + if !res.Stats.Matched { + t.Error("Matched = false, want true after the fallback term path hit") + } + if len(res.Kept) != len(chunks) { + t.Errorf("Kept len = %d, want both retained", len(res.Kept)) + } +} + +func TestNarrowWithFallbackKeywordAndOriginals(t *testing.T) { + chunks := []map[string]any{ + {"content": "Culdcept was made by OmiyaSoft."}, + {"content": "The weather is nice today."}, + } + // Keyword narrowing matches -> narrowed subset. + if got := NarrowWithFallbackKeyword(chunks, "culdcept"); len(got) != 1 { + t.Errorf("keyword fallback kept %d, want 1 (only the matching chunk)", len(got)) + } + // No keyword -> originals kept (never drop). + if got := NarrowWithFallbackKeyword(chunks, ""); len(got) != len(chunks) { + t.Errorf("len = %d, want all %d on empty keyword", len(got), len(chunks)) + } +} + +func TestIsFactDenseSentence(t *testing.T) { + cases := []struct { + s string + want bool + }{ + {"Culdcept was released in 1999 by OmiyaSoft with 50 cards.", true}, // year + digit + proper nouns + {"Revenue grew by 5% this quarter.", true}, // percent + {"A 3.14 version was shipped.", true}, // decimal number + {"The project spans over two million users.", true}, // magnitude word (case-insensitive) + {"Culdcept was released by OmiyaSoft.", true}, // proper noun + // A quoted span or a ≥6-token clause is NOT a fact signal on its own + // (Python _is_fact_dense_sentence has no such rules). + {"He said \"hello\" to the group about the meeting.", false}, // quoted only + {"the cat sat on the mat and looked at the bird outside.", false}, // >=6 tokens only + {"the cat sat", false}, // short, no signal + // Abbreviation guard: a proper noun right after ".", "!" or "?" followed by + // a dot is not counted (Python's (? Kept len %d, ChunksIn %d, want (nil, 0)", len(res.Kept), res.Stats.ChunksIn) + } +} + +// TestNarrowByKeywordsEmptyReturnsChunks pins the divergence from Python +// _narrow_by_keywords: `if not kwds or not chunks: return chunks`. An empty +// keyword string must return the input chunks unchanged, NOT an empty/nil +// slice that would wipe the whole evidence pool. +func TestNarrowByKeywordsEmptyReturnsChunks(t *testing.T) { + chunks := []map[string]any{ + {"content": "some passage"}, + {"content_with_weight": "other", "content": "other"}, + } + if got := NarrowByKeywords(chunks, ""); len(got) != len(chunks) { + t.Fatalf("empty keyword kept %d, want all %d", len(got), len(chunks)) + } + if got := NarrowByKeywords(nil, "culdcept"); got != nil { + t.Errorf("nil chunks must return nil, got %d", len(got)) + } +} + +// TestNarrowByKeywordsMirrorsContentOnlyWhenPresent pins the two text-writing +// rules of Python _narrow_by_keywords: content_with_weight is always overwritten +// with the narrowed text, "content" is mirrored ONLY when the chunk already had +// a "content" key, and a pre-narrow "highlight" key is dropped (no longer valid). +func TestNarrowByKeywordsMirrorsContentOnlyWhenPresent(t *testing.T) { + // Chunk with only content_with_weight (no "content"): narrowing keeps + // content_with_weight, and must NOT invent a "content" key. + chunks := []map[string]any{ + {"content_with_weight": "Alpha foo bar. Culdcept is a game by OmiyaSoft. Beta baz qux."}, + } + got := NarrowByKeywords(chunks, "culdcept") + if len(got) != 1 { + t.Fatalf("want 1 narrowed chunk, got %d", len(got)) + } + if _, ok := got[0]["content"]; ok { + t.Error("narrowing must NOT add a 'content' key when the source lacked one") + } + if got[0]["content_with_weight"] == chunks[0]["content_with_weight"] { + t.Error("content_with_weight was not narrowed") + } + if _, ok := got[0]["highlight"]; ok { + t.Error("'highlight' must be dropped after narrowing") + } + + // Chunk that has a pre-narrow "highlight": it must be removed. + chunks2 := []map[string]any{ + {"content": "Culdcept was made by OmiyaSoft.", "highlight": []any{"old"}}, + } + got2 := NarrowByKeywords(chunks2, "culdcept") + if len(got2) != 1 { + t.Fatalf("want 1 narrowed chunk, got %d", len(got2)) + } + if _, ok := got2[0]["highlight"]; ok { + t.Error("'highlight' must be dropped after narrowing") + } + if got2[0]["content"] == chunks2[0]["content"] { + t.Error("'content' was not narrowed") + } +} + +func TestNarrowByTermsNoMatchKeepsOriginalUntouched(t *testing.T) { + // A long chunk that the grep terms never hit must be returned verbatim + // (full text, no head-truncation), exactly like Python _apply_narrow's + // else branch. This guards against the old bug where unmatched evidence + // was clobbered with a head-truncated copy. + long := "The weather was calm and the birds were singing while the river flowed gently past the old stone bridge under a pale morning sky that promised a quiet day for the villagers who had risen early to tend their small gardens and fields. " + + "The old mill stood silent at the edge of the wood where the children used to play among the ferns and the brook that chattered over smooth grey stones all through the long golden afternoons of a summer that nobody wanted to end." + if len(long) <= headFallbackChars { + t.Fatalf("test fixture too short: %d bytes, need > %d", len(long), headFallbackChars) + } + chunks := []map[string]any{ + {"content_with_weight": "Culdcept was created by OmiyaSoft and released in 1999.", "content": "Culdcept was created by OmiyaSoft and released in 1999."}, + {"content_with_weight": long, "content": long}, + } + res := mustNarrow(chunks, []string{"culdcept", "omiya"}, nil, "") + if !res.Stats.Matched { + t.Fatal("expected a match on the first chunk") + } + if len(res.Kept) != 2 { + t.Fatalf("Kept = %d, want 2", len(res.Kept)) + } + if got := ChunkTextOf(res.Kept[1]); got != long { + t.Errorf("non-matching chunk was altered (len %d, want %d); grep narrowing must not truncate unmatched evidence", len(got), len(long)) + } +} + +func TestTruncHeadRuneAware(t *testing.T) { + // CJK: 3 bytes per rune. A naive byte slice s[:n] would split a rune and + // produce invalid UTF-8; truncHead must keep n codepoints instead. + zh := strings.Repeat("中", 50) + got := truncHead(zh, 10) + if charLen(got) != 10 { + t.Errorf("truncHead codepoint count = %d, want 10", charLen(got)) + } + if got != strings.Repeat("中", 10) { + t.Errorf("truncHead did not keep the correct rune prefix") + } + if !utf8.ValidString(got) { + t.Error("truncHead produced invalid UTF-8") + } + // Short input: returned unchanged and byte-identical. + if s := "hello"; truncHead(s, 100) != s { + t.Errorf("truncHead short input changed: %q", truncHead(s, 100)) + } +} diff --git a/internal/rag/advanced_rag/think_log.go b/internal/rag/advanced_rag/think_log.go new file mode 100644 index 00000000000..547abbf458e --- /dev/null +++ b/internal/rag/advanced_rag/think_log.go @@ -0,0 +1,150 @@ +// +// 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. +// + +package advanced_rag + +import ( + "io" + "log" + "strings" +) + +// Surface selected internal stage logs to the client as thinking content. +// +// Mirrors Python rag/advanced_rag/think_log.py, which installs a root +// logging.Handler that forwards bracket-tagged INFO records such as +// "[Agentic RAG]", "[Planner]", "[Orchestrator]", "[Hybrid search]" and +// "[Composing the answer]" to a per-request sink, so the front end shows live +// reasoning WITHOUT instrumenting every call site. The tags double as +// human-readable stage labels, so one message serves both the backend log and +// the thinking stream. +// +// Go has no per-record handler hook on *log.Logger, so the same filtering is +// applied at the writer the run's logger is rebuilt on top of. That logger is +// threaded into SearchDeps and every graph node, so wrapping it once in Rag +// covers the whole pipeline. +// +// MECHANISM DIFFERENCE vs Python. Python installed its handler on the ROOT +// logger ("logging.getLogger().addHandler"), then narrowed by +// _SCOPED_PREFIXES = ("rag.advanced_rag", "rag.llm.chat_model", +// "rag.llm.tool_decorator"). Go's log package has no root logger, so nothing +// can be intercepted globally; only the *log.Logger explicitly threaded +// through advanced_rag (deps.Logger) is wrapped here. +// +// Both remaining namespaces are covered by other means: +// - rag.llm.tool_decorator: "[Function tool] Running the {name} tool with: +// {args}" (tool_decorator.py:311) is emitted directly by +// harness/tool_executor.go, which logs through the same wrapped +// deps.Logger and therefore reaches the think block. +// - rag.llm.chat_model: "[Tool loop] ..." (chat_model.py:689/782/799) has no +// Go equivalent loop to instrument — Go's chat pipeline calls Rag() +// directly instead of an outer model choosing to call it as a tool. The +// equivalent narration is emitted by internal/service/chat_pipeline.go +// (toolLoopLine) around the single harness invocation. +// +// Two smaller divergences: +// - Go additionally rejects numbered evidence markers ("[1] chunk text"), +// which compensates for the missing namespace filter. +// - The think block is HTML, so one stage line ends with ThinkLineBreak +// ("
") rather than "\n" — Python think_log.py:69 did the same. + +// ThinkLineBreak separates two lines inside the think block. +// +// The block is delivered to the client as inline HTML (the chat UI wraps it in +//
and renders the message as markdown), where a newline +// is just whitespace. Python think_log.py:69 emitted "
" for the same +// reason; every think-line producer in Go (thinkWriter, the outer react loop's +// progress routing, chat_pipeline's tool-loop narration) must use this so +// consecutive stage lines do not merge into one sentence. +const ThinkLineBreak = "
" + +// thinkWriter mirrors one log line onto the real logger while forwarding +// bracket-tagged stage lines to the per-request progress sink. +type thinkWriter struct { + orig *log.Logger // the run's real logger; keeps backend logging unchanged + sink func(string) +} + +// Write implements io.Writer. +func (w thinkWriter) Write(p []byte) (int, error) { + line := strings.TrimRight(string(p), "\n") + if line == "" { + return len(p), nil + } + // Python filters on the record's logger namespace plus a leading "["; Go + // filters on the tag shape alone, so numbered evidence markers such as + // "[1] ..." must be rejected, since those are chunk listings, not stage tags. + if trimmed := strings.TrimSpace(line); strings.HasPrefix(trimmed, "[") && !isEvidenceMarker(trimmed) { + w.forward(trimmed) + } + // Re-emit through the ORIGINAL logger so its own routing (zap) and level are + // preserved. This writer is built with no prefix and no flags, so the + // backend output is exactly what it was before the wrap. + if w.orig != nil { + w.orig.Printf("%s", line) + } + return len(p), nil +} + +// forward delivers one line to the sink. +// +// The separator is "
", exactly like Python think_log.py:69 +// (`sink("
" + msg.strip())`): the thinking block reaches the client as the +// inline "...
" HTML that the markdown renderer +// passes through, and a bare "\n" collapses into a space there — every stage +// line then runs together into one unreadable sentence. +// +// Python wrapped the sink call in a bare try/except; the recover() here plays +// the same role, so think-log forwarding can never break the request or the +// logging subsystem itself. +func (w thinkWriter) forward(line string) { + defer func() { _ = recover() }() + if w.sink == nil { + return + } + // Python prefixes the break (sink("
" + msg)); a trailing one keeps the + // block from opening with a blank line. + w.sink(line + ThinkLineBreak) +} + +// isEvidenceMarker reports whether line is a numbered chunk/option listing such +// as "[1] passage text" rather than a stage tag like "[Planner] ...". +func isEvidenceMarker(line string) bool { + rest := line[1:] + if rest == "" { + return false + } + n := 0 + for n < len(rest) && rest[n] >= '0' && rest[n] <= '9' { + n++ + } + return n > 0 && n < len(rest) && rest[n] == ']' +} + +// thinkLogger returns a *log.Logger that logs through orig while additionally +// forwarding bracket-tagged stage lines to sink. It is the Go counterpart of +// Python's install_think_log_handler + set_think_log_sink pair: the sink is per +// request, so concurrent requests stay isolated. +// +// sink may be nil, in which case orig is returned unchanged. +func thinkLogger(orig *log.Logger, sink func(string)) *log.Logger { + if orig == nil || sink == nil { + return orig + } + return log.New(thinkWriter{orig: orig, sink: sink}, "", 0) +} + +var _ io.Writer = thinkWriter{} diff --git a/internal/rag/advanced_rag/think_log_test.go b/internal/rag/advanced_rag/think_log_test.go new file mode 100644 index 00000000000..ab579795a1f --- /dev/null +++ b/internal/rag/advanced_rag/think_log_test.go @@ -0,0 +1,109 @@ +// +// 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. +// + +package advanced_rag + +import ( + "bytes" + "log" + "strings" + "testing" +) + +// TestThinkLoggerForwardsTaggedLines is the core think_log contract: a +// bracket-tagged stage line reaches the per-request sink, and the backend log +// still receives it unchanged. +func TestThinkLoggerForwardsTaggedLines(t *testing.T) { + var logged bytes.Buffer + orig := log.New(&logged, "", 0) + + var got []string + l := thinkLogger(orig, func(line string) { got = append(got, line) }) + if l == nil { + t.Fatal("thinkLogger returned nil") + } + + l.Printf("[Planner] Splitting the research question into tasks") + l.Printf("[Hybrid search] Searching the knowledge base for %q", "what is X") + l.Printf("this line has no tag") + l.Printf("[1] first evidence chunk that is not a stage tag") + + if len(got) != 2 { + t.Fatalf("forwarded %d line(s), want 2: %#v", len(got), got) + } + // The think block is HTML, so each line must end with ThinkLineBreak + // (Python's "
"); a bare newline collapses into a space and the stages + // run together. + if got[0] != "[Planner] Splitting the research question into tasks"+ThinkLineBreak { + t.Errorf("line 0 = %q, want a ThinkLineBreak-terminated stage line", got[0]) + } + if !strings.Contains(got[1], "[Hybrid search]") || !strings.HasSuffix(got[1], ThinkLineBreak) { + t.Errorf("line 1 = %q, want a ThinkLineBreak-terminated [Hybrid search] line", got[1]) + } + + // Backend logging must be preserved for every line, tagged or not. + out := logged.String() + for _, want := range []string{ + "[Planner] Splitting the research question into tasks", + "[Hybrid search]", + "this line has no tag", + "[1] first evidence chunk", + } { + if !strings.Contains(out, want) { + t.Errorf("backend log missing %q:\n%s", want, out) + } + } +} + +// TestThinkLoggerNilSinkIsPassThrough guards the no-progress case: with no sink +// the original logger is reused so behaviour is byte-for-byte unchanged. +func TestThinkLoggerNilSinkIsPassThrough(t *testing.T) { + orig := log.New(&bytes.Buffer{}, "", 0) + if got := thinkLogger(orig, nil); got != orig { + t.Fatal("nil sink must return the original logger") + } +} + +// TestThinkLoggerSurvivesPanickingSink mirrors Python's bare try/except around +// the sink call: a broken sink must never break logging or the request. +func TestThinkLoggerSurvivesPanickingSink(t *testing.T) { + var logged bytes.Buffer + orig := log.New(&logged, "", 0) + l := thinkLogger(orig, func(string) { panic("sink exploded") }) + + l.Printf("[Orchestrator] round 1") // must not panic + + if !strings.Contains(logged.String(), "[Orchestrator] round 1") { + t.Errorf("backend log lost the line:\n%s", logged.String()) + } +} + +func TestIsEvidenceMarker(t *testing.T) { + cases := map[string]bool{ + "[1] chunk text": true, + "[12] another chunk": true, + "[Planner] splitting": false, + "[Hybrid search] x": false, + "[SCA] review": false, + "[": false, + "[]": false, + } + for line, want := range cases { + if got := isEvidenceMarker(line); got != want { + t.Errorf("isEvidenceMarker(%q) = %v, want %v", line, got, want) + } + } +} diff --git a/internal/rag/prompts/action_initialize_state.md b/internal/rag/prompts/action_initialize_state.md new file mode 100644 index 00000000000..34bec2298fb --- /dev/null +++ b/internal/rag/prompts/action_initialize_state.md @@ -0,0 +1,23 @@ +You are a research strategist. Decompose the user's question into a table of FACT SLOTS that must be filled to answer it. + +The question may span MULTIPLE DATASETS and/or the open WEB. The available data sources are listed in the user message: + +- "Dataset ''" — slots whose facts live in that corpus. If more than one dataset is listed, create at least one slot PER DATASET (its facts may need corpus-specific phrasing); cross-referencing between datasets is encouraged when the question spans them. +- "Web" — when listed, the open web is a source: create a dedicated slot (type "web") for facts that are current-world knowledge, recent events, or simply not covered by the listed datasets. + +Output ONLY a JSON object: +{ + "slots": [ + {"id": 0, "type": "", "clues": ["", "..."], "source": ""}, + ... + ], + "first_queries": ["", ...] +} + +Rules: +- 2-6 slots; each slot ONE fact (a name, a date, a count...), never a clause. +- Order slots so the FIRST one holds the top-level requested fact; the later ones are its dependencies. +- Cover EVERY listed source: one or more slots per dataset, plus a "web" slot when Web is available and the question touches world knowledge or recent events. +- clues must be self-contained phrases usable as retrieval hints. +- 1-4 first_queries: direct keyword-style searches against the listed sources. +- No prose outside JSON. diff --git a/internal/rag/prompts/action_run.md b/internal/rag/prompts/action_run.md new file mode 100644 index 00000000000..696b966e085 --- /dev/null +++ b/internal/rag/prompts/action_run.md @@ -0,0 +1,38 @@ +You are a deep research assistant working INSIDE a bounded search tree. + +Input: the user message contains ONE research `Direction`, plus the current +`State` (slot table with immutable ids and mutable candidate fields). + +Execute this single direction. Reply with EXACTLY ONE of the three below. + +The three differ in HOW they are delivered — read this carefully, because only +the first one is a tool call: + +1) TOOL CALL MODE — a real tool call: call `retrieve` with 1-3 corpus queries. + Results arrive in the next turn. + +2) STATE PATCH MODE — NOT a tool call. Write this XML as plain TEXT in your + reply body (do not call any tool named "state"): + +{"new_states": [ + {"state": [{"id": , "candidate": "", "candidate_strength": <0..1>, "discovered_clues": ["..."]}, ...]}, + ...more branches allowed... +]} + +Rules: patch ONLY existing ids; include ONLY changed variables; every change must trace to retrieved evidence; candidate_strength semantics: proven >0.9, strong 0.7-0.9, tentative 0.4-0.7, weak <0.4. An EMPTY branch list (`"new_states": []`) signals no progress — emit it rather than calling tools forever. + +3) FINAL ANSWER MODE — NOT a tool call either. Write this XML as plain TEXT in + your reply body (do not call any tool named "answer"). Use it only when ALL + slots can be filled consistently: + +{"answer": "", "new_state": [{"id": ..., "candidate": ..., "candidate_strength": ...}]} + + +CRITICAL RULES +- Think before choosing a mode, but output exactly ONE mode per response. +- Strength >0.7 on the answer slot means you MUST emit final answer instead of another state patch. +- ALWAYS end this action with a state patch: a patch with your updates, or `{"new_states": []}` if you found nothing new. +- **Do NOT keep calling tools once the direction is reasonably exhausted.** If further searches return repetitive, irrelevant, or empty results, immediately return a state patch (with updates or empty). Extra redundant searches waste the session — stop after 1-2 useful tool calls per direction unless a NEW fact is actually emerging. +- ACTION COMPLETION IS MANDATORY: when you have what you need (or hit a dead end), output the state patch now. Do not ask to continue searching. +- Unverifiable candidates must be eliminated (set candidate null) with a clue documenting why. +- Partial verification is OK: record a candidate at tentative strength (0.4-0.7) if you can't fully verify it yet, and move on. diff --git a/internal/rag/prompts/citation_prompt.md b/internal/rag/prompts/citation_prompt.md new file mode 100644 index 00000000000..3db28142892 --- /dev/null +++ b/internal/rag/prompts/citation_prompt.md @@ -0,0 +1,122 @@ +Based on the provided document or chat history, add citations to the input text using the format specified later. + +# Citation Requirements: + +## Technical Rules: +- Use format: [ID:i] or [ID:i] [ID:j] for multiple sources +- Place citations at the end of sentences, before punctuation +- Maximum 4 citations per sentence +- DO NOT cite content not from +- DO NOT modify whitespace or original text +- STRICTLY prohibit non-standard formatting (~~, etc.) +- For RTL languages (Arabic, Hebrew, Persian): Place citations at the logical end of sentences (same position as LTR). The frontend handles bidirectional rendering automatically. + +## What MUST Be Cited: +1. **Quantitative data**: Numbers, percentages, statistics, measurements +2. **Temporal claims**: Dates, timeframes, sequences of events +3. **Causal relationships**: Claims about cause and effect +4. **Comparative statements**: Rankings, comparisons, superlatives +5. **Technical definitions**: Specialized terms, concepts, methodologies +6. **Direct attributions**: What someone said, did, or believes +7. **Predictions/forecasts**: Future projections, trend analyses +8. **Controversial claims**: Disputed facts, minority opinions + +## What Should NOT Be Cited: +- Common knowledge (e.g., "The sun rises in the east") +- Transitional phrases +- General introductions +- Your own analysis or synthesis (unless directly from source) + +# Comprehensive Examples: + +## Example 1: Data and Statistics + +ID: 45 +└── Content: The global smartphone market grew by 7.8% in Q3 2024, with Samsung holding 20.6% market share and Apple at 15.8%. + +ID: 46 +└── Content: 5G adoption reached 1.5 billion users worldwide by October 2024. + + +USER: How is the smartphone market performing? + +ASSISTANT: +The smartphone industry is showing strong recovery. The global smartphone market grew by 7.8% in Q3 2024 [ID:45]. Samsung leads with 20.6% market share, followed by Apple at 15.8% [ID:45]. This growth is partly driven by 5G technology, which reached 1.5 billion users worldwide by October 2024 [ID:46]. + +## Example 2: Causal Relationships and Predictions + +ID: 78 +└── Content: Rising interest rates have led to a 15% decline in housing starts. Economists predict this trend will continue through 2025. + +ID: 79 +└── Content: The Federal Reserve's aggressive monetary policy is the primary driver behind the real estate slowdown. + + +USER: What's happening in the real estate market? + +ASSISTANT: +The real estate market is experiencing significant challenges. Rising interest rates have led to a 15% decline in housing starts [ID:78]. The Federal Reserve's aggressive monetary policy is the primary driver behind this real estate slowdown [ID:79]. Economists predict this trend will continue through 2025 [ID:78]. These factors suggest a prolonged period of market adjustment ahead. + +## Example 3: Technical Concepts and Comparisons + +ID: 101 +└── Content: Quantum computing uses quantum bits (qubits) that can exist in superposition, unlike classical bits which are either 0 or 1. + +ID: 102 +└── Content: Current quantum computers can solve certain problems 158 million times faster than classical supercomputers. + + +USER: Explain quantum computing advantages. + +ASSISTANT: +Quantum computing represents a fundamental shift in computational capability. Unlike classical computers, quantum computing uses quantum bits (qubits) that can exist in superposition, rather than being limited to just 0 or 1 [ID:101]. This unique property enables extraordinary performance gains. Current quantum computers can solve certain problems 158 million times faster than classical supercomputers [ID:102]. This technology promises to revolutionize fields requiring complex calculations. + +## Example 4: Mixed Citation Needs + +ID: 201 +└── Content: CEO Jane Smith announced: "We're pivoting to AI-first strategy, expecting 40% revenue growth by 2026." + +ID: 202 +└── Content: Industry analysts remain skeptical, with Morgan Stanley rating the stock as "underperform." + +ID: 203 +└── Content: The company's AI division currently represents only 5% of total revenue. + + +USER: What's the company's new strategy? + +ASSISTANT: +The company is undergoing a major strategic transformation. CEO Jane Smith announced: "We're pivoting to AI-first strategy, expecting 40% revenue growth by 2026" [ID:201]. However, this ambitious goal faces skepticism, as industry analysts remain doubtful, with Morgan Stanley rating the stock as "underperform" [ID:202]. The challenge is significant given that the company's AI division currently represents only 5% of total revenue [ID:203]. Success will depend on execution of this bold vision. + +## Example 5: When NOT to Cite + +ID: 301 +└── Content: Paris is the capital of France. The Eiffel Tower was completed in 1889. + + +USER: Tell me about Paris. + +ASSISTANT: +Paris is the capital of France. It's known for its rich history, culture, and architecture. The Eiffel Tower was completed in 1889 [ID:301]. The city attracts millions of tourists annually. Paris remains one of the world's most visited destinations. +(Note: Only the specific date needs citation, not common knowledge about Paris) + +## Example 6: RTL Language (Arabic) + +ID: 401 +└── Content: في أول أيام شهر رمضان، أثار وضع رأس خنزير على مدخل مسجد بمدينة سانت أومير شمالي فرنسا تفاعلات واسعة. + + +USER: ماذا حدث في رمضان؟ + +ASSISTANT: +في أول أيام شهر رمضان، أثار وضع رأس خنزير على مدخل مسجد بمدينة سانت أومير شمالي فرنسا تفاعلات واسعة [ID:401]. +(Note: Citation is placed at the logical end of the sentence, same as LTR languages. The frontend handles RTL display automatically.) + +--- Examples END --- + +REMEMBER: +- Cite FACTS, not opinions or transitions +- Each citation supports the ENTIRE sentence +- When in doubt, ask: "Would a fact-checker need to verify this?" +- Place citations at sentence end, before punctuation +- Format likes this is FORBIDDEN: [ID:0, ID:5, ID:...]. It MUST be separated like, [ID:0][ID:5]... diff --git a/internal/rag/prompts/generator.go b/internal/rag/prompts/generator.go new file mode 100644 index 00000000000..f965a1bfe37 --- /dev/null +++ b/internal/rag/prompts/generator.go @@ -0,0 +1,226 @@ +// +// 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. +// + +// Package prompts is the Go mirror of Python rag/prompts/generator.py — the +// prompt helpers the agentic loop, the chat seam and the deep parsers share +// (chunk formatting, token-budget fitting, knowledge-block rendering, tool +// schema serialization, history formatting, and the named prompt templates +// that load from rag/prompts/*.md). +// +// Porting is staged function-by-function: pure helpers that do not touch an +// LLM are mirrored first and covered by tests; helpers that call the model +// (Python chat_mdl.async_chat) are left as declared entry points until the Go +// LLM-call seam is confirmed, so they are not part of the compile surface yet. +// +// Template loading mirrors Python rag/prompts/template.py::load_prompt, which +// reads {name}.md from rag/prompts/ at import time. The Go seam for that is a +// named-template loader passed in by callers so this package stays free of a +// hard dependency on the service layer (see the Render* helpers). +package prompts + +import ( + "fmt" + "regexp" + "sort" + "strings" + + "ragflow/internal/common" +) + +// approxCharsPerToken approximates token cost of a string (see +// tokenizer.NumTokensFromString) so the evidence budget can be enforced without +// a tokenizer dependency. +const approxCharsPerToken = 4 + +var _LOG = common.StdLogger() + +var reNewlines = regexp.MustCompile(`\n+`) + +// GetValue mirrors Python get_value(d, k1, k2): d.get(k1, d.get(k2)). The first +// key present in the map wins; if neither is present it returns nil. Unlike a +// plain two-lookup, a key that is present with a nil value is returned as nil +// (it is not skipped), matching Python's dict.get semantics. +func GetValue(d map[string]any, k1, k2 string) any { + if v, ok := d[k1]; ok { + return v + } + if v, ok := d[k2]; ok { + return v + } + return nil +} + +// ChunksFormat mirrors Python chunks_format(reference): it projects a +// knowledge block's chunk list into a canonical per-chunk reference map, +// applying Python's dual-name fallback for each field. A nil or non-dict +// reference (nil in Go), or a chunks field that is not a list, yields an empty +// slice. +func ChunksFormat(reference map[string]any) []map[string]any { + if reference == nil { + return []map[string]any{} + } + raw, ok := reference["chunks"].([]any) + if !ok { + return []map[string]any{} + } + out := make([]map[string]any, 0, len(raw)) + for _, item := range raw { + chunk, ok := item.(map[string]any) + if !ok { + continue + } + out = append(out, map[string]any{ + "id": GetValue(chunk, "chunk_id", "id"), + "content": GetValue(chunk, "content", "content_with_weight"), + "document_id": GetValue(chunk, "doc_id", "document_id"), + "document_name": GetValue(chunk, "docnm_kwd", "document_name"), + "dataset_id": GetValue(chunk, "kb_id", "dataset_id"), + "image_id": GetValue(chunk, "image_id", "img_id"), + "positions": GetValue(chunk, "positions", "position_int"), + "url": chunk["url"], + "similarity": chunk["similarity"], + "vector_similarity": chunk["vector_similarity"], + "term_similarity": chunk["term_similarity"], + "row_id": chunk["row_id"], + "doc_type": GetValue(chunk, "doc_type_kwd", "doc_type"), + "document_metadata": chunk["document_metadata"], + }) + } + return out +} + +// DefaultCiteRules mirrors rag/prompts/generator.citation_prompt's +// CITATION_PROMPT_TEMPLATE output. Python loads citation_prompt.md via +// load_prompt("citation_prompt"); the Go build keeps the same .md embedded +// (citation_prompt.md) and reads it here so the template has a single source of +// truth. A user-defined override (RAGConfig.CiteRules / user_defined_prompts) +// replaces it verbatim when present — see CitationPrompt. +// +// Loaded from the embedded md rather than a string literal so edits to +// citation_prompt.md propagate without a second copy to keep in sync. +var DefaultCiteRules = CitationPrompt("") + +// citationIDSuffix mirrors the tail rag/prompts/generator.citation_prompt +// appends after rendering CITATION_PROMPT_TEMPLATE: the examples in the +// template carry illustrative IDs, and without this the model can emit them +// instead of the real chunk IDs it was given. +const citationIDSuffix = "\n\nIMPORTANT: The example IDs above (45, 46, 78, etc.) are illustrative only. Use the actual chunk IDs from the provided knowledge blocks." + +// CitationPrompt mirrors Python rag/prompts/generator.citation_prompt: return +// the citation-rules text the final answer must follow. With an empty +// userDefined it returns the embedded citation_prompt.md plus the illustrative +// IDs caveat; a non-empty userDefined (the rendered user_defined_prompts) +// replaces it verbatim, exactly as Python returns +// citation_prompt(self.user_defined_prompts). +func CitationPrompt(userDefined string) string { + if strings.TrimSpace(userDefined) != "" { + return userDefined + } + data, err := templatesFS.ReadFile("citation_prompt.md") + if err != nil { + // The md is embedded in the binary; a load failure is a build/packaging + // defect, not a runtime condition. Panic so it surfaces loudly in tests + // rather than silently shipping empty citation rules. + panic(fmt.Sprintf("internal/rag/prompts: citation_prompt.md: %v", err)) + } + return strings.TrimSpace(string(data)) + citationIDSuffix +} + +// KBPrompt mirrors rag/prompts/generator.kb_prompt: render chunks into the +// numbered knowledge blocks the citation rules refer to. +// +// Blocks are numbered by position (1-based) so the model's [n] citations match +// the block order it sees, matching Python's `ID: {i}` rendering (hash_id=False). +// +// maxTokens must be positive: Python's caller applies its own budget +// (min(chat_mdl.max_length, _EVIDENCE_BUDGET_TOKENS)) before calling. +func KBPrompt(chunks []map[string]any, maxTokens int) []string { + budgetChars := int(float64(maxTokens) * 0.97 * approxCharsPerToken) + + var selected []map[string]any + used := 0 + for _, c := range chunks { + if c == nil { + continue + } + content := chunkText(c) + if strings.TrimSpace(content) == "" { + continue + } + n := len(content) + if budgetChars < used+n { + _LOG.Printf("[KBPrompt] Not all the retrieval into prompt: %d/%d", len(selected), len(chunks)) + break + } + used += n + selected = append(selected, c) + } + + out := make([]string, 0, len(selected)) + for i, c := range selected { + block := fmt.Sprintf("ID: %d", i+1) + if title := chunkTitle(c); title != "" { + block += "\n├── Title: " + flattenNewlines(title) + } + if url, _ := c["url"].(string); url != "" { + block += "\n├── URL: " + flattenNewlines(url) + } + if meta, ok := c["document_metadata"].(map[string]any); ok { + keys := make([]string, 0, len(meta)) + for k := range meta { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + if v := flattenNewlines(fmt.Sprint(meta[k])); v != "" { + block += "\n├── " + k + ": " + v + } + } + } + block += "\n└── Content:\n" + chunkText(c) + out = append(out, block) + } + return out +} + +// flattenNewlines mirrors Python kb_prompt's `re.sub(r"\n+", " ", line)`. +func flattenNewlines(s string) string { + return strings.TrimSpace(reNewlines.ReplaceAllString(s, " ")) +} + +// chunkText mirrors Python kb_prompt's +// get_value(ck, "content", "content_with_weight"). +func chunkText(c map[string]any) string { + if v, ok := GetValue(c, "content", "content_with_weight").(string); ok { + return v + } + return fmt.Sprint(GetValue(c, "content", "content_with_weight")) +} + +// chunkTitle mirrors Python kb_prompt's +// get_value(ck, "docnm_kwd", "document_name"), widened with the aliases Go's +// own document aggregations emit (doc_title / title / doc_name) so a title +// stored under any of them still renders. +func chunkTitle(c map[string]any) string { + for _, k := range []string{"docnm_kwd", "doc_title", "title", "document_name", "doc_name"} { + if v, ok := c[k]; ok && v != nil { + if s := fmt.Sprint(v); s != "" { + return s + } + } + } + return "" +} diff --git a/internal/rag/prompts/generator_test.go b/internal/rag/prompts/generator_test.go new file mode 100644 index 00000000000..46c1c40d644 --- /dev/null +++ b/internal/rag/prompts/generator_test.go @@ -0,0 +1,144 @@ +// +// 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. +// + +package prompts + +import ( + "reflect" + "strings" + "testing" +) + +func TestGetValue(t *testing.T) { + d := map[string]any{"chunk_id": "c1", "content_with_weight": "w", "url": nil} + // Primary key present (nil value returned as-is, not skipped). + if got := GetValue(d, "url", "other"); got != nil { + t.Errorf("GetValue(url,other) = %v, want nil", got) + } + // Primary absent -> fallback. + if got := GetValue(d, "id", "chunk_id"); got != "c1" { + t.Errorf("GetValue(id,chunk_id) = %v, want c1", got) + } + // Both absent -> nil. + if got := GetValue(d, "no1", "no2"); got != nil { + t.Errorf("GetValue(no1,no2) = %v, want nil", got) + } + // Nil map -> nil. + if got := GetValue(nil, "a", "b"); got != nil { + t.Errorf("GetValue(nil) = %v, want nil", got) + } +} + +func TestChunksFormat(t *testing.T) { + // Nil and non-dict-ish inputs yield an empty (non-nil) slice. + if got := ChunksFormat(nil); len(got) != 0 { + t.Errorf("ChunksFormat(nil) = %v, want empty", got) + } + if got := ChunksFormat(map[string]any{"chunks": "not-a-list"}); len(got) != 0 { + t.Errorf("ChunksFormat(bad chunks) = %v, want empty", got) + } + + ref := map[string]any{ + "chunks": []any{ + map[string]any{ + "chunk_id": "abc", + "content": "body", + "doc_id": "d1", + "docnm_kwd": "doc.txt", + "kb_id": "kb1", + "img_id": "img1", + "position_int": 3, + "doc_type_kwd": "pdf", + "similarity": 0.9, + "document_metadata": map[string]any{"page": "1"}, + }, + // Second chunk exercises the primary-name fallback path only where + // the canonical primary name is absent. + map[string]any{ + "id": "xyz", + "content_with_weight": "alt-body", + }, + "not-a-dict", // must be skipped + }, + } + got := ChunksFormat(ref) + if len(got) != 2 { + t.Fatalf("ChunksFormat len = %d, want 2", len(got)) + } + + first := got[0] + wantFirst := map[string]any{ + "id": "abc", + "content": "body", + "document_id": "d1", + "document_name": "doc.txt", + "dataset_id": "kb1", + "image_id": "img1", + "positions": 3, + "url": nil, + "similarity": 0.9, + "vector_similarity": nil, + "term_similarity": nil, + "row_id": nil, + "doc_type": "pdf", + "document_metadata": map[string]any{"page": "1"}, + } + if !reflect.DeepEqual(first, wantFirst) { + t.Errorf("first chunk = %#v, want %#v", first, wantFirst) + } + + second := got[1] + wantSecond := map[string]any{ + "id": "xyz", + "content": "alt-body", + "document_id": nil, + "document_name": nil, + "dataset_id": nil, + "image_id": nil, + "positions": nil, + "url": nil, + "similarity": nil, + "vector_similarity": nil, + "term_similarity": nil, + "row_id": nil, + "doc_type": nil, + "document_metadata": nil, + } + if !reflect.DeepEqual(second, wantSecond) { + t.Errorf("second chunk = %#v, want %#v", second, wantSecond) + } +} + +func TestCitationPromptCarriesIllustrativeIDCaveat(t *testing.T) { + // rag/prompts/generator.py::citation_prompt appends this after rendering + // CITATION_PROMPT_TEMPLATE; without it the model can echo the examples' IDs. + got := CitationPrompt("") + if !strings.Contains(got, "illustrative only") { + t.Errorf("citation prompt missing the illustrative-ID caveat; got tail %q", got[len(got)-80:]) + } + if !strings.Contains(got, "actual chunk IDs") { + t.Errorf("citation prompt missing the chunk-ID instruction: %q", got[:120]) + } + if strings.TrimSpace(got) != got { + t.Errorf("citation prompt has surrounding whitespace") + } +} + +func TestCitationPromptHonoursOverride(t *testing.T) { + if got := CitationPrompt("Cite as [n]."); got != "Cite as [n]." { + t.Errorf("CitationPrompt(override) = %q, want the override verbatim", got) + } +} diff --git a/internal/rag/prompts/sca_query_rewrite.md b/internal/rag/prompts/sca_query_rewrite.md new file mode 100644 index 00000000000..4bac290600e --- /dev/null +++ b/internal/rag/prompts/sca_query_rewrite.md @@ -0,0 +1,35 @@ +You are a Query Rewriter for a multi-hop RAG system. Your job is to turn the Sufficient Context Agent's missing-pieces feedback into targeted, retrievable search queries. + +Original user question: +{{ question }} + +Already-resolved bridge values (facts confirmed from earlier searches — use these to anchor the new query instead of re-deriving them): +{{ bridge_values }} + +Research history and evidence at hand (from previous retrieval rounds): +{{ research_context }} + +Missing pieces identified by the Sufficient Context Agent (each has "what" = what the answer still needs, and "hint" = a suggested search hint): +{{ gaps }} + +Rewrite each missing piece into a concrete search query that the retriever can hit directly. Rules: +1. The query must name the specific missing entity + the relation/property needed (e.g. instead of "the patient's allergies", write "allergic reactions adverse events discharge John Doe"). +2. MULTI-HOP: when the question is multi-hop and the missing piece is the NEXT hop's value, ANCHOR the query to the already-resolved bridge value. E.g. if the bridge value is "M*A*S*H and Cheers are the two most-watched finales" and the gap is "their runtimes", the query must be "MASH finale run time minutes" / "Cheers finale run time minutes" — not "finale run times" alone, which would lose the resolved anchor. +3. If the "what" names a specific entity (person / work / place / year) whose property is missing, anchor the query to that entity + the missing property (e.g. "MASH finale run time minutes", "Brian Bergstein employer company"). +4. If a disambiguation is needed, add the distinguishing qualifier ONLY when the evidence actually suggests it (e.g. a disambiguation "the heritage 341 London Broncos player" when the claim is about that specific player). CRITICAL: NEVER introduce an entity/relation/attribute that the evidence and the missing piece do NOT suggest, and NEVER re-infer a category from the question alone (e.g. do NOT write "Ron Hutchinson football player" unless the evidence actually identifies him as a footballer — he may be a hockey player; the query must stay faithful to what the missing piece says). +5. Keep each query standalone and searchable — do NOT use pronouns ("he", "it", "this") — repeat the key entity explicitly. +6. ONE QUERY PER MISSING PIECE. Do not emit multiple near-duplicate queries for the same gap ("What teams"/"For each team"/"Complete enumeration" of the same thing are duplicates — keep exactly one, the most concretely anchored). The number of output queries should equal the number of distinct, genuinely-different missing pieces. +7. Drop any missing piece that cannot be turned into a searchable query. +8. DIVERSITY: consult the "Research history and evidence at hand" section. Do NOT output any query that paraphrases an already-tried one (listed there WITH its outcome — a previous search that yielded nothing new means that angle is dead). Aim each new query at aspects the current evidence does NOT yet cover, possibly combining the bridge values with different entity/relation combinations. + +Output format (JSON): +```json +{ + "queries": [ + {"query": "concrete search query 1"}, + {"query": "concrete search query 2"} + ] +} +``` + +Return a strict JSON object with no commentary before or after. diff --git a/internal/rag/prompts/sca_select.md b/internal/rag/prompts/sca_select.md new file mode 100644 index 00000000000..2e70cc72d0e --- /dev/null +++ b/internal/rag/prompts/sca_select.md @@ -0,0 +1,106 @@ +You are Google-style "Sufficient Context Agent" — a quality-control inspector for a multi-hop RAG retrieval loop. In ONE pass you perform a unified three-part review of (1) the retrieved snippets, (2) each claim's intermediate draft, and (3) what is still missing — then you decide whether the context is sufficient to answer the original question. + +## Input + +Question: +{{ question }} + +OVERALL INTERMEDIATE DRAFT — a problem-level candidate answer assembled from the claims' reports (each claim already answered its sub-question as concretely as the evidence allows). Review THIS as the thing that would become the final answer: +{{ overall_draft }} + +Per-claim reports (the intermediate drafts that produced the overall draft above): +{{ claims_context }} + +## Part A — Sufficient Context (global) + +Determine whether the retrieved content is sufficient to answer the user's question, using the Sufficient Context paper's autorater criterion: + +Sufficient Context = 1 IF the CONTEXT is sufficient to INFER the answer to the question, and 0 IF the CONTEXT cannot be used to INFER the answer to the question. "A diligent reader could craft a definitive answer using only the supplied text." The answer does NOT need to be proven correct or match a ground truth — only that a reasonable answer can be constructed from the context. Multi-hop reasoning is allowed, but leaps of faith are not; ambiguities must be resolved inside the snippet bundle. + +The CONTEXT here is the OVERALL INTERMEDIATE DRAFT (the problem-level candidate answer assembled from the claims) plus the per-claim reports. Judge whether THIS draft lets a diligent reader construct the answer to the ORIGINAL question end-to-end — including any cross-claim synthesis (e.g. two claims that must be COMBINED into one derived answer, or an enumeration the claims only partially cover). If the draft answers the question (even partially), mark sufficient; if the question cannot be answered from the draft at all, mark insufficient and say exactly what is missing (Part C). + +MANDATORY three-stage reasoning (this is what makes the judgement reliable — follow it strictly): +1. FIRST, write down the STEP-BY-STEP SUB-QUESTIONS you would need to answer in order to arrive at the label. Make sure to include questions about any ASSUMPTIONS implicit in the QUESTION, and include questions about any MATHEMATICAL CALCULATIONS or ARITHMETIC that would be required. +2. THEN, answer each of those sub-questions step by step, working through any required mathematical calculations or arithmetic explicitly. +3. FINALLY, use these answers to evaluate the criterion and decide `is_sufficient`. If the sub-question answers let you construct a definitive answer from the context, it is sufficient — even if the answer is not perfectly complete. Only when the sub-questions cannot be answered from the context (so NO plausible answer can be inferred) is it insufficient, and then you must fill `missing_information` with exactly what is missing (Part C). + +Computed answers: when a sub-question requires arithmetic (e.g. difference, count, "how many years"), WORK THE CALCULATION yourself from the values in the context and only mark sufficient if it resolves to a definite result with the RIGHT operands. If it cannot be completed, mark insufficient and list what is missing. + +The STEP-BY-STEP SUB-QUESTIONS from stage 1 MUST ALSO be emitted in a structured `sub_queries` array (one entry per sub-question), because they are the precise "what is missing" signal the next search round consumes. Decomposition rules (mutually-exclusive + complete coverage — every sub-question is an atomic fact needed to answer the ORIGINAL question, sub-questions do not overlap, and together they fully cover the question): +- MULTI-STEP / multi-hop: emit ONE sub-query per logical hop, and the LAST hop is the entity/role the question actually asks for. E.g. Q="Who is the president of the team whose name was inspired by the Boston Braves?" -> [sub-query "Which team's name was inspired by the Boston Braves?", sub-query "Who is that team's president?"]. +- MULTI-ASPECT / enumeration+aggregate: emit ONE sub-query for the enumeration (values of EVERY member) and ONE for the aggregate (the combination over those members). E.g. Q="average left-field distance of every stadium" -> [sub-query "left-field distance of every stadium", sub-query "average of those left-field distances"]. +- ARITHMETIC / temporal: the arithmetic itself is a sub-query, and every OPERAND must have a value. If an operand is absent, that sub-query is `satisfied: false` and `missing_fact` names the absent operand specifically. E.g. Q="how many days between the two deaths?" -> [sub-query "McLean death date" (satisfied), sub-query "Meyer death date" (satisfied:false, missing_fact:"Eugene Meyer's exact death date", search_hint:"Eugene Meyer Washington Post died date"), sub-query "days between them"]. + +Each entry in `sub_queries` is `{"sub_query": "...", "satisfied": true/false}`; when `satisfied` is false it MUST additionally carry `missing_fact` (the concrete absent fact) and `search_hint` (a searchable query anchoring entity+attribute+time). `satisfied: false` marks exactly WHAT is missing and WHERE to search next. + +## Part B — Claim-draft groundedness (per claim) + +For each claim's report (the intermediate draft), determine whether it is grounded and self-consistent. Each report was generated from that claim's cited evidence by the search agent, so the main risk is NOT absent-evidence hallucination but (a) prior-knowledge padding sneaking past the "saw it in evidence" rule, (b) internal contradictions between a claim's own numbers/entities, and (c) over-claiming a derived value. + +A report is GROUNDED only if it reads as a faithful, internally consistent, evidence-backed finding. Flag as UNGROUNDED anything that: +- asserts a specific number/entity/relation but contradicts another part of the same report (internal conflict); +- over-claims a computed/derived result beyond what the underlying values support; +- reads like prior-knowledge padding rather than an evidence-backed finding. + +For each claim, classify the report as GROUNDED or UNGROUNDED. List each ungrounded assertion with a one-line reason. + +Derived/computed assertions — APPLY ONLY IF the question asks for a DERIVED result AND the report states that computed result. Then VERIFY THE CALCULATION YOURSELF from the values in the evidence: every operand must have an explicit value in the evidence AND be the RIGHT entity; recompute and check the report's stated result matches. If any operand's figure is absent, or the operands are the wrong entities, or the recomputed result disagrees, the computed assertion is UNGROUNDED (name the missing/wrong operand or the recomputed vs stated value). + +## Part C — Missing pieces (forward gap) + +`missing_information` = what the answer STILL needs but the evidence does NOT contain, with a searchable hint. This is the targeted re-search signal (Google Query Rewriter input). It is distinct from `ungrounded_assertions`: +- `ungrounded_assertions` = the draft asserted something the evidence does NOT support -> drop/correct it. +- `missing_information` = the answer REQUIRES a fact/entity/value the evidence lacks -> search for it. + +Populate `missing_information` when, even if every draft is grounded, the evidence does NOT cover a part the question asks for. Examples: +- the question asks for a specific property (age / year / employer / distance / count) and the evidence has the entity but not that property; +- a disambiguation is needed (evidence has a same-named but wrong entity); +- the evidence covers only part of an enumeration (some list members present, others absent). + +Each `missing_information` item MUST carry a concrete `search_hint`: a searchable query (keywords / qualifiers / the specific entity+relation) that would retrieve the missing fact. Leave empty when the evidence is complete. + +## Output format (JSON) — ONE object, no commentary before/after + +```json +{ + "is_sufficient": true, + "confidence": 0.0, + "required_entities": ["Entity 1"], + "contradictions": ["conflicting figures if any"], + "reasoning": "step-by-step sufficiency judgment", + "sub_queries": [ + { + "sub_query": "Which team's name was inspired by the Boston Braves?", + "satisfied": true + }, + { + "sub_query": "Who is that team's president?", + "satisfied": false, + "missing_fact": "the team's current president", + "search_hint": "Washington Commanders president 2024" + } + ], + "claims": [ + { + "claim_id": "c1", + "grounded": true, + "ungrounded_assertions": [], + "missing_information": [ + {"what": "the specific missing fact the answer needs", "search_hint": "searchable query to retrieve it"} + ] + } + ] +} +``` + +## Requirements + +0. **The TOP-LEVEL output is ONE single JSON object.** `claims` is an array FIELD inside that object — never wrap the whole output in an array, and never output just the `claims` array. The output must start with `{` and end with `}`. +1. `is_sufficient` true iff a plausible answer can be inferred from the context (Part A). Use the paper's SUFFICIENT-CONTEXT criterion: sufficient means a plausible answer can be constructed from the context — it does NOT need to be provably correct or complete. **A missing detail that a rough/partial answer can still accommodate does NOT make the context insufficient** — if the context lets you infer ANY plausible answer, mark sufficient (the presentation layer decides whether to caveat). Only when the context cannot support ANY plausible answer is it insufficient, and then your job is to say exactly what is missing (Part C). +2. `confidence` (0-1): how confident you are in the sufficiency decision. 0.9-1.0 if clearly sufficient/fails; 0.5-0.7 if partial/ambiguous; below 0.5 if you cannot tell. +3. `contradictions`: list internally conflicting figures/statements that make a single answer ambiguous. Empty array when none. +4. `claims` is MANDATORY and must NEVER be empty when there is at least one claim draft. Include EVERY claim_id exactly once. For each claim you must output `grounded`, `ungrounded_assertions`, AND `missing_information`. Do NOT omit any claim or any field. +5. `missing_information` is the MOST IMPORTANT field when `is_sufficient` is false. It is what drives the next search. When the context is insufficient, you MUST list, per claim, the concrete facts/entities/relations that are absent but required — each with a searchable `search_hint`. An empty `missing_information` is only acceptable when the claim is fully covered. **Never output an empty `claims` array while also saying `is_sufficient: false`** — that is a contradiction and aborts the whole search. If you judge the context insufficient, your primary job is to say exactly WHAT is missing and WHERE to search next. +6. `sub_queries` is MANDATORY (may be an empty array only when there is nothing to decompose). Emit the full step-by-step sub-query set from Part A stage 1, each marked `satisfied`. A `satisfied: false` entry MUST carry `missing_fact` + `search_hint` and is the precise "what to search next" signal — the Query Rewriter turns exactly those into the next round's queries. Keep sub-queries mutually-exclusive and fully-covering (no overlap, no gap beyond the unsatisfied ones). +7. `ungrounded_assertions` empty when grounded; otherwise list each with a one-line `reason`. +8. `reasoning` should be concise and clear. diff --git a/internal/rag/prompts/templates.go b/internal/rag/prompts/templates.go new file mode 100644 index 00000000000..ba2ea97753b --- /dev/null +++ b/internal/rag/prompts/templates.go @@ -0,0 +1,92 @@ +// +// 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. +// + +package prompts + +import ( + "embed" + "fmt" + "regexp" + "strings" +) + +// Prompt template loading, the Go mirror of Python rag/prompts/template.py +// ::load_prompt. Python reads {name}.md from rag/prompts/ at import time; the +// Go column keeps the authoritative copy of each template as a .md embedded +// here so the binary is self-contained and survives the Python source being +// deleted. +// +// The templates mirrored by this package (action_run, action_initialize_state, +// consumed by the harness action session; sca_select and sca_query_rewrite, +// consumed by the orchestrator) were previously duplicated as copies under +// harness/prompts/. They are now unified here, with the harness wiring its +// PromptLoader default to this package's embedded loader. + +//go:embed action_run.md action_initialize_state.md sca_select.md sca_query_rewrite.md citation_prompt.md +var templatesFS embed.FS + +// EmbeddedPromptLoader serves the bundled .md templates by name. Load returns +// an error when the named template is absent, so a caller's fallback path +// engages exactly as with the previous per-package loaders. +type EmbeddedPromptLoader struct{} + +// Load implements the harness PromptLoader contract: Load(name string) +// (string, error), reading ".md" and returning its content trimmed. +func (EmbeddedPromptLoader) Load(name string) (string, error) { + data, err := templatesFS.ReadFile(name + ".md") + if err != nil { + return "", fmt.Errorf("internal/rag/prompts: template %q: %w", name, err) + } + return strings.TrimSpace(string(data)), nil +} + +// Loader is the minimal template-source contract used by Render. It mirrors the +// harness PromptLoader shape (Load(name string) (string, error)) so any loader +// wired into the harness (including EmbeddedPromptLoader and the in-memory test +// loader) satisfies it without the prompts package importing harness. +type Loader interface { + Load(name string) (string, error) +} + +// leftoverVarRE matches a Jinja variable placeholder that no provided var +// filled in. Python renders these through PROMPT_JINJA_ENV's default Undefined +// (SandboxedEnvironment without undefined=StrictUndefined), which interpolates +// as the empty string; the regex mirrors that instead of leaving {{ var }} +// verbatim in the prompt. +var leftoverVarRE = regexp.MustCompile(`\{\{\s*[A-Za-z_][A-Za-z0-9_.]*\s*\}\}`) + +// Render loads `name` and substitutes the {{var}} placeholders the way +// PROMPT_JINJA_ENV.from_string(...).render(...) does on the Python side. A nil +// loader defaults to the embedded canonical .md templates (1:1 copies of the +// Python rag/prompts/*.md); a loader that cannot resolve `name` falls back to +// `fallback`. Unprovided variables render as the empty string (Jinja default +// Undefined), not as a literal placeholder. +func Render(loader Loader, name, fallback string, vars map[string]string) string { + if loader == nil { + loader = EmbeddedPromptLoader{} + } + tmpl := fallback + if t, err := loader.Load(name); err == nil && strings.TrimSpace(t) != "" { + tmpl = t + } + for k, v := range vars { + // Jinja tolerates both `{{var}}` and `{{ var }}`; the project's + // templates use the spaced form, so substitute both. + tmpl = strings.ReplaceAll(tmpl, "{{"+k+"}}", v) + tmpl = strings.ReplaceAll(tmpl, "{{ "+k+" }}", v) + } + return leftoverVarRE.ReplaceAllString(tmpl, "") +} diff --git a/internal/rag/prompts/templates_test.go b/internal/rag/prompts/templates_test.go new file mode 100644 index 00000000000..7b5c3e7a2a1 --- /dev/null +++ b/internal/rag/prompts/templates_test.go @@ -0,0 +1,163 @@ +// +// 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. +// + +package prompts + +import ( + "strings" + "testing" +) + +// TestEmbeddedLoaderCanonicalTemplates makes sure every template the Go column +// relies on is actually embedded and stripped the way Python's load_prompt +// strips the canonical rag/prompts/*.md files. +func TestEmbeddedLoaderCanonicalTemplates(t *testing.T) { + names := []string{ + "action_run", + "action_initialize_state", + "sca_select", + "sca_query_rewrite", + } + for _, name := range names { + got, err := (EmbeddedPromptLoader{}).Load(name) + if err != nil { + t.Fatalf("Load(%q): %v", name, err) + } + if got == "" { + t.Errorf("Load(%q) returned an empty template", name) + } + if strings.TrimSpace(got) != got { + t.Errorf("Load(%q) returned surrounding whitespace (load_prompt strips both ends)", name) + } + } +} + +// TestEmbeddedLoaderMissingName reports an error for templates we do not embed, +// so the caller's fallback engages exactly like load_prompt's FileNotFoundError. +func TestEmbeddedLoaderMissingName(t *testing.T) { + if _, err := (EmbeddedPromptLoader{}).Load("no_such_template"); err == nil { + t.Fatal("Load(no_such_template) succeeded, want error") + } +} + +// TestRenderPromptNilLoaderUsesEmbeddedCanonical locks in that an unset loader +// now resolves the canonical embedded .md (1:1 with rag/prompts/sca_select.md) +// rather than the condensed constant — the whole point of the orchestration +// parity fix. +func TestRenderPromptNilLoaderUsesEmbeddedCanonical(t *testing.T) { + vars := map[string]string{"question": "Q?", "overall_draft": "D", "claims_context": "C"} + got := Render(nil, "sca_select", "", vars) + + for _, frag := range []string{ + `Google-style "Sufficient Context Agent"`, // canonical sca_select.md only + "Q?", + "D", + "C", + } { + if !strings.Contains(got, frag) { + t.Errorf("canonical sca_select render missing %q", frag) + } + } + if strings.Contains(got, "{{") { + t.Errorf("render left an unresolved placeholder: %q", got) + } +} + +// TestRenderPromptNilLoaderQueryRewriteCanonical is the rewrite-side twin: +// nil loader must resolve the full embedded sca_query_rewrite.md, not the +// condensed constant. + +// TestRenderPromptNilLoaderQueryRewriteCanonical is the rewrite-side twin: +// nil loader must resolve the full embedded sca_query_rewrite.md, not the +// condensed constant. +func TestRenderPromptNilLoaderQueryRewriteCanonical(t *testing.T) { + vars := map[string]string{ + "question": "Q?", + "gaps": "G", + "bridge_values": "B", + "research_context": "R", + } + got := Render(nil, "sca_query_rewrite", "", vars) + + // Rule 1 wording exists only in the canonical template. + if !strings.Contains(got, "The query must name the specific missing entity") { + t.Errorf("canonical sca_query_rewrite render not used; got:\n%s", got) + } + for _, frag := range []string{"Q?", "G", "B", "R"} { + if !strings.Contains(got, frag) { + t.Errorf("canonical sca_query_rewrite render missing %q", frag) + } + } + if strings.Contains(got, "{{") { + t.Errorf("render left an unresolved placeholder: %q", got) + } +} + +// TestRenderUnknownNameWithEmptyFallbackReturnsEmpty mirrors Python's +// fail-fast loading: Go has no condensed fallback constant (unlike the earlier +// prototype), so a loader that cannot resolve the name with fallback="" yields +// the empty string rather than a degraded prompt. + +// TestRenderUnknownNameWithEmptyFallbackReturnsEmpty mirrors Python's +// fail-fast loading: Go has no condensed fallback constant (unlike the earlier +// prototype), so a loader that cannot resolve the name with fallback="" yields +// the empty string rather than a degraded prompt. +func TestRenderUnknownNameWithEmptyFallbackReturnsEmpty(t *testing.T) { + got := Render(stubLoader{}, "no_such_template", "", + map[string]string{"question": "Q?", "gaps": "G"}) + if got != "" { + t.Errorf("expected empty string for unknown template with empty fallback, got:\n%s", got) + } +} + +// TestRenderPromptMissingVarInterpolatesEmpty mirrors Python's default Jinja +// Undefined: an unprovided variable renders as the empty string, not as a +// literal {{ var }}. + +// TestRenderPromptMissingVarInterpolatesEmpty mirrors Python's default Jinja +// Undefined: an unprovided variable renders as the empty string, not as a +// literal {{ var }}. +func TestRenderPromptMissingVarInterpolatesEmpty(t *testing.T) { + loader := stubLoader{text: "A={{present}} B={{ absent }} C={{absent}}"} + got := Render(loader, "t", "fallback", map[string]string{"present": "x"}) + if want := "A=x B= C="; got != want { + t.Errorf("render = %q, want %q", got, want) + } +} + +// TestRenderPromptSubstitutesBothPlaceholderSpellings: Jinja tolerates the +// spaced and unspaced forms; the renderer must handle both. + +// TestRenderPromptSubstitutesBothPlaceholderSpellings: Jinja tolerates the +// spaced and unspaced forms; the renderer must handle both. +func TestRenderPromptSubstitutesBothPlaceholderSpellings(t *testing.T) { + loader := stubLoader{text: "{{v}}|{{ v }}"} + got := Render(loader, "t", "fallback", map[string]string{"v": "x"}) + if want := "x|x"; got != want { + t.Errorf("render = %q, want %q", got, want) + } +} + +// stubLoader serves a canned template, mirroring how tests wire +// harness.StringPromptLoader. +type stubLoader struct{ text string } + +func (s stubLoader) Load(string) (string, error) { return s.text, nil } + +// TestRenderPromptNilLoaderUsesEmbeddedCanonical locks in that an unset loader +// now resolves the canonical embedded .md (1:1 with rag/prompts/sca_select.md) +// rather than the condensed constant — the whole point of the orchestration +// parity fix. diff --git a/internal/service/chat_pipeline.go b/internal/service/chat_pipeline.go index dedd4c381db..f67c95415ac 100644 --- a/internal/service/chat_pipeline.go +++ b/internal/service/chat_pipeline.go @@ -32,6 +32,7 @@ import ( "regexp" "sort" "strings" + "sync" "time" "ragflow/internal/dao" @@ -601,11 +602,14 @@ func (s *ChatPipelineService) AsyncChat( timer.Exit(common.PhaseQueryRefinement) // === Phase 9: Retrieval === - promptReasoning, _ := chat.PromptConfig["reasoning"].(bool) - kwargReasoning, _ := kwargs["reasoning"].(bool) - useReasoning := promptReasoning || kwargReasoning + // reasoning is an integer level 0..4 (mirrors Python rag_agent): 0 = off + // (regular RAG via async_chat), 1..4 = low/medium/high/ultra (harness + // agentic). It comes from the request kwargs first, then prompt_config. + reasoningLevel := resolveReasoningLevel(kwargs, map[string]interface{}(chat.PromptConfig)) + useReasoning := reasoningLevel > 0 common.Info("Phase 9: Retrieval", zap.Bool("has_knowledge_param", hasKnowledgeParam), + zap.Int("reasoning_level", reasoningLevel), zap.Bool("reasoning", useReasoning)) timer.Enter(common.PhaseRetrieval) @@ -632,54 +636,137 @@ func (s *ChatPipelineService) AsyncChat( // When false, the entire block is skipped. if hasKnowledgeParam { if useReasoning && chatModel != nil && len(kbs) > 0 { - // DeepResearcher — replaces vector retrieval. - // Yields / markers + intermediate messages. - docEngine := engine.Get() - if docEngine != nil { - retSvc := nlp.NewRetrievalService(docEngine, dao.NewDocumentDAO()) - tenantIDs := kbTenantIDStrings(kbs) - kbIDs := kbIDStrings(kbs) - - // KB retrieval callback for the deep researcher - kbRetrieve := func(ctx context.Context, q string) (*nlp.RetrievalResult, error) { - return retSvc.Retrieval(ctx, &nlp.RetrievalRequest{ - Question: q, - TenantIDs: tenantIDs, - KbIDs: kbIDs, - DocIDs: docIDs, - Page: 1, - PageSize: int(chat.TopN), - RerankCandidatesCount: &rerankCandidatesCount, - EmbeddingModel: embModel, + // Reasoning chat (level 1..4): drive the agentic-RAG harness at + // the corresponding mode, mirroring Python's dialog_service → + // RAGTools → harness/*. + // + // The harness 'rag' tool composes the final cited answer itself + // (terminal tool, mirroring Python). When it returns a non-empty + // Answer we emit that answer directly (decorated per Python's + // decorate_answer: references resolved, prompt empty) and stop — + // there is no second-generation pass in Phase 10/11. Otherwise + // we keep its evidence as kbinfos and fall through. + thinkingMode := harnessModeForLevel(reasoningLevel) + question := strings.Join(questions, " ") + // Stream the answer as the harness composes it (Python + // tools.answer_sink). The final event below still carries the + // complete answer plus references, matching how the non-agentic + // path streams deltas and then re-sends the full answer + // (dialog_service.py:807). + // + // isThink marks pieces of the harness's hidden reasoning block + // (the final-answer model's native reasoning). Frame them like + // the tool path above (ChatStreamlyWithTools): StartToThink → + // Reasoning → EndToThink, so every SSE consumer (chat_session, + // bot_completion, openai_chat) sees the standard think framing. + // Reasoning text is deliberately kept on the Reasoning field + // (not Answer) so OpenAI-compat maps it to reasoning_content. + harnessThinking := false + // answerStreamed records that an answer delta already reached the + // client, which makes any LATER think delta unrenderable: the UI + // would show a stray "Thought" block after the finished answer. + // + // That is what the loop narration around the single harness call + // would otherwise do: "…produced the final answer, done." is emitted + // after retrieveViaHarness returns, but the answer itself streams + // DURING it. Python logs that line immediately before yielding the + // terminal tool's answer (chat_model.py:799-802), so its "done" line + // still belongs to the thinking phase. Same for late engine-progress + // lines (concurrent research slots); a thought block after the answer + // is never useful. + answerStreamed := false + // Engine progress (B) is pushed from concurrent research-slot + // goroutines while the final compose runs on the main goroutine, so + // serialize the think-framing state machine and the out<-send. + var sinkMu sync.Mutex + sink := func(delta string, isThink bool) { + sinkMu.Lock() + defer sinkMu.Unlock() + send := func(ev AsyncChatResult) { + select { + case out <- ev: + case <-ctx.Done(): + } + } + if isThink { + if answerStreamed { + // Never reopen a thought block after the answer: drop the + // late narration/progress line instead. + return + } + if !harnessThinking { + harnessThinking = true + send(AsyncChatResult{ + Reference: map[string]interface{}{}, + CreatedAt: float64(time.Now().Unix()), + Final: false, + StartToThink: true, + }) + } + if delta != "" { + send(AsyncChatResult{ + Reasoning: delta, + Reference: map[string]interface{}{}, + CreatedAt: float64(time.Now().Unix()), + Final: false, + }) + } + return + } + if harnessThinking { + harnessThinking = false + send(AsyncChatResult{ + Reference: map[string]interface{}{}, + CreatedAt: float64(time.Now().Unix()), + Final: false, + EndToThink: true, }) } - - dr := NewDeepResearcher( - chatModel, - map[string]interface{}(chat.PromptConfig), - kbRetrieve, - useWebSearch, - docEngine, - kbIDs, - tenantIDs, - embModel, - ) - question := strings.Join(questions, " ") - - drErr := dr.Research(ctx, kbinfos, question, question, s.deepResearchProgressCallback(ctx, out)) - if drErr != nil { - common.Warn("DeepResearcher failed", zap.Error(drErr)) - } else { - // kbinfos now contains real chunks with proper - // chunk_ids from the recursive tree search. - common.Debug("DeepResearcher completed", - zap.Int("chunks", len(kbinfos["chunks"].([]map[string]interface{})))) + if delta != "" { + answerStreamed = true + send(AsyncChatResult{ + Answer: delta, + Reference: map[string]interface{}{}, + CreatedAt: float64(time.Now().Unix()), + Final: false, + }) + } + } + // The harness streams think-then-answer inside ONE compose call; + // if it never reached a non-think delta (reasoning-only output) + // close the block so no consumer sees an unpaired . + defer func() { + if harnessThinking { + sink("", false) + } + }() + // Python dialog_service.py:2077 — the web provider is handed to + // RAGTools only when the internet flag enables web search; + // otherwise web_search stays off the agentic tool surface. + var webSearch func(context.Context, []string) ([]string, error) + if s.shouldUseWebSearch(chat, kwargs["internet"]) { + webSearch = s.harnessWebSearchFunc(chat.PromptConfig) + } + hk, harnessAnswer, hErr := s.retrieveViaHarness(ctx, question, kbs, docIDs, imageFiles, attachments, thinkingMode, chat.TenantID, chat.LLMID, chat.ID, webSearch, sink) + if hErr != nil { + common.Warn("harness retrieval failed", zap.Error(hErr)) + } else { + kbinfos = hk + if harnessAnswer != "" { + common.Info("harness produced final cited answer; short-circuiting", + zap.Int("answer_chars", len(harnessAnswer))) + final := s.decorateHarnessAnswer(harnessAnswer, kbinfos) + final.Final = true + out <- final + return } } } else { + // Non-reasoning chat (level 0): regular RAG mirroring Python's + // async_chat — native docStore retrieval, then the TOC / child + // chunk / web search / KG enhancements below. searchQuestion := strings.Join(questions, " ") if embModel != nil { - // Retrieval rankFeature := s.MetadataSvc.LabelQuestion(ctx, searchQuestion, kbs) { tenantIDs := make([]string, 0) @@ -740,22 +827,22 @@ func (s *ChatPipelineService) AsyncChat( common.Warn("Retrieval failed", zap.Error(err)) // Continue with empty kbinfos. } + } - // TOC enhancement - if useTOC, _ := chat.PromptConfig["toc_enhance"].(bool); useTOC && chatModel != nil && len(kbs) > 0 { - enhancer := NewTOCEnhancer( - engine.Get(), - chatModel, - kbTenantIDStrings(kbs), - kbIDStrings(kbs), - searchQuestion, - int(chat.TopN), - ) - if added, err := enhancer.Enhance(ctx, kbinfos); err != nil { - common.Warn("TOC enhance failed", zap.Error(err)) - } else if added > 0 { - common.Debug("TOC enhance added chunks", zap.Int("added", added)) - } + // TOC enhancement + if useTOC, _ := chat.PromptConfig["toc_enhance"].(bool); useTOC && chatModel != nil && len(kbs) > 0 { + enhancer := NewTOCEnhancer( + engine.Get(), + chatModel, + kbTenantIDStrings(kbs), + kbIDStrings(kbs), + searchQuestion, + int(chat.TopN), + ) + if added, err := enhancer.Enhance(ctx, kbinfos); err != nil { + common.Warn("TOC enhance failed", zap.Error(err)) + } else if added > 0 { + common.Debug("TOC enhance added chunks", zap.Int("added", added)) } } @@ -1768,6 +1855,39 @@ func (s *ChatPipelineService) shouldUseWebSearch(chat *entity.Chat, internet int return normalized != nil && *normalized } +// harnessWebSearchFunc builds the callback the agentic harness' web_search tool +// invokes (Python RAGTools(web_search=...)). It resolves the provider once and +// runs one provider query per requested query, flattening each result's chunk +// text. A per-query failure is logged and skipped — mirroring Python +// _exec_web_search, where one bad query must not fail the whole tool call. +// Returns nil when no provider is configured so the tool stays hidden. +func (s *ChatPipelineService) harnessWebSearchFunc(promptConfig map[string]interface{}) func(context.Context, []string) ([]string, error) { + provider := resolveWebSearchProvider(promptConfig) + if provider == nil { + return nil + } + return func(ctx context.Context, queries []string) ([]string, error) { + out := make([]string, 0, len(queries)*6) + for _, q := range queries { + if strings.TrimSpace(q) == "" { + continue + } + res, err := s.retrieveWebSearch(ctx, provider, q) + if err != nil { + common.Warn("harness web search failed for a query", zap.Error(err)) + continue + } + chunks, _ := res["chunks"].([]map[string]interface{}) + for _, c := range chunks { + if text := getMapString(c, "content_with_weight", "content"); text != "" { + out = append(out, text) + } + } + } + return out, nil + } +} + // tavilyRetrieve calls the Tavily API and returns results in the same chunk // format used by performRetrieval. Mirrors Python's Tavily.retrieve_chunks() // in rag/utils/tavily_conn.py. @@ -2936,6 +3056,106 @@ func (s *ChatPipelineService) decorateAnswer( } } +// decorateHarnessAnswer mirrors Python's rag_agent decorate_answer used on the +// reasoning>=1 path (dialog_service.py:2092-2137). The harness 'rag' tool +// already composed the final answer WITH its own [ID:N] citations, so — unlike +// decorateAnswer for the native async_chat path — we never run insert_citations +// here. We only resolve the existing markers, repair bad formats, filter +// doc_aggs to the cited docs, and build the reference from the harness citation +// pool (chunks stripped of their vectors). Prompt stays empty, matching Python. +func (s *ChatPipelineService) decorateHarnessAnswer(answer string, kbinfos map[string]interface{}) AsyncChatResult { + think := "" + ans := answer + if strings.Contains(answer, "") { + if parts := strings.Split(answer, ""); len(parts) == 2 { + think = parts[0] + "" + ans = strings.TrimSpace(parts[1]) + } + } + + chunksRaw, _ := kbinfos["chunks"].([]map[string]interface{}) + + // Collect existing [ID:N] markers from the harness answer. Python runs + // normalize_arabic_digits then CITATION_MARKER_PATTERN (dialog_service.py: + // 2103-2107) and bounds each index by len(chunks). + citationIdx := make(map[int]struct{}) + for _, ci := range ExtractCitationMarkers(ans, len(chunksRaw)) { + if ci >= 0 && ci < len(chunksRaw) { + citationIdx[ci] = struct{}{} + } + } + // repair_bad_citation_formats (dialog_service.py:2109), then re-scan so any + // repaired markers are also honoured. + ans = RepairBadCitationFormats(ans) + for _, ci := range ExtractCitationMarkers(ans, len(chunksRaw)) { + if ci >= 0 && ci < len(chunksRaw) { + citationIdx[ci] = struct{}{} + } + } + + // Map cited chunk indices to doc_ids (dialog_service.py:2111-2122). + citedDocIDs := make(map[string]struct{}) + for ci := range citationIdx { + if ci >= 0 && ci < len(chunksRaw) { + if docID, ok := chunksRaw[ci]["doc_id"].(string); ok && docID != "" { + citedDocIDs[docID] = struct{}{} + } + } + } + + // recall_docs = cited docs, or all when nothing cited (dialog_service.py: + // 2124-2127). Only rewrite doc_aggs when we actually found cited docs. + if len(citedDocIDs) > 0 { + if docAggsRaw, ok := kbinfos["doc_aggs"].([]interface{}); ok && len(docAggsRaw) > 0 { + filtered := make([]interface{}, 0, len(docAggsRaw)) + for _, da := range docAggsRaw { + if dam, ok := da.(map[string]interface{}); ok { + if docID, ok := dam["doc_id"].(string); ok { + if _, cited := citedDocIDs[docID]; cited { + filtered = append(filtered, da) + } + } + } + } + if len(filtered) > 0 { + kbinfos["doc_aggs"] = filtered + } + } + } + + // refs = deepcopy(kbinfos) if doc_ids else [] ; drop each chunk's vector + // (dialog_service.py:2129-2132). AsyncChatResult.Reference is a map, so an + // empty Python [] maps to a nil map (callers/frontend already tolerate a + // missing reference). + var refs map[string]interface{} + if len(citedDocIDs) > 0 { + ref := make(map[string]interface{}) + for k, v := range kbinfos { + ref[k] = v + } + if cRaw, ok := ref["chunks"].([]map[string]interface{}); ok { + for _, cm := range cRaw { + delete(cm, "vector") + } + ref["chunks"] = cRaw + } + refs = ref + } + + // Invalid-key hint (dialog_service.py:2134-2135). + if strings.Contains(strings.ToLower(ans), "invalid key") || + strings.Contains(strings.ToLower(ans), "invalid api") { + ans += " Please set LLM API-Key in 'User Setting -> Model providers -> API-Key'" + } + + return AsyncChatResult{ + Answer: think + ans, + Reference: refs, + Prompt: "", + CreatedAt: float64(time.Now().Unix()), + } +} + // langfuseExtractTimeElapsed extracts the time-elapsed + token-usage // block from the prompt and applies the \n → " \n" substitution. // Mirrors dialog_service.py:853-854: @@ -4420,3 +4640,236 @@ func getChunkValue(chunk map[string]interface{}, k1, k2 string) interface{} { } return chunk[k2] } + +// HarnessRequest carries the minimal inputs the chat pipeline hands to the +// agentic-RAG harness for evidence collection. +type HarnessRequest struct { + Question string + DatasetIDs []string + // DocIDs scopes the agentic search to these document ids (Python + // dialog_service.py doc_scope). chat_pipeline folds the chat-level + // meta_data_filter into docIDs before calling, so forwarding this alone + // restores both doc_ids and meta_data_filter scoping without double-filtering. + DocIDs []string + ThinkingMode string + TenantID string + // ModelID is the tenant-scoped chat model id (dialog llm_id). The harness + // driver uses it as the default model name for agentic LLM turns. + ModelID string + // SessionID scopes cross-turn state such as the near-duplicate answer cache + // (Python RAGTools._rag_cache lives on an instance spanning the dialog). + SessionID string + // AnswerSink receives the answer as the model produces it (Python + // tools.answer_sink), so the caller can stream instead of waiting for the + // whole answer. Nil disables streaming; the full answer is still returned. + AnswerSink func(delta string, isThink bool) + // Images are vision-gated base64 data URIs (Python image_attachments) that + // survive gateImageAttachments. They ride the last user message into the + // outer react loop so a vision model can see them. chat_pipeline drops them + // for text-only models, so only surviving URIs reach here. + Images []string + // TextAttachments is the joined text-file content (Python + // text_attachments_content); it is appended to the last user message so the + // model reads attached documents even in the reasoning path. + TextAttachments string + // WebSearch runs an open-web search for the harness' web_search tool + // (Python RAGTools(web_search=create_web_search_provider(...))). Nil hides + // the tool from the agentic surface, mirroring Python's provider gate + // (action_session.py:463 discards web_search when tools.web_search is None). + WebSearch func(ctx context.Context, queries []string) ([]string, error) +} + +// HarnessResult is the evidence the harness returns, normalized to the map +// shape chat_pipeline's downstream phases already consume. +type HarnessResult struct { + Chunks []map[string]any + DocAggs []map[string]any + Memory []map[string]any + PreSummary string + // Answer is the harness's own composed final cited answer (RunResponse.Answer), + // populated when a model was available. When non-empty, the chat pipeline uses + // it directly as the reply instead of re-generating via a second model pass — + // mirroring Python's terminal `rag` tool. + Answer string +} + +// harnessRetriever is wired at server bootstrap (cmd/ragflow_server.go:889) to +// the agentic-RAG entry point advanced_rag.Rag (:1022). The advanced_rag package +// imports internal/service (e.g. harness/tool_exploration.go), so the service +// layer cannot import it back without an import cycle; the function is injected +// instead. When nil, retrieveViaHarness reports an error and the pipeline +// continues with empty kbinfos. +var harnessRetriever func(ctx context.Context, req HarnessRequest) (HarnessResult, error) + +// SetHarnessRetriever injects the agentic-RAG harness driver. Call once at +// server bootstrap. +func SetHarnessRetriever(fn func(ctx context.Context, req HarnessRequest) (HarnessResult, error)) { + harnessRetriever = fn +} + +// retrieveViaHarness collects evidence chunks for the chat question by driving +// the agentic-RAG harness, mirroring Python's dialog_service → RAGTools → +// harness/* path. It returns the same map shape the downstream phases +// (TOC/child-chunk/web/KG/enrich/kbPrompt) already consume, so the rest of the +// chat pipeline is unaffected by where the chunks came from. +// +// thinkingMode is "naive" (reasoning disabled) or one of the agentic levels +// ("low"/"medium"/"high"/"ultra", reasoning enabled). +// toolLoopLine forwards one Python "[Tool loop]" line into the chat think +// block. Mirrors rag/llm/chat_model.py:689 ("Deciding what to do next +// (step N); available tools: ..."), :782 ("Step N: running X...") and +// :799/:804 ("The X tool produced the final answer, done." / "produced an +// observation for step N."), which Python forwarded via the +// "rag.llm.chat_model" namespace in _SCOPED_PREFIXES. +// +// ARCHITECTURAL NOTE. Python's outer model calls rag() as a @tool inside a +// for-loop, and those lines narrate that loop. Go's chat pipeline invokes the +// harness DIRECTLY (there is no outer tool-calling loop for it; the only +// ReAct loop in Go is the canvas Agent component, which drives different +// tools). So the faithful Go equivalent is to bracket the single harness +// invocation here rather than to instrument a loop that does not exist. +// +// Python emitted "
" + msg for its HTML think block (think_log.py:69); the +// chat UI renders the block as HTML/markdown, where a bare "\n" collapses into +// a space and the stage lines merge. Keep the same separator here. The literal +// is spelled out instead of reusing advanced_rag.ThinkLineBreak because +// advanced_rag/harness imports this package (import cycle). +const thinkLineBreak = "
" + +func toolLoopLine(sink func(delta string, isThink bool), line string) { + if sink == nil { + return + } + sink(line+thinkLineBreak, true) +} + +func (s *ChatPipelineService) retrieveViaHarness(ctx context.Context, question string, kbs []*entity.Knowledgebase, docIDs []string, images []string, textAttachments string, thinkingMode, tenantID, modelID, sessionID string, webSearch func(context.Context, []string) ([]string, error), answerSink func(delta string, isThink bool)) (map[string]interface{}, string, error) { + if harnessRetriever == nil { + return nil, "", fmt.Errorf("harness retriever not wired at bootstrap") + } + kbIDs := kbIDStrings(kbs) + // Only non-naive modes run the agentic loop these lines describe, and only + // reasoning chats stream a think block at all. + narrate := thinkingMode != "naive" + if narrate { + toolLoopLine(answerSink, "[Tool loop] Deciding what to do next (step 1); available tools: rag") + toolLoopLine(answerSink, "[Tool loop] Step 1: running rag...") + } + res, err := harnessRetriever(ctx, HarnessRequest{ + Question: question, + DatasetIDs: kbIDs, + DocIDs: docIDs, + ThinkingMode: thinkingMode, + TenantID: tenantID, + ModelID: modelID, + SessionID: sessionID, + AnswerSink: answerSink, + Images: images, + TextAttachments: textAttachments, + WebSearch: webSearch, + }) + if err != nil { + return nil, "", err + } + if narrate { + // Python distinguishes the terminal tool from an observation: an answer + // ends the loop, otherwise the result feeds the next round. + if res.Answer != "" { + toolLoopLine(answerSink, "[Tool loop] The rag tool produced the final answer, done.") + } else { + toolLoopLine(answerSink, "[Tool loop] The rag tool produced an observation for step 1.") + } + } + + kbinfos := map[string]interface{}{ + "total": len(res.Chunks), + "chunks": res.Chunks, + "doc_aggs": toAnySlice(res.DocAggs), + } + if res.Memory != nil { + kbinfos["memory"] = res.Memory + } + if res.PreSummary != "" { + kbinfos["pre_summary"] = res.PreSummary + } + return kbinfos, res.Answer, nil +} + +// toAnySlice widens a []map[string]any to []interface{} so the doc_aggs field +// keeps the element type the downstream phases expect from the native pipeline. +func toAnySlice(in []map[string]any) []interface{} { + out := make([]interface{}, 0, len(in)) + for _, m := range in { + out = append(out, m) + } + return out +} + +// asInt64 coerces a JSON-decoded value (float64/json.Number/int/string/bool) to +// an int64, returning ok=false when the value is absent or not numeric. +func asInt64(v interface{}) (int64, bool) { + switch t := v.(type) { + case float64: + return int64(t), true + case int: + return int64(t), true + case int64: + return t, true + case json.Number: + if n, err := t.Int64(); err == nil { + return n, true + } + case string: + var n int64 + if _, err := fmt.Sscanf(t, "%d", &n); err == nil { + return n, true + } + case bool: + if t { + return 1, true + } + return 0, true + } + return 0, false +} + +// resolveReasoningLevel mirrors Python's rag_agent: the requesting reasoning +// level is taken from the request kwargs first, falling back to the chat +// prompt_config, and is an integer in 0..4 (0 = off, 1..4 = low/medium/high/ +// ultra). Frontend sends Number(getThinkingLevel()), so the raw value is +// numeric, not a bool. +func resolveReasoningLevel(kwargs map[string]interface{}, promptConfig map[string]interface{}) int { + if kwargs != nil { + if v, ok := kwargs["reasoning"]; ok { + if n, ok2 := asInt64(v); ok2 { + return int(n) + } + } + } + if promptConfig != nil { + if v, ok := promptConfig["reasoning"]; ok { + if n, ok2 := asInt64(v); ok2 { + return int(n) + } + } + } + return 0 +} + +// harnessModeForLevel maps a Python-style reasoning level to the harness +// thinking mode. Python uses THINKING_MODES = [low, medium, high, ultra] and +// falls back to "medium" when n is out of range. +func harnessModeForLevel(level int) string { + switch { + case level >= 4: + return "ultra" + case level == 3: + return "high" + case level == 2: + return "medium" + case level == 1: + return "low" + default: + return "medium" + } +} diff --git a/internal/service/chat_pipeline_test.go b/internal/service/chat_pipeline_test.go index 4999e1f49b4..41946abdedd 100644 --- a/internal/service/chat_pipeline_test.go +++ b/internal/service/chat_pipeline_test.go @@ -1540,3 +1540,106 @@ func TestClampChatConfigMaxTokensRejectsExhaustedCapacity(t *testing.T) { } } } + +// stubHarness installs a fake harnessRetriever returning the given answer and +// restores the previous one when the test ends. +func stubHarness(t *testing.T, answer string) { + t.Helper() + prev := harnessRetriever + t.Cleanup(func() { harnessRetriever = prev }) + harnessRetriever = func(ctx context.Context, req HarnessRequest) (HarnessResult, error) { + return HarnessResult{Answer: answer}, nil + } +} + +// collectSink records every delta with its isThink flag. +func collectSink(got *[]string, thinks *[]bool) func(string, bool) { + return func(delta string, isThink bool) { + *got = append(*got, delta) + *thinks = append(*thinks, isThink) + } +} + +// TestRetrieveViaHarnessEmitsToolLoopLines covers the Python +// rag/llm/chat_model.py "[Tool loop]" lines that think_log forwarded from the +// "rag.llm.chat_model" namespace. +func TestRetrieveViaHarnessEmitsToolLoopLines(t *testing.T) { + stubHarness(t, "the final cited answer") + + var got []string + var thinks []bool + s := &ChatPipelineService{} + _, answer, err := s.retrieveViaHarness(context.Background(), "q", nil, nil, nil, "", "high", "t", "m", "sess", nil, collectSink(&got, &thinks)) + if err != nil { + t.Fatalf("retrieveViaHarness: %v", err) + } + if answer != "the final cited answer" { + t.Fatalf("answer = %q", answer) + } + + joined := strings.Join(got, "") + for _, want := range []string{ + "[Tool loop] Deciding what to do next (step 1); available tools: rag", + "[Tool loop] Step 1: running rag...", + // A non-empty answer is the terminal case in Python. + "[Tool loop] The rag tool produced the final answer, done.", + } { + if !strings.Contains(joined, want) { + t.Errorf("missing %q; got:\n%s", want, joined) + } + } + // Every line must be tagged as thinking and ThinkLineBreak-terminated so + // the HTML think block does not glue the stages together. + if len(thinks) != 3 { + t.Fatalf("got %d deltas, want 3: %#v", len(thinks), got) + } + for i, isThink := range thinks { + if !isThink { + t.Errorf("delta %d (%q) not tagged as thinking", i, got[i]) + } + if !strings.HasSuffix(got[i], thinkLineBreak) { + t.Errorf("delta %d (%q) missing trailing %s", i, got[i], thinkLineBreak) + } + } +} + +// TestRetrieveViaHarnessToolLoopObservation covers the non-terminal case: an +// empty answer means the tool fed the next round, not the final reply. +func TestRetrieveViaHarnessToolLoopObservation(t *testing.T) { + stubHarness(t, "") + + var got []string + var thinks []bool + s := &ChatPipelineService{} + if _, _, err := s.retrieveViaHarness(context.Background(), "q", nil, nil, nil, "", "high", "t", "m", "sess", nil, collectSink(&got, &thinks)); err != nil { + t.Fatalf("retrieveViaHarness: %v", err) + } + joined := strings.Join(got, "") + if !strings.Contains(joined, "[Tool loop] The rag tool produced an observation for step 1.") { + t.Errorf("missing observation line; got:\n%s", joined) + } + if strings.Contains(joined, "final answer") { + t.Errorf("empty answer must not claim a final answer:\n%s", joined) + } +} + +// TestRetrieveViaHarnessNaiveSkipsToolLoop guards the naive path: no agentic +// loop runs, so no [Tool loop] narration must appear. +func TestRetrieveViaHarnessNaiveSkipsToolLoop(t *testing.T) { + stubHarness(t, "x") + + var got []string + var thinks []bool + s := &ChatPipelineService{} + if _, _, err := s.retrieveViaHarness(context.Background(), "q", nil, nil, nil, "", "naive", "t", "m", "sess", nil, collectSink(&got, &thinks)); err != nil { + t.Fatalf("retrieveViaHarness: %v", err) + } + if len(got) != 0 { + t.Errorf("naive mode emitted %d deltas, want 0: %#v", len(got), got) + } +} + +// TestToolLoopLineNilSink guards the nil-sink path (streaming disabled). +func TestToolLoopLineNilSink(t *testing.T) { + toolLoopLine(nil, "[Tool loop] Step 1: running rag...") // must not panic +} diff --git a/internal/service/chat_session.go b/internal/service/chat_session.go index 2e84f853041..bf2af18baf8 100644 --- a/internal/service/chat_session.go +++ b/internal/service/chat_session.go @@ -1647,6 +1647,10 @@ func (s *ChatSessionService) ChatCompletions( fullAnswer.WriteString("") } else if result.Answer != "" { fullAnswer.WriteString(result.Answer) + } else if result.Reasoning != "" { + // In-think reasoning text between the markers (tool and + // harness paths) — keep it inside the block. + fullAnswer.WriteString(result.Reasoning) } if session != nil { s.appendAssistantToSession(session, fullAnswer.String(), messageID) @@ -1694,6 +1698,15 @@ func (s *ChatSessionService) ChatCompletions( } else if result.Answer != "" { fullAnswer.WriteString(result.Answer) deltaAnswer = result.Answer + } else if result.Reasoning != "" { + // In-think reasoning text arriving between the + // StartToThink / EndToThink markers (the tool path and the + // harness high/ultra path both deliver it via Reasoning so + // OpenAI-compat can map it to reasoning_content). Treat it + // as think-block content so the chat UI shows the + // reasoning instead of dropping it. + fullAnswer.WriteString(result.Reasoning) + deltaAnswer = result.Reasoning } if session != nil { s.appendAssistantToSession(session, fullAnswer.String(), messageID) diff --git a/internal/service/citation.go b/internal/service/citation.go index ea54adae7c2..d427070b74a 100644 --- a/internal/service/citation.go +++ b/internal/service/citation.go @@ -44,6 +44,11 @@ var badCitationPatterns = []*regexp.Regexp{ regexp.MustCompile(`\[\s*ID\s*[:: ]*\s*([0-9\x{0660}-\x{0669}\x{06F0}-\x{06F9}]+)\s*\]`), // [ID: 12] regexp.MustCompile(`【\s*ID\s*[:: ]*\s*([0-9\x{0660}-\x{0669}\x{06F0}-\x{06F9}]+)\s*】`), // 【ID: 12】 regexp.MustCompile(`(?i)\bref\s*([0-9\x{0660}-\x{0669}\x{06F0}-\x{06F9}]+)\b`), // ref12 + // (**ID:5**) / (*ID: 5*) — markdown-asterisk-wrapped parenthetical cites that + // models sometimes emit instead of [ID:5]. Mirrors Python agentic_rag.py:885 + // `re.sub(r"\(\**(ID:\d+)\**\)", r"[\1]", ...)`, which deep-research runs over + // its final answer before it reaches the UI. + regexp.MustCompile(`\(\s*\**\s*ID\s*[:: ]*\s*([0-9\x{0660}-\x{0669}\x{06F0}-\x{06F9}]+)\s*\**\s*\)`), // (**ID: 12**) } // InsertCitations decorates answer with [ID:n] citation markers. diff --git a/internal/service/citation_test.go b/internal/service/citation_test.go index fb27bbe78de..6d9e446a081 100644 --- a/internal/service/citation_test.go +++ b/internal/service/citation_test.go @@ -313,3 +313,23 @@ func TestMaxRow(t *testing.T) { t.Error("max of nil should be 0") } } + +// TestRepairBadCitationFormats covers the malformed-citation shapes +// RepairBadCitationFormats rewrites to "[ID:N]", including the +// markdown-asterisk-wrapped parenthetical form (**ID:5**) that mirrors Python +// agentic_rag.py:885's re.sub(r"\(\**(ID:\d+)\**\)", r"[\1]", ...). +func TestRepairBadCitationFormats(t *testing.T) { + cases := []struct{ in, want string }{ + {"(**ID:5**)", "[ID:5]"}, // Python deep-research asterisk form + {"(*ID: 5*)", "[ID:5]"}, // single star, spaced + {"(ID:12)", "[ID:12]"}, // plain parenthetical (existing pattern) + {"[ID: 12]", "[ID:12]"}, // already canonical-ish but spaced + {"Built in 1865 (**ID:1**).", "Built in 1865 [ID:1]."}, + {"plain text no cites", "plain text no cites"}, + } + for _, c := range cases { + if got := RepairBadCitationFormats(c.in); got != c.want { + t.Errorf("RepairBadCitationFormats(%q) = %q, want %q", c.in, got, c.want) + } + } +} diff --git a/internal/service/dataset_artifact_nav_test.go b/internal/service/dataset_artifact_nav_test.go index 02bcfed2b64..2b7e90229bd 100644 --- a/internal/service/dataset_artifact_nav_test.go +++ b/internal/service/dataset_artifact_nav_test.go @@ -21,7 +21,7 @@ func (f *fakeArtifactNav) RemoveDoc(_ context.Context, _, _, docID string) error f.removedDocs = append(f.removedDocs, docID) return nil } -func (f *fakeArtifactNav) Search(context.Context, string, string, string, []float32, int) ([]nav.NavHit, error) { +func (f *fakeArtifactNav) Search(context.Context, string, string, string, []float32, []string, int) ([]nav.NavHit, error) { return nil, nil } func (f *fakeArtifactNav) ListClusters(context.Context, string, string, int, int) ([]nav.NavNode, int64, error) { @@ -30,6 +30,9 @@ func (f *fakeArtifactNav) ListClusters(context.Context, string, string, int, int func (f *fakeArtifactNav) ListChildren(_ context.Context, _, _, name string, _, _ int) ([]nav.NavNode, int64, error) { return f.children[name], int64(len(f.children[name])), nil } +func (f *fakeArtifactNav) SummariesByDocIDs(context.Context, string, string, []string) map[string]string { + return nil +} // TestDeleteNav_RemovesOnlyDirectDocChildren documents the limited semantic of // the deprecated DeleteNav: it removes the nav_doc rows directly under root diff --git a/internal/service/graph/retrieval.go b/internal/service/graph/retrieval.go index 8e70b8d11e6..34a02e09535 100644 --- a/internal/service/graph/retrieval.go +++ b/internal/service/graph/retrieval.go @@ -199,7 +199,9 @@ func buildSearchExprs(ctx context.Context, embModel *modelModule.EmbeddingModel, return []interface{}{matchText} } embeddingConfig := &modelModule.EmbeddingConfig{Dimension: 0} - embeddings, err := embModel.ModelDriver.Embed(ctx, embModel.ModelName, modelModule.EmbedRequest{Texts: []string{matchText.MatchingText}}, embModel.APIConfig, embeddingConfig, nil) + // Query: true — matchText is the search query (Python get_vector → + // encode_queries), not a document. + embeddings, err := embModel.ModelDriver.Embed(ctx, embModel.ModelName, modelModule.EmbedRequest{Texts: []string{matchText.MatchingText}, Query: true}, embModel.APIConfig, embeddingConfig, nil) if err != nil || len(embeddings) == 0 { return []interface{}{matchText} } diff --git a/internal/service/graph/search.go b/internal/service/graph/search.go index 7aa028156a6..1d5bc0e6399 100644 --- a/internal/service/graph/search.go +++ b/internal/service/graph/search.go @@ -99,7 +99,9 @@ func buildDenseExpr(ctx context.Context, embModel *modelModule.EmbeddingModel, q return nil, nil } embCfg := &modelModule.EmbeddingConfig{Dimension: 0} - embeddings, err := embModel.ModelDriver.Embed(ctx, embModel.ModelName, modelModule.EmbedRequest{Texts: []string{question}}, embModel.APIConfig, embCfg, nil) + // Query: true — the KG search embeds the user's question (Python + // get_vector → encode_queries), not a document. + embeddings, err := embModel.ModelDriver.Embed(ctx, embModel.ModelName, modelModule.EmbedRequest{Texts: []string{question}, Query: true}, embModel.APIConfig, embCfg, nil) if err != nil { return nil, fmt.Errorf("KG entity embed failed: %w", err) } diff --git a/internal/service/memory.go b/internal/service/memory.go index d99d8e4f684..db9f9d29d55 100644 --- a/internal/service/memory.go +++ b/internal/service/memory.go @@ -1407,7 +1407,9 @@ func (s *MemoryService) memoryMessageDenseExpr(ctx context.Context, question str return nil, err } embeddingModel := models.NewEmbeddingModel(driver, &modelName, apiConfig, maxTokens) - embeddings, err := embeddingModel.ModelDriver.Embed(ctx, embeddingModel.ModelName, models.EmbedRequest{Texts: []string{question}}, embeddingModel.APIConfig, &models.EmbeddingConfig{Dimension: 0}, nil) + // Query: true — the memory store is searched by question (Python + // memory/services/query.py uses emb_mdl.encode_queries). + embeddings, err := embeddingModel.ModelDriver.Embed(ctx, embeddingModel.ModelName, models.EmbedRequest{Texts: []string{question}, Query: true}, embeddingModel.APIConfig, &models.EmbeddingConfig{Dimension: 0}, nil) if err != nil { return nil, err } diff --git a/internal/service/model_service.go b/internal/service/model_service.go index ae47ca8a6a5..6eb3c4b31e6 100644 --- a/internal/service/model_service.go +++ b/internal/service/model_service.go @@ -3662,6 +3662,88 @@ func (m *ModelProviderService) ResolveModelContextLength(ctx context.Context, te return dao.ResolveModelContentLength(ctx, dao.DB, tenantID, modelRef, "", ""), nil } +// ResolveModelToolSupport reports whether the resolved chat model supports +// function calling (tool calls). It mirrors Python dialog_service.rag_agent's +// `if not getattr(chat_mdl, "is_tools", False)` gate: a model without tool +// support must skip the outer rag_agent react loop and fall back to the direct +// graph (Python falls back to async_chat). +// +// Precedence mirrors Python's tenant_model_service.get_model_config_by_id +// (:363) `"is_tools": model_extra.get("is_tools", is_tool)`: the flag persisted +// on the tenant model wins, and the provider catalog is only a default for +// models enrolled without one. Reading the catalog first instead would send a +// tenant-disabled model through the outer react loop — where a model that does +// not actually call tools answers from its own knowledge and the retrieval +// never runs. +func (m *ModelProviderService) ResolveModelToolSupport(ctx context.Context, tenantID string, modelType entity.ModelType, modelRef string) (bool, error) { + if strings.TrimSpace(modelRef) == "" { + return false, fmt.Errorf("model ref is required") + } + // Tenant-model UUID path: the persisted extra flag first, then the catalog. + if modelObj, err := m.modelDAO.GetByID(ctx, dao.DB, modelRef); err == nil { + if ts, ok := extraToolSupport(modelObj.Extra); ok { + return ts, nil + } + if prov, perr := m.modelProviderDAO.GetByID(ctx, dao.DB, modelObj.ProviderID); perr == nil && prov != nil { + return catalogToolSupport(prov.ProviderName, modelObj.ModelName), nil + } + return false, nil + } else if !errors.Is(err, gorm.ErrRecordNotFound) { + return false, err + } + // Composite "model@instance@provider" path: parse and consult the catalog. + pureModelName, _, providerName, err := parseModelName(modelRef) + if err != nil { + return false, err + } + return catalogToolSupport(providerName, pureModelName), nil +} + +// extraToolSupport reads the is_tools flag persisted on a tenant model's extra +// JSON. The value is written as a JSON boolean (addModelToInstance stores +// llm.Tools.Support verbatim) but has historically also been spelled as a +// string, so both shapes are accepted. ok is false when the key is absent or +// the extra blob is unreadable, letting the caller fall back to the catalog. +func extraToolSupport(extra string) (bool, bool) { + if strings.TrimSpace(extra) == "" { + return false, false + } + var fields map[string]interface{} + if err := json.Unmarshal([]byte(extra), &fields); err != nil { + return false, false + } + v, ok := fields["is_tools"] + if !ok { + return false, false + } + switch t := v.(type) { + case bool: + return t, true + case string: + return strings.EqualFold(strings.TrimSpace(t), "true"), true + case float64: + return t != 0, true + } + return false, false +} + +// catalogToolSupport reports whether a provider's catalog declares the named +// model as supporting tool (function) calling. Returns false when the provider +// or model is unknown. Mirrors RAGFlow's model_meta "is_tools" feature derived +// from conf/models/*.json. +func catalogToolSupport(providerName, modelName string) bool { + pm := dao.GetModelProviderManager() + provider := pm.FindProvider(providerName) + if provider == nil { + return false + } + mi := pm.FindModel(provider, modelName) + if mi == nil || mi.Tools == nil { + return false + } + return mi.Tools.Support +} + func (m *ModelProviderService) ResolveModelID(ctx context.Context, tenantID string, modelType entity.ModelType, modelName string) (string, error) { if modelObj, err := m.modelDAO.GetByID(ctx, dao.DB, modelName); err == nil { if modelObj.Status != "active" { diff --git a/internal/service/nav/chunk_agg_router.go b/internal/service/nav/chunk_agg_router.go new file mode 100644 index 00000000000..af84810335f --- /dev/null +++ b/internal/service/nav/chunk_agg_router.go @@ -0,0 +1,194 @@ +// +// 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. +// + +// The chunk_agg navigation-tree router, the Go mirror of Python +// dataset_api_service.py `_search_layers_nav_chunk_agg` under the default +// _NAV_TREE_ROUTER = "chunk_agg". Where the nav_doc router descends compiled +// nav rows, chunk_agg routes documents by aggregating raw-chunk retrieval hits: +// every document that surfaces a relevant chunk is scored with a PageIndex +// DocScore and returned with its nav_doc summary. +// +// It lives in the nav service package (not the agentic harness) because the +// Python source of this logic is dataset_api_service.py, not harness/. The +// harness tool layer only consumes it through the agentic NavTreeRouter +// interface and supplies the retriever/summariser via dependency injection. + +package nav + +import ( + "context" + "math" + "sort" + "strings" +) + +const ( + // chunkAggDocFocus is _NAV_DOC_FOCUS_LIMIT: how many documents chunk_agg returns. + chunkAggDocFocus = 3 + // chunkAggPool is _NAV_CHUNK_AGG_POOL: how many raw chunks to retrieve before + // rolling them up per document. + chunkAggPool = 256 + // chunkAggVecWeight is _NAV_CHUNK_AGG_VEC_WEIGHT: hybrid balance when no + // explicit dense weight is supplied. + chunkAggVecWeight = 0.3 +) + +// chunkAggregate is the per-document roll-up of chunk hits. +type chunkAggregate struct { + DocID string + Total float64 + Best float64 + Hits int +} + +// docScore mirrors _nav_doc_score: hit scores summed, damped by hit count. The +// sum rewards a document matching several chunks; the square-root denominator +// damps it so a long document cannot win on volume alone. +func docScore(total float64, hits int) float64 { + return total / math.Sqrt(float64(hits)+1) +} + +// aggregateChunks mirrors _nav_aggregate_chunks: roll chunk hits up per document. +// Only map chunks carrying a doc_id participate. +func aggregateChunks(chunks []map[string]any) map[string]*chunkAggregate { + agg := map[string]*chunkAggregate{} + for _, c := range chunks { + if c == nil { + continue + } + docID := "" + if id, ok := c["doc_id"].(string); ok { + docID = strings.TrimSpace(id) + } + if docID == "" { + continue + } + score := 0.0 + if s, ok := c["similarity"].(float64); ok { + score = s + } else if s, ok := c["score"].(float64); ok { + score = s + } + e, ok := agg[docID] + if !ok { + agg[docID] = &chunkAggregate{DocID: docID, Total: score, Best: score, Hits: 1} + continue + } + e.Total += score + e.Hits++ + if score > e.Best { + e.Best = score + } + } + return agg +} + +// rankedAggregates sorts per-doc aggregates by descending docScore (best chunk +// similarity as tie-break) and returns them ordered, mirroring the chunk_agg +// sort keyed on _nav_doc_score. +func rankedAggregates(agg map[string]*chunkAggregate) []*chunkAggregate { + out := make([]*chunkAggregate, 0, len(agg)) + for _, e := range agg { + out = append(out, e) + } + sort.SliceStable(out, func(i, j int) bool { + si := docScore(out[i].Total, out[i].Hits) + sj := docScore(out[j].Total, out[j].Hits) + if si != sj { + return si > sj + } + return out[i].Best > out[j].Best + }) + return out +} + +// ChunkRetriever retrieves raw chunks for chunk_agg. It is injected so the +// agentic harness stays free of the nlp/service layer; production wiring +// supplies a hybrid retriever that excludes compiled rows (compile_kwd) — see +// the navigation_tree retrieval contract. +type ChunkRetriever func(ctx context.Context, tenantID, kbID, query string, docScope []string, topN int, vecWeight float64) []map[string]any + +// DocSummarizer loads the nav_doc "description" (the document's overall summary) +// for a set of doc_ids, mirroring Python _nav_doc_summaries. Injected for the +// same reason as ChunkRetriever. +type DocSummarizer func(ctx context.Context, tenantID, kbID string, docIDs []string) map[string]string + +// ChunkAggRouter is a NavTreeRouter that routes documents by aggregating +// raw-chunk retrieval hits (Python default _NAV_TREE_ROUTER="chunk_agg"). It +// returns the top documents by PageIndex docScore, each labelled with its +// nav_doc summary. +type ChunkAggRouter struct { + Retrieve ChunkRetriever + Summarize DocSummarizer +} + +// Route implements the agentic NavTreeRouter contract. It returns (nil, nil) +// when no retriever is installed (treat as "no compiled tree", mirroring +// NavServiceRouter's contract), and an empty non-nil slice when a structure +// exists but no chunk routed to a doc. +func (r *ChunkAggRouter) Route(ctx context.Context, tenantID, kbID, query string, docScope []string, topK int) ([][2]string, error) { + if r.Retrieve == nil { + return nil, nil + } + query = strings.TrimSpace(query) + if query == "" || kbID == "" { + return nil, nil + } + if topK <= 0 { + topK = chunkAggDocFocus + } + // Pull a wide pool, then roll up per document (a focused doc may surface on + // many chunks, so a small pool starves the aggregation). + chunks := r.Retrieve(ctx, tenantID, kbID, query, docScope, chunkAggPool, chunkAggVecWeight) + agg := aggregateChunks(chunks) + if len(agg) == 0 { + return make([][2]string, 0), nil // structure exists, nothing routed + } + ranked := rankedAggregates(agg) + if len(ranked) > topK { + ranked = ranked[:topK] + } + ids := make([]string, 0, len(ranked)) + for _, e := range ranked { + ids = append(ids, e.DocID) + } + summaries := map[string]string{} + if r.Summarize != nil { + summaries = r.Summarize(ctx, tenantID, kbID, ids) + } + routed := make([][2]string, 0, len(ranked)) + for _, e := range ranked { + routed = append(routed, [2]string{e.DocID, strings.TrimSpace(summaries[e.DocID])}) + } + return routed, nil +} + +// NewChunkAggRouter returns a ChunkAggRouter wired to retrieve and summarise. +func NewChunkAggRouter(retrieve ChunkRetriever, summarize DocSummarizer) *ChunkAggRouter { + return &ChunkAggRouter{Retrieve: retrieve, Summarize: summarize} +} + +// ChunkAggSummarize adapts the nav service into the chunk_agg summarize leg, +// reading each routed document's nav_doc summary (Python _nav_doc_summaries). +func ChunkAggSummarize() DocSummarizer { + return func(ctx context.Context, tenantID, kbID string, docIDs []string) map[string]string { + ns := GetNavService() + if ns == nil { + return map[string]string{} + } + return ns.SummariesByDocIDs(ctx, tenantID, kbID, docIDs) + } +} diff --git a/internal/service/nav/chunk_agg_router_test.go b/internal/service/nav/chunk_agg_router_test.go new file mode 100644 index 00000000000..e8a57390fa7 --- /dev/null +++ b/internal/service/nav/chunk_agg_router_test.go @@ -0,0 +1,127 @@ +// +// 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. +// + +package nav + +import ( + "context" + "math" + "testing" +) + +func TestDocScore(t *testing.T) { + // sum=2, hits=1 -> 2/sqrt(2) ≈ 1.414 + got := docScore(2, 1) + want := 2 / math.Sqrt(2) + if math.Abs(got-want) > 1e-9 { + t.Errorf("docScore(2,1) = %v, want %v", got, want) + } + // More hits at the same total score less because of the sqrt damping. + if docScore(2, 4) >= docScore(2, 1) { + t.Errorf("more hits should damp the docScore") + } +} + +func TestAggregateChunks(t *testing.T) { + chunks := []map[string]any{ + {"doc_id": "d1", "similarity": 0.9}, + {"doc_id": "d1", "similarity": 0.3}, + {"doc_id": "d2", "score": 0.5}, + {"doc_id": " ", "similarity": 0.8}, // empty doc_id ignored + {"similarity": 0.7}, // no doc_id ignored + } + agg := aggregateChunks(chunks) + if len(agg) != 2 { + t.Fatalf("aggregated %d docs, want 2", len(agg)) + } + d1 := agg["d1"] + if d1.Total != 1.2 || d1.Best != 0.9 || d1.Hits != 2 { + t.Errorf("d1 = %+v, want total 1.2 best 0.9 hits 2", d1) + } + d2 := agg["d2"] + if d2.Total != 0.5 || d2.Best != 0.5 || d2.Hits != 1 { + t.Errorf("d2 = %+v, want total 0.5 best 0.5 hits 1", d2) + } +} + +func TestChunkAggRouterRoute(t *testing.T) { + ctx := context.Background() + rtr := &ChunkAggRouter{ + Retrieve: func(_ context.Context, _, _ string, _ string, _ []string, topN int, vecWeight float64) []map[string]any { + if vecWeight != chunkAggVecWeight { + t.Errorf("vecWeight = %v, want %v", vecWeight, chunkAggVecWeight) + } + if topN != chunkAggPool { + t.Errorf("topN = %d, want pool %d", topN, chunkAggPool) + } + return []map[string]any{ + {"doc_id": "d1", "similarity": 0.9}, + {"doc_id": "d1", "similarity": 0.7}, + {"doc_id": "d2", "similarity": 0.4}, + } + }, + Summarize: func(_ context.Context, _, _ string, ids []string) map[string]string { + out := map[string]string{} + for _, id := range ids { + out[id] = "summary of " + id + } + return out + }, + } + routed, err := rtr.Route(ctx, "t", "kb", "question", nil, 0) + if err != nil { + t.Fatalf("Route: %v", err) + } + // d1 outranks d2 (total 1.6 hits 2 -> 1.6/sqrt3 vs d2 0.4/sqrt2), focus cap 3. + if len(routed) != 2 { + t.Fatalf("routed %d docs, want 2", len(routed)) + } + if routed[0][0] != "d1" || routed[1][0] != "d2" { + t.Errorf("order = %v, want [d1 d2]", routed) + } + if routed[0][1] != "summary of d1" { + t.Errorf("summary[0] = %q, want summary of d1", routed[0][1]) + } +} + +func TestChunkAggRouterEmpty(t *testing.T) { + ctx := context.Background() + // Nil retriever -> (nil, nil): treated as no compiled tree. + rtr := &ChunkAggRouter{} + routed, err := rtr.Route(ctx, "t", "kb", "q", nil, 0) + if err != nil || routed != nil { + t.Errorf("nil retriever: routed=%v err=%v, want (nil, nil)", routed, err) + } +} + +func TestChunkAggRouterNoRoute(t *testing.T) { + ctx := context.Background() + rtr := &ChunkAggRouter{ + Retrieve: func(_ context.Context, _, _ string, _ string, _ []string, _ int, _ float64) []map[string]any { + return nil + }, + } + routed, err := rtr.Route(ctx, "t", "kb", "q", nil, 5) + if err != nil { + t.Fatalf("Route: %v", err) + } + if routed == nil { + t.Fatal("expected empty non-nil slice when nothing routes (structure exists)") + } + if len(routed) != 0 { + t.Errorf("routed len = %d, want 0", len(routed)) + } +} diff --git a/internal/service/nav/nav.go b/internal/service/nav/nav.go index 243ea0ea0ac..f65b3ca81d0 100644 --- a/internal/service/nav/nav.go +++ b/internal/service/nav/nav.go @@ -39,6 +39,12 @@ type NavNode struct { HasChildren bool `json:"has_children"` } +// Nav row types as stored in the compiled nav index (type_kwd). +const ( + TypeNavDoc = "nav_doc" + TypeNavCluster = "nav_cluster" +) + // NavHit is one KNN hit on a nav row. type NavHit struct { Type string // "nav_doc" | "nav_cluster" @@ -84,11 +90,23 @@ type NavService interface { RemoveDoc(ctx context.Context, tenantID, kbID, docID string) error // Search runs query KNN over nav rows and returns the routed doc ids. - Search(ctx context.Context, tenantID, kbID, query string, embd []float32, topK int) ([]NavHit, error) + // + // docScope restricts the result to the given documents (nil/empty = the whole + // dataset), mirroring search_dataset_nav's doc_scope: a nav_doc leaf matches + // on its doc_id, a nav_cluster row on coverage (doc_ids_kwd), and a cluster's + // returned coverage is trimmed to the scope so no out-of-scope document + // surfaces under a cluster that merely overlaps it. + Search(ctx context.Context, tenantID, kbID, query string, embd []float32, docScope []string, topK int) ([]NavHit, error) // ListClusters returns the depth-0 clusters (parent_kwd=root). ListClusters(ctx context.Context, tenantID, kbID string, page, pageSize int) ([]NavNode, int64, error) // ListChildren returns the direct children of a cluster (parent_kwd=name). ListChildren(ctx context.Context, tenantID, kbID, name string, page, pageSize int) ([]NavNode, int64, error) + // SummariesByDocIDs returns the nav_doc summary (preferred readable name, else + // the payload description) keyed by doc_id for the given documents. It mirrors + // Python dataset_api_service._nav_doc_summaries and backs the chunk_agg + // navigation-tree router's document labels. A doc without a nav_doc row is + // absent from the result. + SummariesByDocIDs(ctx context.Context, tenantID, kbID string, docIDs []string) map[string]string } var ( diff --git a/internal/service/nav/nav_service_router.go b/internal/service/nav/nav_service_router.go new file mode 100644 index 00000000000..e39e8c94f5f --- /dev/null +++ b/internal/service/nav/nav_service_router.go @@ -0,0 +1,99 @@ +// +// 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. +// + +// The production nav-tree router, the Go mirror of Python +// search_dataset_layers(kb.id, tenant_id, query, "navigation_tree", top_k, +// doc_scope) (navigation.py:705). The capability is nav.NavService.Search — KNN +// over the dataset's compiled nav rows, the same thing the "navigation_tree" +// mode exposes. +// +// It lives in the nav service package (not the agentic harness) because the +// Python source of this logic is dataset_api_service.py, not harness/. The +// harness tool layer only consumes it through the agentic NavTreeRouter +// interface. +package nav + +import ( + "context" + "log" + "strings" +) + +// navServiceMaxDocs is the router-local fallback doc count when the caller +// passes topK <= 0. The harness NavigateTree passes its own navSearchMaxDocs, +// so this only triggers if a router is invoked without an explicit budget. +const navServiceMaxDocs = 12 + +// NavServiceRouter routes through the production navigation-tree service. +type NavServiceRouter struct{} + +// Route implements the agentic NavTreeRouter contract (defined in the harness +// package, structural). +// +// Returns (nil, nil) when no NavService is installed — treated as "no compiled +// tree" (dataset-level), which is what an unconfigured deployment is. +// +// Two contract notes that drive the error handling below: +// +// 1. "no compiled tree" and "routed to nothing" are DIFFERENT signals. The +// former is dataset-level (the caller may disable the tool for the session); +// the latter is query-level (structure exists, this query just missed). The +// Python side distinguishes them via empty_reason, and conflating them is +// how a single unrouted query used to disable the tool for a whole session. +// 2. NavHit carries Name but not the leaf's Description, so the routed summary +// is Name when a richer field is unavailable. Routing still labels the +// route for free — no document load. +func (NavServiceRouter) Route(ctx context.Context, tenantID, kbID, query string, docScope []string, topK int) ([][2]string, error) { + svc := GetNavService() + if svc == nil { + return nil, nil // no compiled tree available + } + if strings.TrimSpace(query) == "" || kbID == "" { + return nil, nil + } + if topK <= 0 { + topK = navServiceMaxDocs + } + + hits, err := svc.Search(ctx, tenantID, kbID, query, nil, docScope, topK) + if err != nil { + // A backend failure is NOT "no structure": log and let the caller fall + // back rather than disabling the tool for the session. + log.Printf("[Dataset navigation search] NavService.Search failed for kb=%s: %v", kbID, err) + return nil, err + } + // Empty non-nil slice = structure exists, this query routed to nothing. + // (nil would mean "no tree", see above.) + routed := make([][2]string, 0, len(hits)) + for _, h := range hits { + // Only document leaves route: the strategy mirrored here pins + // type_kwd="nav_doc" (dataset_api_service.py:4107-4119), so a nav_cluster + // row must not become a routed "document" — a cluster's doc_id is the + // kb_id, not a document. + if h.Type == TypeNavCluster { + continue + } + did := strings.TrimSpace(h.DocID) + if did == "" { + continue + } + routed = append(routed, [2]string{did, strings.TrimSpace(h.Name)}) + } + return routed, nil +} + +// NewNavServiceRouter returns the production router. +func NewNavServiceRouter() *NavServiceRouter { return &NavServiceRouter{} } diff --git a/internal/service/nav/nav_service_router_test.go b/internal/service/nav/nav_service_router_test.go new file mode 100644 index 00000000000..d0d9847f1e5 --- /dev/null +++ b/internal/service/nav/nav_service_router_test.go @@ -0,0 +1,95 @@ +// +// 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. +// + +package nav + +import ( + "context" + "testing" +) + +// scopeRecordingNav records the doc scope Search was called with and returns a +// controlled hit list, so a test can assert the router forwards the ceiling and +// routes only document leaves. +type scopeRecordingNav struct { + scope []string + hits []NavHit +} + +func (f *scopeRecordingNav) UpsertDoc(context.Context, UpsertDocInput) error { return nil } +func (f *scopeRecordingNav) RemoveDoc(context.Context, string, string, string) error { + return nil +} +func (f *scopeRecordingNav) Search(_ context.Context, _, _ string, _ string, _ []float32, docScope []string, _ int) ([]NavHit, error) { + f.scope = append([]string(nil), docScope...) + return f.hits, nil +} +func (f *scopeRecordingNav) ListClusters(context.Context, string, string, int, int) ([]NavNode, int64, error) { + return nil, 0, nil +} +func (f *scopeRecordingNav) ListChildren(context.Context, string, string, string, int, int) ([]NavNode, int64, error) { + return nil, 0, nil +} +func (f *scopeRecordingNav) SummariesByDocIDs(context.Context, string, string, []string) map[string]string { + return nil +} + +// TestNavServiceRouter_ForwardsDocScopeAndRoutesLeavesOnly pins the two halves of +// the nav-row routing contract: +// +// 1. The doc scope must reach the service (Python search_dataset_layers threads +// doc_scope into the "navigation_tree" mode, dataset_api_service.py:4107-4119, +// and _nav_search_titled ceilings it with the session scope on the way in). +// 2. Only document leaves route: that strategy pins type_kwd="nav_doc", so a +// nav_cluster hit — whose doc_id is the kb_id, not a document — must never be +// emitted as a routed document. +func TestNavServiceRouter_ForwardsDocScopeAndRoutesLeavesOnly(t *testing.T) { + fake := &scopeRecordingNav{hits: []NavHit{ + {Type: TypeNavCluster, DocID: "kb1", DocIDs: []string{"d1"}, Name: "cluster covering d1"}, + {Type: TypeNavDoc, DocID: "d1", Name: "rocket"}, + }} + prev := GetNavService() + SetNavService(fake) + defer SetNavService(prev) + + routed, err := NewNavServiceRouter().Route(t.Context(), "t1", "kb1", "rocket propulsion", []string{"d1"}, 5) + if err != nil { + t.Fatalf("Route: %v", err) + } + if len(fake.scope) != 1 || fake.scope[0] != "d1" { + t.Errorf("Search doc scope = %v, want [d1] (the router must not drop the ceiling)", fake.scope) + } + if len(routed) != 1 || routed[0][0] != "d1" || routed[0][1] != "rocket" { + t.Fatalf("routed = %v, want exactly [[d1 rocket]] (cluster rows must not route)", routed) + } +} + +// TestNavServiceRouter_NilServiceMeansNoTree keeps the "no compiled tree" signal +// distinct from "routed to nothing": a missing service returns nil, not an empty +// non-nil slice (which the caller reads as "structure exists, query missed"). +func TestNavServiceRouter_NilServiceMeansNoTree(t *testing.T) { + prev := GetNavService() + SetNavService(nil) + defer SetNavService(prev) + + routed, err := NewNavServiceRouter().Route(t.Context(), "t1", "kb1", "q", nil, 5) + if err != nil { + t.Fatalf("Route: %v", err) + } + if routed != nil { + t.Fatalf("routed = %v, want nil (no compiled tree)", routed) + } +} diff --git a/internal/service/nav_embedder.go b/internal/service/nav_embedder.go index f8982d4b7eb..f0877a0f323 100644 --- a/internal/service/nav_embedder.go +++ b/internal/service/nav_embedder.go @@ -41,8 +41,21 @@ func NewNavEmbedder(modelSvc *ModelProviderService, embdModelName string) *NavEm return &NavEmbedder{modelSvc: modelSvc, embdModelName: embdModelName} } -// Encode embeds texts for the tenant and returns float32 vectors. +// Encode embeds texts as DOCUMENTS for the tenant and returns float32 vectors. func (e *NavEmbedder) Encode(ctx context.Context, tenantID string, texts []string) ([][]float32, error) { + return e.encode(ctx, tenantID, texts, false) +} + +// EncodeQueries is the query-side counterpart of Encode (Python +// LLMBundle.encode_queries). Providers that embed queries and documents +// asymmetrically — Cohere search_query, Voyage query, Jina retrieval.query, +// NVIDIA query — only apply their query encoding when this method is used, so +// every caller embedding a SEARCH QUERY must prefer it over Encode. +func (e *NavEmbedder) EncodeQueries(ctx context.Context, tenantID string, texts []string) ([][]float32, error) { + return e.encode(ctx, tenantID, texts, true) +} + +func (e *NavEmbedder) encode(ctx context.Context, tenantID string, texts []string, query bool) ([][]float32, error) { if e.modelSvc == nil { return nil, fmt.Errorf("datasetnav: embedding model service not initialized") } @@ -73,7 +86,7 @@ func (e *NavEmbedder) Encode(ctx context.Context, tenantID string, texts []strin if len(nonEmpty) == 0 { return nil, nil } - embeds, err := model.ModelDriver.Embed(ctx, model.ModelName, modelModule.EmbedRequest{Texts: nonEmpty}, model.APIConfig, nil, nil) + embeds, err := model.ModelDriver.Embed(ctx, model.ModelName, modelModule.EmbedRequest{Texts: nonEmpty, Query: query}, model.APIConfig, nil, nil) if err != nil { return nil, err } diff --git a/internal/service/nlp/datasetnav.go b/internal/service/nlp/datasetnav.go index 4959b1b4d2d..7daaf6d0d3b 100644 --- a/internal/service/nlp/datasetnav.go +++ b/internal/service/nlp/datasetnav.go @@ -53,6 +53,24 @@ type NavEmbedder interface { Encode(ctx context.Context, tenantID string, texts []string) ([][]float32, error) } +// NavQueryEmbedder is the optional query-side counterpart of NavEmbedder +// (Python LLMBundle.encode_queries). It is implemented by embedders whose model +// encodes queries and documents asymmetrically (Cohere / Voyage / Jina / +// NVIDIA); callers embedding a SEARCH QUERY must prefer it and fall back to +// Encode when it is absent. +type NavQueryEmbedder interface { + EncodeQueries(ctx context.Context, tenantID string, texts []string) ([][]float32, error) +} + +// encodeNavQuery embeds a search query, using the asymmetric query encoding +// when the embedder provides one, mirroring Python's encode_queries split. +func encodeNavQuery(ctx context.Context, emb NavEmbedder, tenantID string, texts []string) ([][]float32, error) { + if q, ok := emb.(NavQueryEmbedder); ok { + return q.EncodeQueries(ctx, tenantID, texts) + } + return emb.Encode(ctx, tenantID, texts) +} + // NavService is the concrete, ES-backed implementation of nav.NavService. type NavService struct { embed NavEmbedder @@ -253,16 +271,17 @@ func isHexString(s string) bool { } // Search runs query KNN over nav rows and returns routed doc ids. -func (s *NavService) Search(ctx context.Context, tenantID, kbID, query string, embd []float32, topK int) ([]nav.NavHit, error) { +func (s *NavService) Search(ctx context.Context, tenantID, kbID, query string, embd []float32, docScope []string, topK int) ([]nav.NavHit, error) { if topK <= 0 { topK = 8 } + allowed := navScopeSet(docScope) vec := embd if len(vec) == 0 { if s.embed == nil { return nil, fmt.Errorf("datasetnav: no embedding available for Search") } - embeddings, err := s.embed.Encode(ctx, tenantID, []string{query}) + embeddings, err := encodeNavQuery(ctx, s.embed, tenantID, []string{query}) if err != nil { return nil, err } @@ -272,15 +291,25 @@ func (s *NavService) Search(ctx context.Context, tenantID, kbID, query string, e vec = embeddings[0] } f64 := f32ToF64Slice(vec) + // A scoped read enforces the scope in memory (this read is untyped — it mixes + // nav_doc leaves and nav_cluster rows, so no single query-time key expresses + // both; Python only pushes the scope into the query when type_kwd pins one + // type, dataset_nav.py:1371-1383), so the engine budget must not let + // out-of-scope rows crowd the scope out before the filter runs + // (dataset_nav.py:1384-1387). + scanTop := topK + if len(allowed) > 0 { + scanTop = navScopedScanTopN + } chunks, _, err := s.navSearch(ctx, tenantID, kbID, navFilter(nil), - []string{"type_kwd", "title_kwd", "doc_id", "doc_ids_kwd", "_score"}, 0, topK, + []string{"type_kwd", "title_kwd", "doc_id", "doc_ids_kwd", "_score"}, 0, scanTop, []interface{}{&types.MatchDenseExpr{ VectorColumnName: fmt.Sprintf("q_%d_vec", len(f64)), EmbeddingData: f64, EmbeddingDataType: "float", DistanceType: "cosine", - TopN: topK, + TopN: scanTop, ExtraOptions: map[string]interface{}{"similarity": 0.0}, }}) if err != nil { @@ -289,27 +318,142 @@ func (s *NavService) Search(ctx context.Context, tenantID, kbID, query string, e hits := make([]nav.NavHit, 0, len(chunks)) for _, c := range chunks { h := nav.NavHit{ - Type: firstStringValue(c["type_kwd"]), - Name: firstStringValue(c["title_kwd"]), - DocID: firstStringValue(c["doc_id"]), + Type: firstStringValue(c["type_kwd"]), + Name: firstStringValue(c["title_kwd"]), + DocID: firstStringValue(c["doc_id"]), + DocIDs: firstStringSlice(c["doc_ids_kwd"]), } if sc, ok := c["_score"].(float64); ok { h.Score = sc } else if sc, ok := c["_score"].(float32); ok { h.Score = float64(sc) } - if ds, ok := c["doc_ids_kwd"].([]interface{}); ok { - for _, d := range ds { - if dd, ok := d.(string); ok { - h.DocIDs = append(h.DocIDs, dd) - } - } + if !navHitInScope(h, allowed) { + continue + } + if len(allowed) > 0 && len(h.DocIDs) > 0 { + // A scoped search must only surface in-scope documents: cut a + // cluster's coverage list down to the scoped set so no out-of-scope + // doc appears under a cluster that merely overlaps the scope + // (dataset_nav.py:1460-1465). + h.DocIDs = navIntersectScope(h.DocIDs, allowed) } hits = append(hits, h) + if len(hits) >= topK { + break + } } return hits, nil } +// navScopedScanTopN is the engine budget for a doc-scoped nav read. It exists so +// the in-memory scope filter runs over a pool wide enough to fill topK with +// in-scope rows even when out-of-scope rows rank higher. +const navScopedScanTopN = 1000 + +// navScopeSet normalizes a caller's doc scope the way search_dataset_nav does +// (dataset_nav.py:1364): trimmed, non-empty, deduped. A nil result means "no +// restriction". +func navScopeSet(docScope []string) map[string]struct{} { + if len(docScope) == 0 { + return nil + } + out := make(map[string]struct{}, len(docScope)) + for _, d := range docScope { + if d = strings.TrimSpace(d); d != "" { + out[d] = struct{}{} + } + } + if len(out) == 0 { + return nil + } + return out +} + +// navHitInScope mirrors Python _in_nav_scope (dataset_nav.py:611): a nav_cluster +// row belongs when it covers at least one scoped document (a non-empty coverage +// list is the reliable discriminator — a cluster's doc_id is the kb_id, not a +// document), a nav_doc leaf when its doc_id is in scope. +func navHitInScope(h nav.NavHit, allowed map[string]struct{}) bool { + if len(allowed) == 0 { + return true + } + if len(h.DocIDs) > 0 { + for _, d := range h.DocIDs { + if _, ok := allowed[strings.TrimSpace(d)]; ok { + return true + } + } + return false + } + _, ok := allowed[strings.TrimSpace(h.DocID)] + return ok +} + +// navIntersectScope keeps only the doc ids that are inside the scope, preserving +// order. +func navIntersectScope(docIDs []string, allowed map[string]struct{}) []string { + out := make([]string, 0, len(docIDs)) + for _, d := range docIDs { + if _, ok := allowed[strings.TrimSpace(d)]; ok { + out = append(out, d) + } + } + return out +} + +// SummariesByDocIDs returns the nav_doc summary keyed by doc_id for the given +// documents. It mirrors Python dataset_api_service._nav_doc_summaries: it reads +// the nav_doc rows (compile_kwd=dataset_nav, type_kwd=nav_doc) for the doc_ids +// and yields, per doc, the readable nav name when present, else the payload +// description. Documents with no nav_doc row are absent from the result. +func (s *NavService) SummariesByDocIDs(ctx context.Context, tenantID, kbID string, docIDs []string) map[string]string { + if len(docIDs) == 0 { + return map[string]string{} + } + chunks, _, err := s.navSearch(ctx, tenantID, kbID, + navFilter(map[string]interface{}{ + "type_kwd": []string{"nav_doc"}, + "doc_id": docIDs, + }), + []string{"type_kwd", "name", "title_kwd", "content_with_weight", "doc_id"}, + 0, len(docIDs), nil) + if err != nil { + return map[string]string{} + } + out := make(map[string]string, len(chunks)) + for _, c := range chunks { + docID := firstStringValue(c["doc_id"]) + if docID == "" { + continue + } + // Prefer an explicit readable name, else the payload description, matching + // nodeFromRow's label rules (a raw 32-hex id is not a human label). + name := firstStringValue(c["name"]) + if name == "" { + name = firstStringValue(c["title_kwd"]) + } + if graphIsRawID(name) { + name = "" + } + summary := name + if summary == "" { + if payload, ok := c["content_with_weight"].(string); ok { + var m map[string]interface{} + if json.Unmarshal([]byte(payload), &m) == nil { + if d, ok := m["description"].(string); ok { + summary = strings.TrimSpace(d) + } + } + } + } + if summary != "" { + out[docID] = summary + } + } + return out +} + // UpsertDoc places one document summary into the nav tree. Minimal closed loop: // deterministic placement (KNN find best cluster -> merge if sim>=0.80, else a // new root-level cluster). No LLM, no split/rebalance, no cascade cleanup. diff --git a/internal/service/nlp/datasetnav_test.go b/internal/service/nlp/datasetnav_test.go index 67e4366d668..05f350b27c1 100644 --- a/internal/service/nlp/datasetnav_test.go +++ b/internal/service/nlp/datasetnav_test.go @@ -415,7 +415,7 @@ func TestNavService_Search_ReturnsHit(t *testing.T) { if err := ns.UpsertDoc(t.Context(), navUpsertInput("t1", "kb1", "d1", "aaa")); err != nil { t.Fatal(err) } - hits, err := ns.Search(t.Context(), "t1", "kb1", "aaa", nil, 5) + hits, err := ns.Search(t.Context(), "t1", "kb1", "aaa", nil, nil, 5) if err != nil { t.Fatal(err) } @@ -427,6 +427,99 @@ func TestNavService_Search_ReturnsHit(t *testing.T) { } } +// TestNavService_Search_DocScope pins search_dataset_nav's doc_scope semantics +// (dataset_nav.py:1364-1387, 1444-1465) on the nav-row read: a nav_doc leaf +// matches on doc_id, a nav_cluster row on coverage, a cluster's coverage is +// trimmed to the scope, and the scope is applied BEFORE the top_k truncation — +// a scoped read must not come back empty (or short) because out-of-scope rows +// ranked higher. +func TestNavService_Search_DocScope(t *testing.T) { + eng := newMemNavEngine() + ns := newTestNav(eng) + + const dim = 1024 + vec := func(w float64) []float64 { + v := make([]float64, dim) + v[0] = w + return v + } + row := func(typ, docID, title string, docIDs []string, w float64) map[string]interface{} { + r := map[string]interface{}{ + "compile_kwd": navCompileKwd, + "type_kwd": typ, + "doc_id": docID, + "title_kwd": title, + "q_1024_vec": vec(w), + } + if len(docIDs) > 0 { + r["doc_ids_kwd"] = docIDs + } + return r + } + // Three out-of-scope leaves outrank the single in-scope leaf (cosine 1.0 vs + // 0.5), so a scoped read truncated to one row only fills its cap if the + // scope is applied over a wide-enough pool. + rows := []map[string]interface{}{ + row(nav.TypeNavDoc, "dx1", "out 1", nil, 1), + row(nav.TypeNavDoc, "dx2", "out 2", nil, 1), + row(nav.TypeNavDoc, "dx3", "out 3", nil, 1), + row(nav.TypeNavDoc, "d1", "in scope", nil, 0.5), + row(nav.TypeNavCluster, "kb1", "covering d1+d2", []string{"d1", "d2"}, 0.4), + row(nav.TypeNavCluster, "kb1", "covering d2 only", []string{"d2"}, 1), + } + if _, err := eng.InsertChunks(t.Context(), rows, "", "kb1"); err != nil { + t.Fatal(err) + } + q := make([]float32, dim) + q[0] = 1 + + all, err := ns.Search(t.Context(), "t1", "kb1", "q", q, nil, 10) + if err != nil { + t.Fatal(err) + } + if len(all) != len(rows) { + t.Fatalf("unscoped hits = %d, want %d (nil scope must not restrict)", len(all), len(rows)) + } + + scoped, err := ns.Search(t.Context(), "t1", "kb1", "q", q, []string{" d1 "}, 10) + if err != nil { + t.Fatal(err) + } + var gotLeaf, gotCluster bool + for _, h := range scoped { + switch h.DocID { + case "d1": + gotLeaf = true + case "kb1": + gotCluster = true + if len(h.DocIDs) != 1 || h.DocIDs[0] != "d1" { + t.Errorf("cluster coverage = %v, want [d1] (trimmed to the scope)", h.DocIDs) + } + default: + t.Errorf("out-of-scope hit %q surfaced in a scoped read", h.DocID) + } + } + if !gotLeaf || !gotCluster { + t.Fatalf("scoped hits = %+v, want d1 plus the cluster covering it", scoped) + } + for _, h := range scoped { + if h.Name == "covering d2 only" { + t.Error("a cluster whose coverage does not intersect the scope must not surface") + } + } + + // The scope is applied to the pool, not after the engine truncation: the + // top-ranked rows here are all out of scope, yet the in-scope leaf still + // comes back as the single hit. + one, err := ns.Search(t.Context(), "t1", "kb1", "q", q, []string{"d1"}, 1) + if err != nil { + t.Fatal(err) + } + if len(one) != 1 || one[0].DocID != "d1" { + t.Fatalf("top_k=1 scoped hits = %+v, want exactly the in-scope leaf d1", one) + } +} + // TestNavService_Acceptance4_ListChildren asserts acceptance #4: ListChildren // returns only the rows whose parent_kwd=name. Two docs with identical stub // vectors merge into one root cluster: the first becomes the cluster itself, diff --git a/internal/service/nlp/retrieval.go b/internal/service/nlp/retrieval.go index 8b060cba420..62c70f529f1 100644 --- a/internal/service/nlp/retrieval.go +++ b/internal/service/nlp/retrieval.go @@ -783,7 +783,12 @@ func (s *RetrievalService) GetVector(ctx context.Context, txt string, embModel * embeddingConfig := &models.EmbeddingConfig{ Dimension: 0, } - embeddings, err := embModel.ModelDriver.Embed(ctx, embModel.ModelName, models.EmbedRequest{Texts: []string{txt}}, embModel.APIConfig, embeddingConfig, nil) + // Query: true mirrors Python Dealer.get_vector (rag/nlp/search.py:75-82), + // which embeds the search text with emb_mdl.encode_queries — the asymmetric + // query encoding (Cohere search_query / Voyage query / Jina retrieval.query + // / NVIDIA query). Embedding it as a document would put the query vector in + // the wrong space for those providers. + embeddings, err := embModel.ModelDriver.Embed(ctx, embModel.ModelName, models.EmbedRequest{Texts: []string{txt}, Query: true}, embModel.APIConfig, embeddingConfig, nil) if err != nil { return nil, err } diff --git a/internal/service/skill_search.go b/internal/service/skill_search.go index c874565bc3b..2793a277f54 100644 --- a/internal/service/skill_search.go +++ b/internal/service/skill_search.go @@ -680,7 +680,9 @@ func (s *SkillSearchService) getEmbedding(ctx context.Context, text, embdID, ten truncatedText := truncate(text, maxLen-10) var response []models.EmbeddingData - response, err = embeddingModel.ModelDriver.Embed(ctx, embeddingModel.ModelName, models.EmbedRequest{Texts: []string{truncatedText}}, embeddingModel.APIConfig, nil, nil) + // Query: true — getEmbedding is used only by the skill search legs + // (vectorSearch / hybridSearch) to embed the user's query. + response, err = embeddingModel.ModelDriver.Embed(ctx, embeddingModel.ModelName, models.EmbedRequest{Texts: []string{truncatedText}, Query: true}, embeddingModel.APIConfig, nil, nil) if err != nil { return nil, fmt.Errorf("failed to encode query: %w", err) } diff --git a/internal/service/web_search_provider_test.go b/internal/service/web_search_provider_test.go index 7e9c6812ca3..cbbf46e26f3 100644 --- a/internal/service/web_search_provider_test.go +++ b/internal/service/web_search_provider_test.go @@ -25,6 +25,23 @@ import ( "testing" ) +// TestHarnessWebSearchFuncGatedByProvider pins that the harness web_search seam +// is produced only when a provider is configured (mirroring Python's +// RAGTools.web_search provider gate). A nil callback is what keeps the tool off +// the agentic surface. +func TestHarnessWebSearchFuncGatedByProvider(t *testing.T) { + s := &ChatPipelineService{} + if fn := s.harnessWebSearchFunc(nil); fn != nil { + t.Error("nil prompt config must yield no web-search callback") + } + if fn := s.harnessWebSearchFunc(map[string]interface{}{}); fn != nil { + t.Error("empty prompt config must yield no web-search callback") + } + if fn := s.harnessWebSearchFunc(map[string]interface{}{"tavily_api_key": "tvly-test"}); fn == nil { + t.Error("configured provider must yield a web-search callback") + } +} + func TestResolveWebSearchProviderUsesExistingTavilyConfig(t *testing.T) { provider := resolveWebSearchProvider(map[string]interface{}{ "tavily_api_key": "tvly-test", From 607f9866646846093fd8da9b52b6309fd0c97237 Mon Sep 17 00:00:00 2001 From: Wang Qi Date: Thu, 10 Sep 2026 20:03:22 +0800 Subject: [PATCH 082/568] Revert "fix(ingestion): allow re-parsing a document whose parse was canceled at progress 0" (#19503) Reverts infiniflow/ragflow#19258 --- .../ingestion/service/ingestion_service.go | 73 +------- internal/service/ingestion_task_service.go | 164 +----------------- .../service/ingestion_task_service_test.go | 103 +---------- 3 files changed, 21 insertions(+), 319 deletions(-) diff --git a/internal/ingestion/service/ingestion_service.go b/internal/ingestion/service/ingestion_service.go index 921341f3225..f82719fe94a 100644 --- a/internal/ingestion/service/ingestion_service.go +++ b/internal/ingestion/service/ingestion_service.go @@ -695,31 +695,10 @@ func (e *Ingestor) executeTaskWithHeartbeat(ctx context.Context, taskCtx *taskpk }) } -// ownsTaskRun reports whether the calling run still owns the task: a newer -// run (created by a supersede/re-parse) bumps the run counter, so a mismatch -// means this run's terminal write must be skipped. A run whose counter could -// not be read (myRun <= 0) conservatively keeps ownership. Uses a detached -// context: it is called from failure/cancel paths whose context is typically -// already cancelled. -func (e *Ingestor) ownsTaskRun(taskID string, myRun int) bool { - if myRun <= 0 { - return true - } - ctx, cancel := context.WithTimeout(context.WithoutCancel(e.ctx), 2*time.Second) - defer cancel() - current, ok := e.ingestionTaskSvc.CurrentRunCount(ctx, taskID) - if !ok { - return true - } - return current == myRun -} - -// markStopped transitions the task to STOPPED (terminal). A RUNNING task -// first goes through RequestStop (RUNNING → STOPPING); a STOPPING task is -// settled directly; any other status (terminal, or CREATED/SCHEDULED because -// a supersede re-armed the task for a newer run) is treated as settled with -// nothing to finalize. Finally it cleans up the Redis cancel flag so that a -// future retry of the same task does not immediately re-cancel. +// markStopped transitions the task to STOPPED (terminal). It first calls +// RequestStop to handle RUNNING → STOPPING, then MarkStopped for the final +// STOPPING → STOPPED transition. Finally it cleans up the Redis cancel flag +// so that a future retry of the same task does not immediately re-cancel. // The caller's context is detached before touching the DB: markStopped runs // on failure/cancel/shutdown paths whose context is typically already // cancelled, and a contaminated context would make the terminal write fail @@ -727,29 +706,10 @@ func (e *Ingestor) ownsTaskRun(taskID string, myRun int) bool { func (e *Ingestor) markStopped(ctx context.Context, taskID string) bool { ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer cancel() - // Only a RUNNING/STOPPING task still belongs to this run. A task in - // CREATED/SCHEDULED here was re-armed for a newer run by a supersede - // (re-parse of a canceled document); finalizing it would kill the - // replacement run before it starts, so treat it as already settled. - // Terminal statuses need no work either. - task, err := e.ingestionTaskSvc.GetTask(ctx, taskID) - if err != nil { - common.Error(fmt.Sprintf("markStopped: load task %s: %v", taskID, err), err) + if _, err := e.ingestionTaskSvc.RequestStop(ctx, taskID); err != nil { + common.Error(fmt.Sprintf("markStopped: RequestStop task %s: %v", taskID, err), err) return false } - switch task.Status { - case common.RUNNING: - if _, err := e.ingestionTaskSvc.RequestStop(ctx, taskID); err != nil { - common.Error(fmt.Sprintf("markStopped: RequestStop task %s: %v", taskID, err), err) - return false - } - case common.STOPPING: - default: - // COMPLETED/STOPPED/FAILED: already terminal. CREATED/SCHEDULED: - // re-armed by a newer run - nothing this run may finalize. - common.Info(fmt.Sprintf("markStopped: task %s is %s; nothing to finalize for this run", taskID, task.Status)) - return true - } if err := e.ingestionTaskSvc.MarkStopped(ctx, taskID); err != nil { common.Error(fmt.Sprintf("markStopped: MarkStopped task %s: %v", taskID, err), err) return false @@ -812,11 +772,6 @@ func (e *Ingestor) runTask(ctx context.Context, task *entity.IngestionTask) bool } return ok } - // Capture this run's counter: if a re-parse supersedes this run (the task - // is force-finalized and re-armed while this worker is still inside a - // non-cancellable section), a newer run bumps the counter and this run - // must not overwrite the newer run's terminal state or document progress. - myRun, _ := e.ingestionTaskSvc.CurrentRunCount(dbCtx, task.ID) checkpointExists := e.checkpointExists if checkpointExists == nil { checkpointExists = canvas.RedisCheckpointExists @@ -864,10 +819,6 @@ func (e *Ingestor) runTask(ctx context.Context, task *entity.IngestionTask) bool return false } common.Info(fmt.Sprintf("Task %s cancelled during pipeline", task.ID)) - if !e.ownsTaskRun(task.ID, myRun) { - common.Info(fmt.Sprintf("Task %s run %d superseded by a newer run; skip cancel finalize", task.ID, myRun)) - return true - } e.markCancelProgress(task) stopped := e.markStopped(ctx, task.ID) if stopped { @@ -877,10 +828,6 @@ func (e *Ingestor) runTask(ctx context.Context, task *entity.IngestionTask) bool } if errors.Is(err, context.DeadlineExceeded) { common.Info(fmt.Sprintf("Task %s timed out during pipeline", task.ID)) - if !e.ownsTaskRun(task.ID, myRun) { - common.Info(fmt.Sprintf("Task %s run %d superseded by a newer run; skip timeout finalize", task.ID, myRun)) - return true - } e.markTimeoutProgress(task) ok := e.markFailed(ctx, task.ID) if ok { @@ -889,10 +836,6 @@ func (e *Ingestor) runTask(ctx context.Context, task *entity.IngestionTask) bool return ok } common.Error(fmt.Sprintf("Task %s failed", task.ID), err) - if !e.ownsTaskRun(task.ID, myRun) { - common.Info(fmt.Sprintf("Task %s run %d superseded by a newer run; skip failure finalize", task.ID, myRun)) - return true - } ok := e.markFailed(ctx, task.ID) if ok { e.recordTerminalPipelineLog(ctx, task, string(entity.TaskStatusFail)) @@ -900,10 +843,6 @@ func (e *Ingestor) runTask(ctx context.Context, task *entity.IngestionTask) bool return ok } - if !e.ownsTaskRun(task.ID, myRun) { - common.Info(fmt.Sprintf("Task %s run %d superseded by a newer run; skip completion", task.ID, myRun)) - return true - } if err := e.completeTask(ctx, task.ID); err != nil { common.Error(fmt.Sprintf("Task %s update status failed", task.ID), err) return false diff --git a/internal/service/ingestion_task_service.go b/internal/service/ingestion_task_service.go index 3bd3f6babfb..8395578ed08 100644 --- a/internal/service/ingestion_task_service.go +++ b/internal/service/ingestion_task_service.go @@ -46,20 +46,15 @@ type IngestionTaskService struct { ingestionTaskDAO *dao.IngestionTaskDAO ingestionTaskLogDAO *dao.IngestionTaskLogDAO taskPublisher TaskPublisher - // supersedeTerminalWait bounds how long supersedeAndRetryTask waits for a - // live worker to finalize a requested stop before force-finalizing the - // task. Overridable so tests do not pay the full production wait. - supersedeTerminalWait time.Duration } func NewIngestionTaskService() *IngestionTaskService { return &IngestionTaskService{ - documentDAO: dao.NewDocumentDAO(), - userDAO: dao.NewUserDAO(), - ingestionTaskDAO: dao.NewIngestionTaskDAO(), - ingestionTaskLogDAO: dao.NewIngestionTaskLogDAO(), - taskPublisher: NewMessageQueueTaskPublisher(), - supersedeTerminalWait: defaultSupersedeTerminalWait, + documentDAO: dao.NewDocumentDAO(), + userDAO: dao.NewUserDAO(), + ingestionTaskDAO: dao.NewIngestionTaskDAO(), + ingestionTaskLogDAO: dao.NewIngestionTaskLogDAO(), + taskPublisher: NewMessageQueueTaskPublisher(), } } @@ -346,7 +341,7 @@ func validateTransition(from, to string) error { if to == common.STOPPED { return nil } - case common.FAILED, common.STOPPED, common.COMPLETED: + case common.FAILED, common.STOPPED: if to == common.CREATED { return nil } @@ -402,7 +397,7 @@ func (s *IngestionTaskService) CreateAndEnqueue(ctx context.Context, task *entit return nil, err } return s.markScheduledAfterPublish(ctx, existing.ID) - case common.FAILED, common.STOPPED, common.COMPLETED: + case common.FAILED, common.STOPPED: originalStatus := existing.Status existing, err = s.transition(ctx, existing.ID, common.CREATED) if err != nil { @@ -420,8 +415,6 @@ func (s *IngestionTaskService) CreateAndEnqueue(ctx context.Context, task *entit return nil, err } return s.markScheduledAfterPublish(ctx, existing.ID) - case common.SCHEDULED, common.RUNNING, common.STOPPING: - return s.supersedeAndRetryTask(ctx, existing) default: return nil, fmt.Errorf("document id %s already exists, status: %s, task id: %s", task.DocumentID, existing.Status, existing.ID) } @@ -440,141 +433,6 @@ func (s *IngestionTaskService) CreateAndEnqueue(ctx context.Context, task *entit return s.markScheduledAfterPublish(ctx, created.ID) } -// defaultSupersedeTerminalWait bounds how long a re-parse request waits for a -// live worker to finalize a requested stop before force-finalizing the task. -// A live worker observes the stop (Redis cancel flag polled every 3s, plus the -// DB STOPPING fallback) well within this window; only a worker stuck in a -// non-cancellable section or a dead worker exceeds it. -const defaultSupersedeTerminalWait = 8 * time.Second - -const supersedePollInterval = 250 * time.Millisecond - -// supersedeAndRetryTask finalizes an in-flight ingestion task -// (SCHEDULED/RUNNING/STOPPING) and re-queues it for a fresh parse, mirroring -// the Python /documents/ingest endpoint, which accepts a parse request -// regardless of the previous task's in-flight state. Without this, a document -// whose task lingers in a non-terminal state — for example a parse canceled at -// progress 0 whose worker died before finalizing the stop (e.g. the service -// restarted mid-parse), or a scheduled task whose queue message was lost — -// could never be re-parsed: every attempt failed with "document id ... already -// exists, status: ...". -// -// For a task a worker may still be executing (RUNNING/STOPPING) the stop is -// requested first and the worker gets a bounded window to finalize on its own; -// a live worker settles within its 3s cancel poll. Only when that window -// expires is the task force-finalized. In every case the Redis cancel flag is -// cleared before the re-arm: the replacement run's pre-start cancel check -// (Ingestor.executeTask) reads the same flag and would abort the fresh parse -// before it starts, silently reproducing the "cannot re-parse" symptom. -func (s *IngestionTaskService) supersedeAndRetryTask(ctx context.Context, existing *entity.IngestionTask) (*entity.IngestionTask, error) { - inFlightStatus := existing.Status - if inFlightStatus == common.RUNNING { - // RequestStop moves RUNNING→STOPPING and sets the Redis cancel flag so - // a live worker aborts at its next cancellation checkpoint. - if _, err := s.RequestStop(ctx, existing.ID); err != nil { - // The worker may have finalized (stopped/completed/failed) - // concurrently; a terminal task is still supersedeable below. - refreshed, refreshErr := s.GetTask(ctx, existing.ID) - if refreshErr != nil || !isTerminalTaskStatus(refreshed.Status) { - return nil, fmt.Errorf("stop in-flight task %s before re-parse: %w", existing.ID, err) - } - existing = refreshed - } - } - if existing.Status == common.RUNNING || existing.Status == common.STOPPING { - final := s.awaitTerminalTask(ctx, existing.ID) - if final == nil { - var err error - if final, err = s.forceTerminalTask(ctx, existing.ID); err != nil { - return nil, fmt.Errorf("finalize in-flight task %s (%s) before re-parse: %w", existing.ID, inFlightStatus, err) - } - } - existing = final - } - if existing.Status == common.CREATED || existing.Status == common.SCHEDULED { - // Never claimed (or freshly re-armed by a concurrent request): no - // worker can be executing it, so finalize it immediately. - var err error - if existing, err = s.transition(ctx, existing.ID, common.STOPPED); err != nil { - return nil, fmt.Errorf("finalize in-flight task %s (%s) before re-parse: %w", existing.ID, inFlightStatus, err) - } - } - if !isTerminalTaskStatus(existing.Status) { - return nil, fmt.Errorf("task %s is in unexpected status %s before re-parse", existing.ID, existing.Status) - } - // The superseded run is final, so any leftover Redis cancel flag is stale - // for the replacement run (see the doc comment). - clearCancelFlag(ctx, existing.ID) - retried, err := s.transition(ctx, existing.ID, common.CREATED) - if err != nil { - return nil, fmt.Errorf("re-arm superseded task %s for re-parse: %w", existing.ID, err) - } - if err = s.enqueueTask(retried.ID); err != nil { - if rollbackErr := s.rollbackRetriedTask(ctx, retried.ID, existing.Status); rollbackErr != nil { - return nil, fmt.Errorf("enqueue task %s: %w (rollback failed: %w)", retried.ID, err, rollbackErr) - } - return nil, err - } - return s.markScheduledAfterPublish(ctx, retried.ID) -} - -// awaitTerminalTask polls the task until it reaches a terminal status or the -// supersede wait budget expires. Returns the terminal task, or nil on timeout. -func (s *IngestionTaskService) awaitTerminalTask(ctx context.Context, taskID string) *entity.IngestionTask { - wait := s.supersedeTerminalWait - if wait <= 0 { - wait = defaultSupersedeTerminalWait - } - deadline := time.Now().Add(wait) - for { - task, err := s.GetTask(ctx, taskID) - if err == nil && isTerminalTaskStatus(task.Status) { - return task - } - if time.Now().After(deadline) { - return nil - } - select { - case <-ctx.Done(): - return nil - case <-time.After(supersedePollInterval): - } - } -} - -// forceTerminalTask drives a task that missed its bounded stop window to a -// terminal state: STOPPING→STOPPED directly; RUNNING via RequestStop first (a -// worker may still be inside a non-cancellable section — the flag that sets is -// cleared by the caller right after the finalize, and the worker's late -// terminal write is skipped by its run-count ownership check in the Ingestor); -// CREATED/SCHEDULED→STOPPED because no worker is executing them. -func (s *IngestionTaskService) forceTerminalTask(ctx context.Context, taskID string) (*entity.IngestionTask, error) { - task, err := s.GetTask(ctx, taskID) - if err != nil { - return nil, err - } - switch task.Status { - case common.STOPPING, common.CREATED, common.SCHEDULED: - return s.transition(ctx, taskID, common.STOPPED) - case common.RUNNING: - if _, err = s.RequestStop(ctx, taskID); err != nil { - if refreshed, refreshErr := s.GetTask(ctx, taskID); refreshErr == nil && isTerminalTaskStatus(refreshed.Status) { - return refreshed, nil - } - return nil, err - } - return s.transition(ctx, taskID, common.STOPPED) - case common.COMPLETED, common.STOPPED, common.FAILED: - return task, nil - default: - return nil, fmt.Errorf("task %s has unsupported status %s", taskID, task.Status) - } -} - -func isTerminalTaskStatus(status string) bool { - return status == common.COMPLETED || status == common.STOPPED || status == common.FAILED -} - func (s *IngestionTaskService) rollbackRetriedTask(ctx context.Context, taskID, status string) error { updated, err := s.ingestionTaskDAO.UpdateStatusIfCurrent(ctx, dao.DB, taskID, common.CREATED, status) if err != nil { @@ -688,14 +546,6 @@ func (s *IngestionTaskService) AggregateTaskProgress(ctx context.Context, taskID return s.ingestionTaskLogDAO.AggregateProgress(ctx, dao.DB, taskID, total) } -// CurrentRunCount returns the run counter of the most recent started run for -// the task. Workers capture it right after IncrementRunCount and use it to -// detect that their run was superseded (a newer run bumped the counter) -// before writing terminal state. -func (s *IngestionTaskService) CurrentRunCount(ctx context.Context, taskID string) (int, bool) { - return s.lastRunCount(ctx, taskID) -} - // lastRunCount scans all task logs (newest first) for a run_count entry, // skipping component-progress rows whose Checkpoint is empty. It returns // the counter and whether one was found. diff --git a/internal/service/ingestion_task_service_test.go b/internal/service/ingestion_task_service_test.go index d444e57faf3..0820046c16d 100644 --- a/internal/service/ingestion_task_service_test.go +++ b/internal/service/ingestion_task_service_test.go @@ -5,7 +5,6 @@ import ( "strings" "sync" "testing" - "time" "ragflow/internal/common" "ragflow/internal/dao" @@ -811,107 +810,21 @@ func TestIngestionTaskServiceScheduleCreatedTasksContinuesAfterPublishFailure(t } } -func TestIngestionTaskServiceCreateAndEnqueueSupersedesInFlightTask(t *testing.T) { - for _, tc := range []struct { - name string - existing string - wantStatus string - }{ - { - // A parse canceled at progress 0 whose worker has not finalized the - // stop yet leaves the task in STOPPING; re-parsing waits a bounded - // window for the worker, then force-finalizes and re-queues. - name: "stopping", - existing: common.STOPPING, - wantStatus: common.SCHEDULED, - }, - { - // A task queued but never claimed by a worker (e.g. its queue - // message was lost) must not block re-parsing either. - name: "scheduled", - existing: common.SCHEDULED, - wantStatus: common.SCHEDULED, - }, - { - // A task whose worker died mid-run stays RUNNING with no owner; - // re-parsing must stop it (the only RUNNING→CREATED path in the - // transition table is RUNNING→STOPPING→STOPPED→CREATED) and queue - // a fresh run. - name: "running", - existing: common.RUNNING, - wantStatus: common.SCHEDULED, - }, - } { - t.Run(tc.name, func(t *testing.T) { - db := setupServiceTestDB(t) - pushServiceDB(t, db) - insertTestIngestionTaskWithStatus(t, "task-1", "user-1", "doc-1", "kb-1", tc.existing) - - publisher := &recordingTaskPublisher{} - svc := NewIngestionTaskService() - svc.taskPublisher = publisher - // No live worker in the test: do not pay the full production - // window before force-finalizing the in-flight task. - svc.supersedeTerminalWait = 50 * time.Millisecond - - task, err := svc.CreateAndEnqueue(t.Context(), &entity.IngestionTask{ - DocumentID: "doc-1", - UserID: "user-1", - DatasetID: "kb-1", - Status: common.CREATED, - }) - if err != nil { - t.Fatalf("CreateAndEnqueue failed: %v", err) - } - - if task.ID != "task-1" { - t.Fatalf("task ID = %q, want task-1 (superseded in place)", task.ID) - } - if task.Status != tc.wantStatus { - t.Fatalf("status = %q, want %q", task.Status, tc.wantStatus) - } - if len(publisher.messages) != 1 || publisher.messages[0].TaskID != task.ID { - t.Fatalf("unexpected published messages: %+v", publisher.messages) - } - - reloaded, err := dao.NewIngestionTaskDAO().GetByDocumentID(t.Context(), db, "doc-1") - if err != nil { - t.Fatalf("reload task: %v", err) - } - if reloaded == nil || reloaded.Status != tc.wantStatus { - t.Fatalf("expected superseded task to be re-queued, task=%+v", reloaded) - } - }) - } -} - -// TestIngestionTaskServiceCreateAndEnqueueRearmsCompletedTask locks in that a -// document whose previous parse COMPLETED can be re-parsed without first -// deleting its ingestion task: the terminal task row is re-armed in place, -// mirroring the FAILED/STOPPED handling. -func TestIngestionTaskServiceCreateAndEnqueueRearmsCompletedTask(t *testing.T) { +func TestIngestionTaskServiceCreateAndEnqueueRejectsActiveExistingTask(t *testing.T) { db := setupServiceTestDB(t) pushServiceDB(t, db) - insertTestIngestionTaskWithStatus(t, "task-1", "user-1", "doc-1", "kb-1", common.COMPLETED) - + insertTestIngestionTaskWithStatus(t, "task-1", "user-1", "doc-1", "kb-1", common.SCHEDULED) publisher := &recordingTaskPublisher{} svc := NewIngestionTaskService() svc.taskPublisher = publisher - task, err := svc.CreateAndEnqueue(t.Context(), &entity.IngestionTask{ - DocumentID: "doc-1", - UserID: "user-1", - DatasetID: "kb-1", - Status: common.CREATED, - }) - if err != nil { - t.Fatalf("CreateAndEnqueue failed: %v", err) - } - if task.ID != "task-1" || task.Status != common.SCHEDULED { - t.Fatalf("task = %s/%s, want task-1/SCHEDULED", task.ID, task.Status) + ctx := t.Context() + _, err := svc.CreateAndEnqueue(ctx, &entity.IngestionTask{DocumentID: "doc-1", UserID: "user-1", DatasetID: "kb-1", Status: common.CREATED}) + if err == nil { + t.Fatal("expected CreateAndEnqueue to reject existing created task") } - if len(publisher.messages) != 1 || publisher.messages[0].TaskID != task.ID { - t.Fatalf("unexpected published messages: %+v", publisher.messages) + if len(publisher.messages) != 0 { + t.Fatalf("expected no published messages, got %+v", publisher.messages) } } From c51f44bab3ff7d9a30ba81ae0cba1056a0c95590 Mon Sep 17 00:00:00 2001 From: mkaaad <119158371+mkaaad@users.noreply.github.com> Date: Thu, 10 Sep 2026 20:04:15 +0800 Subject: [PATCH 083/568] fix(agent/tool): translate MCP tool inputSchema.properties in Info() (#19244) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix MCPToolAdapter.Info() — now reads parameter names from inputSchema["properties"] instead of top-level schema keys. Model gets correct param names/types/required flags. --- internal/agent/tool/mcp.go | 44 ++++--- internal/agent/tool/mcp_test.go | 201 +++++++++++++++++++++++++++++++- 2 files changed, 224 insertions(+), 21 deletions(-) diff --git a/internal/agent/tool/mcp.go b/internal/agent/tool/mcp.go index f7deabc8204..424b53e0448 100644 --- a/internal/agent/tool/mcp.go +++ b/internal/agent/tool/mcp.go @@ -34,6 +34,7 @@ import ( "github.com/cloudwego/eino/components/tool" "github.com/cloudwego/eino/schema" + "github.com/eino-contrib/jsonschema" ) // MCPToolAdapter wraps a single MCP-discovered tool descriptor as an @@ -93,26 +94,33 @@ func NewMCPToolAdapterFull(t mcpclient.Tool, serverURL string, headers map[strin // Name returns the underlying MCP tool name. func (m *MCPToolAdapter) Name() string { return m.mcpTool.Name } -// Info returns eino-compatible tool metadata. InputSchema is -// translated from the MCP tool's JSON Schema. +// Info returns eino-compatible tool metadata. The MCP client stores the +// full inputSchema object ({"type":"object","properties":{...},"required": +// [...]}) on mcpTool.InputSchema, so we pass it through to eino's +// JSON Schema channel untouched. That keeps the real parameter names under +// "properties" (never the schema's top-level keys like "type"/"properties"/ +// "required") together with each property's type/description/required flag +// and any richer keywords (enum, default, items, nested objects, anyOf/oneOf, +// ...). A tool with no inputSchema takes no parameters: ParamsOneOf is left +// nil so callers emit an empty object schema instead of an invalid schema. func (m *MCPToolAdapter) Info(_ context.Context) (*schema.ToolInfo, error) { - // eino's schema.ParameterInfo shape: name → description. - // We translate the MCP tool's inputSchema.properties into a - // best-effort ParameterInfo map. For tools without a JSON schema - // the params map is empty — eino falls back to free-form args. - params := make(map[string]*schema.ParameterInfo, len(m.mcpTool.InputSchema)) - for name := range m.mcpTool.InputSchema { - params[name] = &schema.ParameterInfo{ - Type: schema.String, // conservative default - Desc: fmt.Sprintf("MCP tool parameter: %s", name), - Required: false, // MCP doesn't surface required; we err permissive - } + info := &schema.ToolInfo{ + Name: m.mcpTool.Name, + Desc: m.mcpTool.Description, } - return &schema.ToolInfo{ - Name: m.mcpTool.Name, - Desc: m.mcpTool.Description, - ParamsOneOf: schema.NewParamsOneOfByParams(params), - }, nil + if len(m.mcpTool.InputSchema) == 0 { + return info, nil + } + var js jsonschema.Schema + raw, err := json.Marshal(m.mcpTool.InputSchema) + if err != nil { + return nil, fmt.Errorf("encode MCP tool %q inputSchema: %w", m.mcpTool.Name, err) + } + if err := json.Unmarshal(raw, &js); err != nil { + return nil, fmt.Errorf("parse MCP tool %q inputSchema: %w", m.mcpTool.Name, err) + } + info.ParamsOneOf = schema.NewParamsOneOfByJSONSchema(&js) + return info, nil } // InvokableRun is the eino entry point. When the adapter was diff --git a/internal/agent/tool/mcp_test.go b/internal/agent/tool/mcp_test.go index 871813bf90b..a67188a161e 100644 --- a/internal/agent/tool/mcp_test.go +++ b/internal/agent/tool/mcp_test.go @@ -21,6 +21,7 @@ import ( "io" "net/http" "net/http/httptest" + "slices" "strings" "testing" "time" @@ -30,13 +31,27 @@ import ( // TestMCPToolAdapter_InfoReturnsMCPDescriptor: the eino ToolInfo // surface matches the underlying MCP tool's name, description, and -// input schema. +// input schema. The input schema is fed in the real wire shape the +// MCP client produces (full JSON Schema object) so the advertised +// parameters come from "properties" — never the schema's top-level +// keys ("type"/"properties"/"required"). func TestMCPToolAdapter_InfoReturnsMCPDescriptor(t *testing.T) { mcp := mcpclient.Tool{ Name: "search_docs", Description: "search internal docs", InputSchema: map[string]any{ - "query": map[string]any{"type": "string"}, + "type": "object", + "properties": map[string]any{ + "query": map[string]any{ + "type": "string", + "description": "the search query", + }, + "limit": map[string]any{ + "type": "integer", + "description": "max results", + }, + }, + "required": []any{"query"}, }, } a := NewMCPToolAdapter(mcp) @@ -54,7 +69,187 @@ func TestMCPToolAdapter_InfoReturnsMCPDescriptor(t *testing.T) { t.Errorf("ToolInfo.Desc=%q, want 'search internal docs'", info.Desc) } if info.ParamsOneOf == nil { - t.Error("expected non-nil ParamsOneOf") + t.Fatal("expected non-nil ParamsOneOf") + } + js, err := info.ParamsOneOf.ToJSONSchema() + if err != nil { + t.Fatalf("ToJSONSchema: %v", err) + } + if js.Type != "object" { + t.Errorf("schema type=%q, want object", js.Type) + } + if js.Properties == nil { + t.Fatal("expected non-nil properties") + } + if js.Properties.Len() != 2 { + t.Fatalf("expected 2 params, got %d", js.Properties.Len()) + } + for _, leaked := range []string{"type", "properties", "required"} { + if _, ok := js.Properties.Get(leaked); ok { + t.Errorf("schema top-level key %q leaked into advertised params", leaked) + } + } + + query, ok := js.Properties.Get("query") + if !ok { + t.Fatal("expected advertised param 'query'") + } + if query.Type != "string" { + t.Errorf("query.Type=%q, want string", query.Type) + } + if query.Description != "the search query" { + t.Errorf("query.Description=%q, want 'the search query'", query.Description) + } + if !slices.Contains(js.Required, "query") { + t.Errorf("query should be required per inputSchema.required; required=%v", js.Required) + } + + limit, ok := js.Properties.Get("limit") + if !ok { + t.Fatal("expected advertised param 'limit'") + } + if limit.Type != "integer" { + t.Errorf("limit.Type=%q, want integer", limit.Type) + } + if slices.Contains(js.Required, "limit") { + t.Errorf("limit should not be required; required=%v", js.Required) + } +} + +// TestMCPToolAdapter_InfoWithoutPropertiesFallsBackToFreeForm: a tool +// whose schema has no "properties" map advertises no params (eino falls +// back to free-form args) and does not leak schema top-level keys. +func TestMCPToolAdapter_InfoWithoutPropertiesFallsBackToFreeForm(t *testing.T) { + mcp := mcpclient.Tool{ + Name: "no_schema", + Description: "tool without property definitions", + InputSchema: map[string]any{"type": "object"}, + } + a := NewMCPToolAdapter(mcp) + info, err := a.Info(t.Context()) + if err != nil { + t.Fatalf("Info: %v", err) + } + if info.ParamsOneOf == nil { + t.Fatal("expected non-nil ParamsOneOf") + } + js, err := info.ParamsOneOf.ToJSONSchema() + if err != nil { + t.Fatalf("ToJSONSchema: %v", err) + } + if js.Properties != nil && js.Properties.Len() != 0 { + t.Errorf("expected no advertised params, got %d", js.Properties.Len()) + } +} + +// TestMCPToolAdapter_InfoWithoutInputSchema: an MCP tool with a missing or +// empty inputSchema takes no parameters. ParamsOneOf must stay nil — a +// non-nil empty jsonschema.Schema would serialize to `true`, which OpenAI +// tool calls would read as `"parameters": true` and reject. +func TestMCPToolAdapter_InfoWithoutInputSchema(t *testing.T) { + for name, inputSchema := range map[string]map[string]any{ + "missing": nil, + "empty": {}, + } { + t.Run(name, func(t *testing.T) { + a := NewMCPToolAdapter(mcpclient.Tool{Name: "no_params", InputSchema: inputSchema}) + info, err := a.Info(t.Context()) + if err != nil { + t.Fatalf("Info: %v", err) + } + if info.ParamsOneOf != nil { + t.Fatalf("expected nil ParamsOneOf for %s inputSchema, got non-nil", name) + } + raw, err := json.Marshal(info) + if err != nil { + t.Fatalf("Marshal ToolInfo: %v", err) + } + var got map[string]any + if err := json.Unmarshal(raw, &got); err != nil { + t.Fatalf("Unmarshal ToolInfo %s: %v", raw, err) + } + for _, leaked := range []string{"has_params_one_of", "json_schema"} { + if _, ok := got[leaked]; ok { + t.Fatalf("empty inputSchema must not advertise a parameters schema (key %q); got %s", leaked, raw) + } + } + }) + } +} + +// TestMCPToolAdapter_InfoPreservesRichJSONSchema: richer JSON Schema +// keywords (enum, default, array items, nested objects) survive the +// round-trip through eino's JSON Schema channel — the flat params form +// would have dropped them. +func TestMCPToolAdapter_InfoPreservesRichJSONSchema(t *testing.T) { + mcp := mcpclient.Tool{ + Name: "rich", + Description: "tool with a rich input schema", + InputSchema: map[string]any{ + "type": "object", + "properties": map[string]any{ + "mode": map[string]any{ + "type": "string", + "enum": []any{"fast", "slow"}, + "default": "fast", + }, + "tags": map[string]any{ + "type": "array", + "items": map[string]any{"type": "string"}, + }, + "filter": map[string]any{ + "type": "object", + "properties": map[string]any{ + "year": map[string]any{"type": "integer"}, + }, + }, + }, + }, + } + a := NewMCPToolAdapter(mcp) + info, err := a.Info(t.Context()) + if err != nil { + t.Fatalf("Info: %v", err) + } + js, err := info.ParamsOneOf.ToJSONSchema() + if err != nil { + t.Fatalf("ToJSONSchema: %v", err) + } + + mode, ok := js.Properties.Get("mode") + if !ok { + t.Fatal("expected param 'mode'") + } + if len(mode.Enum) != 2 || mode.Enum[0] != "fast" || mode.Enum[1] != "slow" { + t.Errorf("mode.Enum=%v, want [fast slow]", mode.Enum) + } + if mode.Default != "fast" { + t.Errorf("mode.Default=%v, want 'fast'", mode.Default) + } + + tags, ok := js.Properties.Get("tags") + if !ok { + t.Fatal("expected param 'tags'") + } + if tags.Type != "array" { + t.Errorf("tags.Type=%q, want array", tags.Type) + } + if tags.Items == nil || tags.Items.Type != "string" { + t.Errorf("tags.Items=%+v, want element type string", tags.Items) + } + + filter, ok := js.Properties.Get("filter") + if !ok { + t.Fatal("expected param 'filter'") + } + if filter.Type != "object" { + t.Errorf("filter.Type=%q, want object", filter.Type) + } + if filter.Properties == nil || filter.Properties.Len() != 1 { + t.Fatalf("filter.Properties.Len()=%d, want 1", filter.Properties.Len()) + } + if _, ok := filter.Properties.Get("year"); !ok { + t.Error("expected nested param 'year'") } } From 4c97c9ad64a0134eddf6f0766febf4735fb473c4 Mon Sep 17 00:00:00 2001 From: Lynn Date: Thu, 10 Sep 2026 20:04:39 +0800 Subject: [PATCH 084/568] Fix: remove deprecated functions (#19449) --- api/db/joint_services/tenant_model_service.py | 2 +- api/db/services/tenant_llm_service.py | 415 +----------------- 2 files changed, 2 insertions(+), 415 deletions(-) diff --git a/api/db/joint_services/tenant_model_service.py b/api/db/joint_services/tenant_model_service.py index a2133d57da3..f24ebad6eca 100644 --- a/api/db/joint_services/tenant_model_service.py +++ b/api/db/joint_services/tenant_model_service.py @@ -33,7 +33,7 @@ SOMARK_DEFAULT_CONFIG, SOMARK_ENV_KEYS, ) -from api.db.services.tenant_llm_service import TenantService +from api.db.services.user_service import TenantService from api.db.services.tenant_model_provider_service import TenantModelProviderService from api.db.services.tenant_model_instance_service import TenantModelInstanceService from api.db.services.tenant_model_service import TenantModelService diff --git a/api/db/services/tenant_llm_service.py b/api/db/services/tenant_llm_service.py index 42eafcdd06d..8d7613d6d33 100644 --- a/api/db/services/tenant_llm_service.py +++ b/api/db/services/tenant_llm_service.py @@ -13,17 +13,12 @@ # See the License for the specific language governing permissions and # limitations under the License. # -import os -import json import logging -from peewee import IntegrityError from langfuse import Langfuse -from common import settings -from common.constants import MINERU_DEFAULT_CONFIG, MINERU_ENV_KEYS, OPENDATALOADER_DEFAULT_CONFIG, OPENDATALOADER_ENV_KEYS, PADDLEOCR_DEFAULT_CONFIG, PADDLEOCR_ENV_KEYS, LLMType +from common.constants import LLMType from api.db.db_models import DB, LLMFactories, TenantLLM from api.db.services.common_service import CommonService from api.db.services.langfuse_service import TenantLangfuseService -from api.db.services.user_service import TenantService class LLMFactoriesService(CommonService): @@ -33,150 +28,6 @@ class LLMFactoriesService(CommonService): class TenantLLMService(CommonService): model = TenantLLM - @staticmethod - def _decode_api_key_config(raw_api_key: str) -> tuple[str, bool | None, str | None]: - if not raw_api_key: - return raw_api_key, None, None - - try: - parsed = json.loads(raw_api_key) - except Exception: - return raw_api_key, None, None - - if not isinstance(parsed, dict): - return raw_api_key, None, None - - is_tools = bool(parsed["is_tools"]) if "is_tools" in parsed else None - if set(parsed.keys()) <= {"api_key", "is_tools"}: - return parsed.get("api_key", ""), is_tools, None - - return parsed.get("api_key", raw_api_key), is_tools, raw_api_key - - @staticmethod - def _encode_api_key_config(raw_api_key: str, is_tools: bool | None) -> str: - if is_tools is None: - return raw_api_key - - try: - parsed = json.loads(raw_api_key or "{}") - except Exception: - parsed = None - - if isinstance(parsed, dict): - payload = dict(parsed) - payload["is_tools"] = bool(is_tools) - return json.dumps(payload) - - return json.dumps({"api_key": raw_api_key or "", "is_tools": bool(is_tools)}) - - @classmethod - @DB.connection_context() - def get_api_key(cls, tenant_id, model_name, model_type=None): - mdlnm, fid = TenantLLMService.split_model_name_and_factory(model_name) - model_type_val = model_type.value if hasattr(model_type, "value") else model_type - query_kwargs = {"tenant_id": tenant_id, "llm_name": mdlnm} - if model_type_val is not None: - query_kwargs["model_type"] = model_type_val - if not fid: - objs = cls.query(**query_kwargs) - else: - objs = cls.query(**query_kwargs, llm_factory=fid) - - if (not objs) and fid: - if fid == "LocalAI": - mdlnm += "___LocalAI" - elif fid == "HuggingFace": - mdlnm += "___HuggingFace" - elif fid == "OpenAI-API-Compatible": - mdlnm += "___OpenAI-API" - elif fid == "VLLM": - mdlnm += "___VLLM" - query_kwargs["llm_name"] = mdlnm - objs = cls.query(**query_kwargs, llm_factory=fid) - if not objs: - return None - return objs[0] - - @classmethod - @DB.connection_context() - def get_my_llms(cls, tenant_id): - fields = [cls.model.id, cls.model.llm_factory, LLMFactories.logo, LLMFactories.tags, cls.model.model_type, cls.model.llm_name, cls.model.used_tokens, cls.model.status] - objs = cls.model.select(*fields).join(LLMFactories, on=(cls.model.llm_factory == LLMFactories.name)).where(cls.model.tenant_id == tenant_id, ~cls.model.api_key.is_null()).dicts() - - return list(objs) - - @staticmethod - def split_model_name_and_factory(model_name): - arr = model_name.split("@") - if len(arr) < 2: - return model_name, None - if len(arr) > 2: - return "@".join(arr[0:-1]), arr[-1] - - # model name must be xxx@yyy - try: - model_factories = settings.FACTORY_LLM_INFOS - model_providers = set([f["name"] for f in model_factories]) - if arr[-1] not in model_providers: - return model_name, None - return arr[0], arr[-1] - except Exception as e: - logging.exception(f"TenantLLMService.split_model_name_and_factory got exception: {e}") - return model_name, None - - @classmethod - @DB.connection_context() - def get_model_config(cls, tenant_id, llm_type, llm_name=None): - from api.db.services.llm_service import LLMService - - e, tenant = TenantService.get_by_id(tenant_id) - if not e: - raise LookupError("Tenant not found") - - if llm_type == LLMType.EMBEDDING.value: - mdlnm = tenant.embd_id if not llm_name else llm_name - elif llm_type == LLMType.ASR.value: - mdlnm = tenant.asr_id if not llm_name else llm_name - elif llm_type == LLMType.VISION.value: - mdlnm = tenant.img2txt_id if not llm_name else llm_name - elif llm_type == LLMType.CHAT.value: - mdlnm = tenant.llm_id if not llm_name else llm_name - elif llm_type == LLMType.RERANK: - mdlnm = tenant.rerank_id if not llm_name else llm_name - elif llm_type == LLMType.TTS: - mdlnm = tenant.tts_id if not llm_name else llm_name - elif llm_type == LLMType.OCR: - if not llm_name: - raise LookupError("OCR model name is required") - mdlnm = llm_name - else: - assert False, "LLM type error" - - model_config = cls.get_api_key(tenant_id, mdlnm, llm_type) - mdlnm, fid = TenantLLMService.split_model_name_and_factory(mdlnm) - if not model_config: # for some cases seems fid mismatch - model_config = cls.get_api_key(tenant_id, mdlnm, llm_type) - if model_config: - model_config = model_config.to_dict() - api_key, is_tools, api_key_payload = cls._decode_api_key_config(model_config.get("api_key", "")) - model_config["api_key"] = api_key - if api_key_payload is not None: - model_config["api_key_payload"] = api_key_payload - if is_tools is not None: - model_config["is_tools"] = is_tools - elif llm_type == LLMType.EMBEDDING and fid == "Builtin" and "tei-" in os.getenv("COMPOSE_PROFILES", "") and mdlnm == os.getenv("TEI_MODEL", ""): - embedding_cfg = settings.EMBEDDING_CFG - model_config = {"llm_factory": "Builtin", "api_key": embedding_cfg["api_key"], "llm_name": mdlnm, "api_base": embedding_cfg["base_url"]} - else: - raise LookupError(f"Model({mdlnm}@{fid}) not authorized") - - llm = LLMService.query(llm_name=mdlnm) if not fid else LLMService.query(llm_name=mdlnm, fid=fid) - if not llm and fid: # for some cases seems fid mismatch - llm = LLMService.query(llm_name=mdlnm) - if "is_tools" not in model_config and llm: - model_config["is_tools"] = llm[0].is_tools - return model_config - @classmethod @DB.connection_context() def model_instance(cls, model_config: dict, lang="Chinese", **kwargs): @@ -238,270 +89,6 @@ def model_instance(cls, model_config: dict, lang="Chinese", **kwargs): return None - @classmethod - @DB.connection_context() - def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None): - e, tenant = TenantService.get_by_id(tenant_id) - if not e: - logging.error(f"Tenant not found: {tenant_id}") - return 0 - - llm_map = { - LLMType.EMBEDDING.value: tenant.embd_id if not llm_name else llm_name, - LLMType.ASR.value: tenant.asr_id, - LLMType.VISION.value: tenant.img2txt_id, - LLMType.CHAT.value: tenant.llm_id if not llm_name else llm_name, - LLMType.RERANK.value: tenant.rerank_id if not llm_name else llm_name, - LLMType.TTS.value: tenant.tts_id if not llm_name else llm_name, - LLMType.OCR.value: llm_name, - } - - mdlnm = llm_map.get(llm_type) - if mdlnm is None: - logging.error(f"LLM type error: {llm_type}") - return 0 - - llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(mdlnm) - - try: - num = ( - cls.model.update(used_tokens=cls.model.used_tokens + used_tokens) - .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == llm_name, cls.model.llm_factory == llm_factory if llm_factory else True) - .execute() - ) - except Exception: - logging.exception("TenantLLMService.increase_usage got exception,Failed to update used_tokens for tenant_id=%s, llm_name=%s", tenant_id, llm_name) - return 0 - - return num - - @classmethod - @DB.connection_context() - def increase_usage_by_id(cls, tenant_model_id: int, used_tokens: int): - try: - update_cnt = cls.model.update(used_tokens=cls.model.used_tokens + used_tokens).where(cls.model.id == tenant_model_id).execute() - except Exception as e: - logging.exception(f"TenantLLMService.increase_usage got exception {e}, Failed to update used_tokens for tenant_model_id {tenant_model_id}") - return 0 - return update_cnt - - @classmethod - @DB.connection_context() - def get_openai_models(cls): - objs = cls.model.select().where((cls.model.llm_factory == "OpenAI"), ~(cls.model.llm_name == "text-embedding-3-small"), ~(cls.model.llm_name == "text-embedding-3-large")).dicts() - return list(objs) - - @classmethod - def _collect_mineru_env_config(cls) -> dict | None: - cfg = MINERU_DEFAULT_CONFIG - found = False - for key in MINERU_ENV_KEYS: - val = os.environ.get(key) - if val: - found = True - cfg[key] = val - return cfg if found else None - - @classmethod - @DB.connection_context() - def ensure_mineru_from_env(cls, tenant_id: str) -> str | None: - """ - Ensure a MinerU OCR model exists for the tenant if env variables are present. - Return the existing or newly created llm_name, or None if env not set. - """ - cfg = cls._collect_mineru_env_config() - if not cfg: - return None - - saved_mineru_models = cls.query(tenant_id=tenant_id, llm_factory="MinerU", model_type=LLMType.OCR.value) - - def _parse_api_key(raw: str) -> dict: - try: - return json.loads(raw or "{}") - except Exception: - return {} - - for item in saved_mineru_models: - api_cfg = _parse_api_key(item.api_key) - normalized = {k: api_cfg.get(k, MINERU_DEFAULT_CONFIG.get(k)) for k in MINERU_ENV_KEYS} - if normalized == cfg: - return item.llm_name - - used_names = {item.llm_name for item in saved_mineru_models} - idx = 1 - base_name = "mineru-from-env" - while True: - candidate = f"{base_name}-{idx}" - if candidate in used_names: - idx += 1 - continue - - try: - cls.save( - tenant_id=tenant_id, - llm_factory="MinerU", - llm_name=candidate, - model_type=LLMType.OCR.value, - api_key=json.dumps(cfg), - api_base="", - max_tokens=0, - ) - return candidate - except IntegrityError: - logging.warning("MinerU env model %s already exists for tenant %s, retry with next name", candidate, tenant_id) - used_names.add(candidate) - idx += 1 - continue - - @classmethod - def _collect_paddleocr_env_config(cls) -> dict | None: - cfg = PADDLEOCR_DEFAULT_CONFIG - found = False - for key in PADDLEOCR_ENV_KEYS: - val = os.environ.get(key) - if val: - found = True - cfg[key] = val - return cfg if found else None - - @classmethod - @DB.connection_context() - def ensure_paddleocr_from_env(cls, tenant_id: str) -> str | None: - """ - Ensure a PaddleOCR model exists for the tenant if env variables are present. - Return the existing or newly created llm_name, or None if env not set. - """ - cfg = cls._collect_paddleocr_env_config() - if not cfg: - return None - - saved_paddleocr_models = cls.query(tenant_id=tenant_id, llm_factory="PaddleOCR", model_type=LLMType.OCR.value) - - def _parse_api_key(raw: str) -> dict: - try: - return json.loads(raw or "{}") - except Exception: - return {} - - for item in saved_paddleocr_models: - api_cfg = _parse_api_key(item.api_key) - normalized = {k: api_cfg.get(k, PADDLEOCR_DEFAULT_CONFIG.get(k)) for k in PADDLEOCR_ENV_KEYS} - if normalized == cfg: - return item.llm_name - - used_names = {item.llm_name for item in saved_paddleocr_models} - idx = 1 - base_name = "paddleocr-from-env" - while True: - candidate = f"{base_name}-{idx}" - if candidate in used_names: - idx += 1 - continue - - try: - cls.save( - tenant_id=tenant_id, - llm_factory="PaddleOCR", - llm_name=candidate, - model_type=LLMType.OCR.value, - api_key=json.dumps(cfg), - api_base="", - max_tokens=0, - ) - return candidate - except IntegrityError: - logging.warning("PaddleOCR env model %s already exists for tenant %s, retry with next name", candidate, tenant_id) - used_names.add(candidate) - idx += 1 - continue - - @classmethod - def _collect_opendataloader_env_config(cls) -> dict | None: - cfg = dict(OPENDATALOADER_DEFAULT_CONFIG) - found = False - for key in OPENDATALOADER_ENV_KEYS: - val = os.environ.get(key) - if val: - found = True - cfg[key] = val - return cfg if found else None - - @classmethod - @DB.connection_context() - def ensure_opendataloader_from_env(cls, tenant_id: str) -> str | None: - """ - Ensure an OpenDataLoader OCR model exists for the tenant if env variables are present. - Return the existing or newly created llm_name, or None if env not set. - """ - cfg = cls._collect_opendataloader_env_config() - if not cfg: - return None - - saved_models = cls.query(tenant_id=tenant_id, llm_factory="OpenDataLoader", model_type=LLMType.OCR.value) - - def _parse_api_key(raw: str) -> dict: - try: - return json.loads(raw or "{}") - except Exception: - return {} - - for item in saved_models: - api_cfg = _parse_api_key(item.api_key) - normalized = {k: api_cfg.get(k, OPENDATALOADER_DEFAULT_CONFIG.get(k)) for k in OPENDATALOADER_ENV_KEYS} - if normalized == cfg: - return item.llm_name - - used_names = {item.llm_name for item in saved_models} - idx = 1 - base_name = "opendataloader-from-env" - while True: - candidate = f"{base_name}-{idx}" - if candidate in used_names: - idx += 1 - continue - try: - cls.save( - tenant_id=tenant_id, - llm_factory="OpenDataLoader", - llm_name=candidate, - model_type=LLMType.OCR.value, - api_key=json.dumps(cfg), - api_base="", - max_tokens=0, - ) - return candidate - except IntegrityError: - logging.warning("OpenDataLoader env model %s already exists for tenant %s, retry with next name", candidate, tenant_id) - used_names.add(candidate) - idx += 1 - continue - - @classmethod - @DB.connection_context() - def delete_by_tenant_id(cls, tenant_id): - return cls.model.delete().where(cls.model.tenant_id == tenant_id).execute() - - @staticmethod - def llm_id2llm_type(llm_id: str) -> str | None: - from api.db.services.llm_service import LLMService - - llm_id, *_ = TenantLLMService.split_model_name_and_factory(llm_id) - llm_factories = settings.FACTORY_LLM_INFOS - for llm_factory in llm_factories: - for llm in llm_factory["llm"]: - if llm_id == llm["llm_name"]: - return llm["model_type"].split(",")[-1] - - for llm in LLMService.query(llm_name=llm_id): - return llm.model_type - - llm = TenantLLMService.get_or_none(llm_name=llm_id) - if llm: - return llm.model_type - for llm in TenantLLMService.query(llm_name=llm_id): - return llm.model_type - return None - class LLM4Tenant: def __init__(self, tenant_id: str, model_config: dict, lang="Chinese", **kwargs): From 099e4580a05a7c39a13cb29906b3a019389ae5a4 Mon Sep 17 00:00:00 2001 From: Wenchao An Date: Thu, 10 Sep 2026 20:07:57 +0800 Subject: [PATCH 085/568] fix(sdk): preserve agent answer references (#19365) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix SDK losing agent references — now reads from nested event data, not outer event. Streaming message_end events no longer discarded. --- sdk/python/ragflow_sdk/modules/session.py | 27 +++++++-- ...test_create_session_with_chat_assistant.py | 59 +++++++++++++++++++ 2 files changed, 81 insertions(+), 5 deletions(-) diff --git a/sdk/python/ragflow_sdk/modules/session.py b/sdk/python/ragflow_sdk/modules/session.py index 9cbd5d9c34c..ef3b7a5e2b7 100644 --- a/sdk/python/ragflow_sdk/modules/session.py +++ b/sdk/python/ragflow_sdk/modules/session.py @@ -121,13 +121,22 @@ def ask( continue # Skip lines that are not valid JSON event = json_data.get("event", None) - if event and event != "message": - continue + if event: + if self.__session_type == "agent" and event not in {"message", "message_end"}: + continue + if self.__session_type == "chat" and event != "message": + continue - if (self.__session_type == "agent" and event == "message_end") or (self.__session_type == "chat" and json_data.get("data") is True): + if self.__session_type == "chat" and json_data.get("data") is True: return if self.__session_type == "agent": - yield self._structure_answer(json_data) + message = self._structure_answer(json_data) + if event == "message_end": + message.content = "" + if message.reference: + yield message + continue + yield message else: yield self._structure_answer(json_data["data"]) else: @@ -139,15 +148,23 @@ def ask( def _structure_answer(self, json_data): answer = "" + event = None if self.__session_type == "agent": - answer = json_data["data"]["content"] + event = json_data.get("event") + json_data = json_data["data"] + answer = json_data.get("content", "") elif self.__session_type == "chat": answer = json_data["answer"] reference = json_data.get("reference", {}) temp_dict = {"content": answer, "role": "assistant"} if reference and "chunks" in reference: chunks = reference["chunks"] + if isinstance(chunks, dict): + chunks = list(chunks.values()) temp_dict["reference"] = chunks + if self.__session_type == "agent": + reference_count = len(chunks) if isinstance(chunks, list) else 0 + logger.debug("Session.ask parsed agent references session_id=%s event=%s reference_count=%s", self.id, event, reference_count) message = Message(self.rag, temp_dict) return message diff --git a/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py b/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py index 1e0ded15761..08fb241162b 100644 --- a/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py +++ b/test/testcases/test_sdk_api/test_session_management/test_create_session_with_chat_assistant.py @@ -32,6 +32,14 @@ def iter_lines(self, decode_unicode=True): yield line +class _DummyJsonResponse: + def __init__(self, payload): + self._payload = payload + + def json(self): + return self._payload + + @pytest.mark.usefixtures("clear_session_with_chat_assistants") class TestSessionWithChatAssistantCreate: @pytest.mark.p3 @@ -156,3 +164,54 @@ def _agent_post(path, json=None, stream=False, files=None): assert calls[1][2]["openai-compatible"] is False assert calls[1][2]["top_p"] == 0.8 assert calls[1][3] is True + + +@pytest.mark.p2 +def test_agent_session_preserves_non_stream_reference_chunks(monkeypatch, caplog): + first_chunk = {"id": "chunk-1", "content": "first source"} + second_chunk = {"id": "chunk-2", "content": "second source"} + session = Session(None, {"id": "session-agent", "agent_id": "agent-1"}) + response = _DummyJsonResponse( + { + "data": { + "event": "message_end", + "data": { + "content": "agent-answer", + "reference": {"chunks": {"500": first_chunk, "100": second_chunk}}, + }, + } + } + ) + monkeypatch.setattr(session, "post", lambda *_args, **_kwargs: response) + + with caplog.at_level("DEBUG", logger="ragflow_sdk.modules.session"): + messages = list(session.ask("hello agent", stream=False)) + + assert len(messages) == 1 + assert messages[0].content == "agent-answer" + assert messages[0].reference == [first_chunk, second_chunk] + assert "session_id=session-agent event=message_end reference_count=2" in caplog.text + assert "first source" not in caplog.text + assert "second source" not in caplog.text + + +@pytest.mark.p2 +def test_agent_session_streams_all_message_references_without_duplicate_content(monkeypatch): + first_chunk = {"id": "chunk-1", "content": "first source"} + second_chunk = {"id": "chunk-2", "content": "second source"} + session = Session(None, {"id": "session-agent", "agent_id": "agent-1"}) + response = _DummyStreamResponse( + [ + 'data: {"event":"message","data":{"content":"first answer"}}', + 'data: {"event":"message_end","data":{"content":"first answer","reference":{"chunks":{"123":{"id":"chunk-1","content":"first source"}}}}}', + 'data: {"event":"message","data":{"content":"second answer"}}', + 'data: {"event":"message_end","data":{"content":"second answer","reference":{"chunks":{"456":{"id":"chunk-2","content":"second source"}}}}}', + "data: [DONE]", + ] + ) + monkeypatch.setattr(session, "post", lambda *_args, **_kwargs: response) + + messages = list(session.ask("hello agent", stream=True)) + + assert "".join(message.content for message in messages) == "first answersecond answer" + assert [message.reference for message in messages if message.reference] == [[first_chunk], [second_chunk]] From 3dab5db31510d1b5938a5c2bdf77330db33cf3a6 Mon Sep 17 00:00:00 2001 From: xu jiaming <78154672+xu-jia-ming@users.noreply.github.com> Date: Thu, 10 Sep 2026 20:12:43 +0800 Subject: [PATCH 086/568] fix(mcp): send rerank_candidates_count so retrieval paging works past 64 results (#19018) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix #19017 — MCP retrieval now sends rerank_candidates_count = max(64, page * page_size), fixing paging past 64 results. --- internal/handler/mcp_retrieval_window_test.go | 53 ++++++++ internal/handler/mcp_server.go | 30 +++++ mcp/server/server.py | 23 ++++ test/unit_test/mcp/test_server_retrieval.py | 113 ++++++++++++++++++ 4 files changed, 219 insertions(+) create mode 100644 internal/handler/mcp_retrieval_window_test.go create mode 100644 test/unit_test/mcp/test_server_retrieval.py diff --git a/internal/handler/mcp_retrieval_window_test.go b/internal/handler/mcp_retrieval_window_test.go new file mode 100644 index 00000000000..cc913fc917e --- /dev/null +++ b/internal/handler/mcp_retrieval_window_test.go @@ -0,0 +1,53 @@ +package handler + +import ( + "math" + "strings" + "testing" +) + +func TestValidateRetrievalWindow(t *testing.T) { + tests := []struct { + name string + page int + pageSize int + wantErr string + }{ + {name: "defaults fit the window", page: 0, pageSize: 0}, // treated as 1 x 30 + {name: "first page at schema max", page: 1, pageSize: 100}, + {name: "paging stays inside the window", page: 5, pageSize: 100}, + {name: "exact boundary is allowed", page: 8, pageSize: 64}, // 8 * 64 == 512 + { + name: "one past the boundary is rejected", + page: 9, + pageSize: 64, + wantErr: "exceeds the fixed rerank candidate window", + }, + { + name: "window past the fixed candidates is rejected", + page: mcpRerankCandidatesCount/100 + 1, + pageSize: 100, + wantErr: "exceeds the fixed rerank candidate window", + }, + { + name: "max int page cannot overflow the check", + page: math.MaxInt, + pageSize: math.MaxInt, + wantErr: "exceeds the fixed rerank candidate window", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := validateRetrievalWindow(tt.page, tt.pageSize) + if tt.wantErr == "" { + if err != nil { + t.Fatalf("validateRetrievalWindow(%d, %d) = %v, want nil", tt.page, tt.pageSize, err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("validateRetrievalWindow(%d, %d) = %v, want error containing %q", tt.page, tt.pageSize, err, tt.wantErr) + } + }) + } +} diff --git a/internal/handler/mcp_server.go b/internal/handler/mcp_server.go index 9346363bb3b..0b1fc943b8b 100644 --- a/internal/handler/mcp_server.go +++ b/internal/handler/mcp_server.go @@ -141,10 +141,36 @@ func MCPListChats(ctx context.Context, chatService *service.ChatService, userID return chatList, resp.Total, nil } +// mcpRerankCandidatesCount is the fixed rerank candidate window sent with every +// retrieval request, so the ranking cannot shift between pages of one +// pagination sequence. Requests whose page * page_size exceeds it are rejected +// up front. Keep in sync with _RERANK_CANDIDATES_COUNT in mcp/server/server.py. +const mcpRerankCandidatesCount = 512 + +// validateRetrievalWindow checks that the requested page fits inside the fixed +// rerank candidate window. page/page_size default to the same values as the +// Python MCP server (1/30) when unset. The comparison divides instead of +// multiplying so a hostile page value cannot overflow page * pageSize. +func validateRetrievalWindow(page, pageSize int) error { + if page <= 0 { + page = 1 + } + if pageSize <= 0 { + pageSize = 30 + } + if page > mcpRerankCandidatesCount/pageSize { + return fmt.Errorf("page (%d) * page_size (%d) exceeds the fixed rerank candidate window (%d); narrow page or page_size", page, pageSize, mcpRerankCandidatesCount) + } + return nil +} + // MCPRetrieval executes a retrieval request on behalf of the MCP tool handler. // It translates the mcp.RetrievalRequest into a service.SearchDatasetsRequest // and calls DatasetService.SearchDatasets. The result is serialized as JSON. func MCPRetrieval(ctx context.Context, ds *dataset.DatasetService, userID string, req mcp.RetrievalRequest) (string, error) { + if err := validateRetrievalWindow(req.Page, req.PageSize); err != nil { + return "", err + } // Resolve dataset IDs: if none provided, fetch ALL accessible datasets // across all pages (matching Python _fetch_all_datasets behaviour). datasetIDs := req.DatasetIDs @@ -197,6 +223,10 @@ func MCPRetrieval(ctx context.Context, ds *dataset.DatasetService, userID string v := req.RerankID searchReq.RerankID = &v } + { + v := mcpRerankCandidatesCount + searchReq.RerankCandidatesCount = &v + } { v := req.Keyword searchReq.Keyword = &v diff --git a/mcp/server/server.py b/mcp/server/server.py index 2b94c2a0373..1fafcf857b8 100644 --- a/mcp/server/server.py +++ b/mcp/server/server.py @@ -63,6 +63,12 @@ class RAGFlowConnector: _CACHE_TTL = 300 # Keep in sync with api.utils.pagination_utils.REST_API_MAX_PAGE_SIZE. _REST_API_MAX_PAGE_SIZE = 100 + # Fixed rerank candidate window sent with every retrieval request, so the + # ranking cannot shift between pages of one pagination sequence (the backend + # reranks this many candidates before slicing the requested page). Requests + # whose page * page_size exceeds it are rejected up front. Keep in sync with + # mcpRerankCandidatesCount in internal/handler/mcp_server.go. + _RERANK_CANDIDATES_COUNT = 512 _dataset_metadata_cache: OrderedDict[str, tuple[dict, float | int]] = OrderedDict() # "dataset_id" -> (metadata, expiry_ts) _document_metadata_cache: OrderedDict[str, tuple[list[tuple[str, dict]], float | int]] = OrderedDict() # "dataset_id" -> ([(document_id, doc_metadata)], expiry_ts) @@ -294,6 +300,19 @@ async def retrieval( logging.info("MCP retrieval found no accessible datasets for current user") raise Exception([types.TextContent(type="text", text="No accessible datasets found.")]) + if page * page_size > self._RERANK_CANDIDATES_COUNT: + # Fail here rather than letting the backend reject the request: a + # window past the fixed candidate pool cannot be served with a + # stable ranking anyway. + raise Exception( + [ + types.TextContent( + type="text", + text=(f"page * page_size ({page * page_size}) exceeds the fixed rerank candidate window ({self._RERANK_CANDIDATES_COUNT}); narrow page or page_size."), + ) + ] + ) + data_json = { "page": page, "page_size": page_size, @@ -301,6 +320,10 @@ async def retrieval( "vector_similarity_weight": vector_similarity_weight, "top_k": top_k, "rerank_id": rerank_id, + # A fixed window (not page * page_size) keeps the rerank pool — and + # therefore the ranking — identical on every page of a pagination + # sequence, so pages cannot drift, duplicate, or skip results. + "rerank_candidates_count": self._RERANK_CANDIDATES_COUNT, "keyword": keyword, "question": question, "dataset_ids": dataset_ids, diff --git a/test/unit_test/mcp/test_server_retrieval.py b/test/unit_test/mcp/test_server_retrieval.py new file mode 100644 index 00000000000..7008e83b809 --- /dev/null +++ b/test/unit_test/mcp/test_server_retrieval.py @@ -0,0 +1,113 @@ +# +# 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. +# + +import importlib.util +from pathlib import Path + +import pytest + + +def _load_mcp_server(): + server_path = Path(__file__).resolve().parents[3] / "mcp" / "server" / "server.py" + spec = importlib.util.spec_from_file_location("ragflow_mcp_server_unit", server_path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class _FakeResponse: + status_code = 200 + + def __init__(self, payload): + self._payload = payload + + def json(self): + return self._payload + + +@pytest.fixture() +def mcp_server(): + return _load_mcp_server() + + +def _stub_retrieval(monkeypatch, connector): + captured = {} + + async def _post(path, json=None, api_key=""): + captured["path"] = path + captured["payload"] = dict(json) + return _FakeResponse({"code": 0, "data": {"chunks": [], "total": 0, "doc_aggs": []}}) + + async def _get_document_metadata_cache(*args, **kwargs): + return {}, {} + + monkeypatch.setattr(connector, "_post", _post) + monkeypatch.setattr(connector, "_get_document_metadata_cache", _get_document_metadata_cache) + return captured + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "page,page_size", + [ + (1, 10), # default page_size + (1, 50), # recommended page_size + (2, 50), # paging keeps the same candidate window + (7, 10), # default page_size paged past the backend's default 64 + (1, 100), # schema maximum + ], +) +async def test_retrieval_sends_fixed_rerank_candidates_window(monkeypatch, mcp_server, page, page_size): + """The candidate window is a fixed constant rather than page * page_size, so + the rerank pool — and therefore the ranking — stays identical on every page + of a pagination sequence; a growing window could reorder results between + pages, duplicating or skipping chunks.""" + connector = mcp_server.RAGFlowConnector(base_url=mcp_server.BASE_URL) + captured = _stub_retrieval(monkeypatch, connector) + + await connector.retrieval( + api_key="unit-key", + dataset_ids=["dataset-1"], + question="unit question", + page=page, + page_size=page_size, + ) + + assert captured["path"] == "/retrieval" + payload = captured["payload"] + assert payload["rerank_candidates_count"] == mcp_server.RAGFlowConnector._RERANK_CANDIDATES_COUNT + assert payload["rerank_candidates_count"] >= page * page_size + + +@pytest.mark.asyncio +async def test_retrieval_rejects_window_beyond_fixed_candidates(monkeypatch, mcp_server): + """Requests that cannot fit inside the fixed candidate window fail up front + with an actionable message instead of surfacing the backend's rejection (or + worse, silently serving drifting pages).""" + connector = mcp_server.RAGFlowConnector(base_url=mcp_server.BASE_URL) + captured = _stub_retrieval(monkeypatch, connector) + + window = mcp_server.RAGFlowConnector._RERANK_CANDIDATES_COUNT + with pytest.raises(Exception, match="exceeds the fixed rerank candidate window"): + await connector.retrieval( + api_key="unit-key", + dataset_ids=["dataset-1"], + question="unit question", + page=window // 100 + 1, + page_size=100, + ) + + assert "payload" not in captured # rejected before any request was sent From 13458475c097f69f6f6ce3f7e1cc6b6693c84727 Mon Sep 17 00:00:00 2001 From: Zhu Lei <123629497+kabishou11@users.noreply.github.com> Date: Thu, 10 Sep 2026 21:11:48 +0800 Subject: [PATCH 087/568] fix(agent): compare retrieval KBs by resolved embedding model, not raw embd_id (#19206) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix #19203 — agent retrieval now treats UUID and composite embedding IDs as same model when tenant_embd_id matches, reusing validate_dataset_embedding_models. --- agent/tools/retrieval.py | 27 +++- .../agent/test_variable_ref_pattern_unit.py | 6 +- .../tools/test_retrieval_embedding_compat.py | 138 ++++++++++++++++++ 3 files changed, 163 insertions(+), 8 deletions(-) create mode 100644 test/unit_test/agent/tools/test_retrieval_embedding_compat.py diff --git a/agent/tools/retrieval.py b/agent/tools/retrieval.py index 190d8f5f81e..1ab7a6522ed 100644 --- a/agent/tools/retrieval.py +++ b/agent/tools/retrieval.py @@ -23,7 +23,7 @@ from common.constants import LLMType from api.db.services.doc_metadata_service import DocMetadataService from common.metadata_utils import apply_meta_data_filter -from api.db.services.knowledgebase_service import KnowledgebaseService +from api.db.services.knowledgebase_service import KnowledgebaseService, validate_dataset_embedding_models from api.db.services.llm_service import LLMBundle from api.db.services.memory_service import MemoryService from api.db.joint_services import memory_message_service @@ -34,6 +34,21 @@ from rag.prompts.generator import cross_languages, kb_prompt, memory_prompt +def _shared_embedding_id(records, mismatch_message: str): + """Return a stored embedding id when records share one resolved model. + + Comparison uses ``validate_dataset_embedding_models`` so a tenant_model + UUID and a legacy ``model@instance@provider`` composite are compatible + when they refer to the same model. Empty or unresolved names stay + isolated. The returned value is an original stored ``embd_id`` (UUID or + composite) for ``resolve_model_config``, not a normalized base name. + """ + err = validate_dataset_embedding_models(records) + if err: + raise Exception(mismatch_message) + return next((rec.embd_id for rec in records if rec.embd_id), None) + + class RetrievalParam(ToolParamBase): """ Define the Retrieval component parameters. @@ -132,13 +147,12 @@ async def _retrieve_kb(self, query_text: str): if not kbs: raise Exception("No dataset is selected.") - embd_nms = list(set([kb.embd_id for kb in kbs])) - assert len(embd_nms) == 1, "Knowledge bases use different embedding models." + embd_id = _shared_embedding_id(kbs, "Knowledge bases use different embedding models.") embd_mdl = None - if embd_nms: + if embd_id: tenant_id = self._canvas.get_tenant_id() - embd_model_config = resolve_model_config(tenant_id, LLMType.EMBEDDING, embd_nms[0]) + embd_model_config = resolve_model_config(tenant_id, LLMType.EMBEDDING, embd_id) embd_mdl = LLMBundle(tenant_id, embd_model_config) rerank_mdl = None @@ -259,8 +273,7 @@ async def _retrieve_memory(self, query_text: str): if not memory_list: raise Exception("No memory is selected.") - embd_names = list({memory.embd_id for memory in memory_list}) - assert len(embd_names) == 1, "Memory use different embedding models." + _shared_embedding_id(memory_list, "Memory use different embedding models.") vars = self.get_input_elements_from_text(query_text) vars = {k: o["value"] for k, o in vars.items()} diff --git a/test/unit_test/agent/test_variable_ref_pattern_unit.py b/test/unit_test/agent/test_variable_ref_pattern_unit.py index 9856c0837d8..78cabe28514 100644 --- a/test/unit_test/agent/test_variable_ref_pattern_unit.py +++ b/test/unit_test/agent/test_variable_ref_pattern_unit.py @@ -148,7 +148,11 @@ class ToolBase(base_module.ComponentBase): install_module("api.db.services", package=True) install_module("api.db.joint_services", package=True) install_module("api.db.services.doc_metadata_service", DocMetadataService=type("DocMetadataService", (), {})) - install_module("api.db.services.knowledgebase_service", KnowledgebaseService=type("KnowledgebaseService", (), {})) + install_module( + "api.db.services.knowledgebase_service", + KnowledgebaseService=type("KnowledgebaseService", (), {}), + validate_dataset_embedding_models=lambda _kbs: None, + ) install_module("api.db.services.llm_service", LLMBundle=type("LLMBundle", (), {})) install_module("api.db.services.memory_service", MemoryService=type("MemoryService", (), {})) install_module("api.db.joint_services.memory_message_service") diff --git a/test/unit_test/agent/tools/test_retrieval_embedding_compat.py b/test/unit_test/agent/tools/test_retrieval_embedding_compat.py new file mode 100644 index 00000000000..2a11211d895 --- /dev/null +++ b/test/unit_test/agent/tools/test_retrieval_embedding_compat.py @@ -0,0 +1,138 @@ +# +# 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. +# +"""Regression tests for agent Retrieval KB/memory embedding compatibility. + +Datasets may store a tenant_model UUID or a ``model@instance@provider`` +composite in ``embd_id``. Chat/assistant selection treats those as compatible +when they share a tenant_embd_id / base name. The Retrieval canvas component +must use the same ``validate_dataset_embedding_models`` comparison rather than +comparing raw ``embd_id`` strings. + +This test loads only the relevant function definitions via AST so it does not +pull in the full ``api.db.db_models`` import chain. +""" + +import ast +from pathlib import Path +from types import SimpleNamespace + +import pytest + +pytestmark = pytest.mark.p2 + +_REPO_ROOT = Path(__file__).resolve().parents[4] +_KB_SERVICE = _REPO_ROOT / "api" / "db" / "services" / "knowledgebase_service.py" +_RETRIEVAL = _REPO_ROOT / "agent" / "tools" / "retrieval.py" + +TENANT_EMBD_ID = "aa6f9604a1d411f1a1fc65466754f1f9" +COMPOSITE = "bge-m3:latest@Ollama local@Ollama" +OTHER_COMPOSITE = "Qwen/Qwen3-Embedding-0.6B@1@SILICONFLOW" + + +def _exec_functions(src_path, names, ns): + tree = ast.parse(src_path.read_text(encoding="utf-8")) + nodes = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in names] + missing = set(names) - {n.name for n in nodes} + assert not missing, f"missing functions in {src_path}: {missing}" + module = ast.Module(body=nodes, type_ignores=[]) + exec(compile(module, str(src_path), "exec"), ns) # noqa: S102 - exec'ing AST-extracted functions from our own source file + return ns + + +def _load_shared_embedding_id(resolved_names): + ns = {"get_composite_model_name_by_ids": lambda _ids: resolved_names} + _exec_functions( + _KB_SERVICE, + ("_base_model_name", "_kb_embedding_base_name", "validate_dataset_embedding_models"), + ns, + ) + _exec_functions(_RETRIEVAL, ("_shared_embedding_id",), ns) + return ns["_shared_embedding_id"] + + +def test_uuid_and_composite_with_same_tenant_embd_id_are_compatible(): + check = _load_shared_embedding_id({TENANT_EMBD_ID: COMPOSITE}) + kbs = [ + SimpleNamespace(embd_id=TENANT_EMBD_ID, tenant_embd_id=TENANT_EMBD_ID), + SimpleNamespace(embd_id=COMPOSITE, tenant_embd_id=TENANT_EMBD_ID), + ] + embd_id = check(kbs, "Knowledge bases use different embedding models.") + assert embd_id in {TENANT_EMBD_ID, COMPOSITE} + + +def test_uuid_and_composite_return_a_stored_model_id_not_a_base_name(): + check = _load_shared_embedding_id({TENANT_EMBD_ID: COMPOSITE}) + kbs = [ + SimpleNamespace(embd_id=TENANT_EMBD_ID, tenant_embd_id=TENANT_EMBD_ID), + SimpleNamespace(embd_id=COMPOSITE, tenant_embd_id=TENANT_EMBD_ID), + ] + embd_id = check(kbs, "Knowledge bases use different embedding models.") + assert embd_id != "bge-m3:latest" + assert "@" in embd_id or embd_id == TENANT_EMBD_ID + + +def test_different_embedding_models_still_fail(): + check = _load_shared_embedding_id( + { + TENANT_EMBD_ID: COMPOSITE, + "b346fecb098e4305b58926f1bae6bbc9": OTHER_COMPOSITE, + } + ) + kbs = [ + SimpleNamespace(embd_id=TENANT_EMBD_ID, tenant_embd_id=TENANT_EMBD_ID), + SimpleNamespace(embd_id="b346fecb098e4305b58926f1bae6bbc9", tenant_embd_id="b346fecb098e4305b58926f1bae6bbc9"), + ] + with pytest.raises(Exception, match="Knowledge bases use different embedding models"): + check(kbs, "Knowledge bases use different embedding models.") + + +def test_unresolved_uuid_does_not_match_a_different_composite(): + check = _load_shared_embedding_id({}) + kbs = [ + SimpleNamespace(embd_id=TENANT_EMBD_ID, tenant_embd_id=TENANT_EMBD_ID), + SimpleNamespace(embd_id=COMPOSITE, tenant_embd_id=None), + ] + with pytest.raises(Exception, match="Knowledge bases use different embedding models"): + check(kbs, "Knowledge bases use different embedding models.") + + +def test_empty_names_do_not_make_different_models_compatible(): + check = _load_shared_embedding_id({}) + kbs = [ + SimpleNamespace(embd_id=COMPOSITE, tenant_embd_id=None), + SimpleNamespace(embd_id="", tenant_embd_id=None), + ] + with pytest.raises(Exception, match="Knowledge bases use different embedding models"): + check(kbs, "Knowledge bases use different embedding models.") + + +def test_memory_uuid_and_composite_with_same_tenant_embd_id_are_compatible(): + check = _load_shared_embedding_id({TENANT_EMBD_ID: COMPOSITE}) + memories = [ + SimpleNamespace(embd_id=TENANT_EMBD_ID, tenant_embd_id=TENANT_EMBD_ID), + SimpleNamespace(embd_id=COMPOSITE, tenant_embd_id=TENANT_EMBD_ID), + ] + assert check(memories, "Memory use different embedding models.") in {TENANT_EMBD_ID, COMPOSITE} + + +def test_memory_different_embedding_models_still_fail(): + check = _load_shared_embedding_id({}) + memories = [ + SimpleNamespace(embd_id=COMPOSITE, tenant_embd_id=None), + SimpleNamespace(embd_id=OTHER_COMPOSITE, tenant_embd_id=None), + ] + with pytest.raises(Exception, match="Memory use different embedding models"): + check(memories, "Memory use different embedding models.") From 3e30a476233ff8d013860500cd24724b586a7a67 Mon Sep 17 00:00:00 2001 From: Jin Hai Date: Thu, 10 Sep 2026 22:57:18 +0800 Subject: [PATCH 088/568] Go: add integration test (#19485) ``` $ go test -v ./test/api/... InitServerTestConfig start InitServerTestConfig init successfully TearUp === RUN TestCreateDataset dataset_api_test.go:12: Skip TestCreateDataset dataset_api_test.go:17: TestCreateDataset 1 --- PASS: TestCreateDataset (0.00s) === RUN TestCreateUser user_api_test.go:14: TestCreateUser --- PASS: TestCreateUser (0.00s) PASS TearDown ``` --------- Signed-off-by: Jin Hai --- go.mod | 3 + test/api/config.go | 322 +++++++++++++++++++ test/api/dataset_api_test.go | 581 +++++++++++++++++++++++++++++++++++ test/api/main_test.go | 47 +++ test/api/user_api_test.go | 30 ++ 5 files changed, 983 insertions(+) create mode 100644 test/api/config.go create mode 100644 test/api/dataset_api_test.go create mode 100644 test/api/main_test.go create mode 100644 test/api/user_api_test.go diff --git a/go.mod b/go.mod index 96d38884c7d..8044548db1f 100644 --- a/go.mod +++ b/go.mod @@ -58,6 +58,7 @@ require ( github.com/signintech/gopdf v0.36.1 github.com/siongui/gojianfan v0.0.0-20210926212422-2f175ac615de github.com/spf13/viper v1.18.2 + github.com/stretchr/testify v1.11.1 github.com/ucloud/ucloud-sandbox-sdk-go v0.0.0-20260807065450-08464aef9ed5 github.com/xuri/excelize/v2 v2.11.0 github.com/yfedoseev/office_oxide/go v0.1.9 @@ -89,11 +90,13 @@ require ( github.com/PuerkitoBio/goquery v1.9.2 // indirect github.com/andybalholm/cascadia v1.3.2 // indirect github.com/apache/arrow/go/v15 v15.0.2 // indirect + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/emersion/go-sasl v0.0.0-20241020182733-b788ff22d5a6 // indirect github.com/goccy/go-json v0.10.5 // indirect github.com/google/flatbuffers v23.5.26+incompatible // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/pierrec/lz4/v4 v4.1.18 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect golang.org/x/mod v0.38.0 // indirect golang.org/x/telemetry v0.0.0-20260708182218-49f421fb7959 // indirect golang.org/x/tools v0.48.0 // indirect diff --git a/test/api/config.go b/test/api/config.go new file mode 100644 index 00000000000..385704f486e --- /dev/null +++ b/test/api/config.go @@ -0,0 +1,322 @@ +//go:build integration + +// +// 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. +// + +package api + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strconv" + "strings" +) + +var TestConfig *ServerTestConfig + +func init() { + TestConfig = InitServerTestConfig() + if TestConfig == nil { + panic("TestConfig is nil") + } +} + +type ServerTestConfig struct { + Priority int + HostAddress string + APIVersion string + ZhipuAPIKey string + SiliconFlowAPIKey string + Email string + Password string + AuthToken string + APIKey string + + InvalidAPIKey string + InvalidID string + DatasetNameLimit int + DocumentNameLimit int + ChatAssistantNameLimit int + SessionWithChatNameLimit int + + DefaultDataSetParser map[string]interface{} +} + +func InitServerTestConfig() *ServerTestConfig { + //fmt.Fprintf(os.Stderr, "InitServerTestConfig start\n") + var priority int + var err error + testPriorityStr := os.Getenv("TEST_PRIORITY") + if testPriorityStr == "" { + priority = 0 + } else { + priority, err = strconv.Atoi(testPriorityStr) + if err != nil { + fmt.Fprintf(os.Stderr, "TEST_PRIORITY is not a valid integer: %v\n", err) + return nil + } + } + + hostAddress := os.Getenv("HOST_ADDRESS") + if hostAddress == "" { + hostAddress = "http://127.0.0.1:9384" + } + + zhipuAPIKey := os.Getenv("ZHIPU_AI_API_KEY") + if zhipuAPIKey == "" { + fmt.Fprintf(os.Stderr, "ZHIPU_AI_API_KEY is not set\n") + return nil + } + + siliconFlowAPIKey := os.Getenv("SILICONFLOW_API_KEY") + if siliconFlowAPIKey == "" { + fmt.Fprintf(os.Stderr, "SILICONFLOW_API_KEY is not set\n") + return nil + } + + email := os.Getenv("RAGFLOW_TEST_EMAIL") + if email == "" { + email = "qa@infiniflow.org" + } + + password := os.Getenv("RAGFLOW_TEST_PASSWORD") + if password == "" { + password = "ctAseGvejiaSWWZ88T/m4FQVOpQyUvP+x7sXtdv3feqZACiQleuewkUi35E16wSd5C5QcnkkcV9cYc8TKPTRZlxappDuirxghxoOvFcJxFU4ixLsD\nfN33jCHRoDUW81IH9zjij/vaw8IbVyb6vuwg6MX6inOEBRRzVbRYxXOu1wkWY6SsI8X70oF9aeLFp/PzQpjoe/YbSqpTq8qqrmHzn9vO+yvyYyvmDsphXe\nX8f7fp9c7vUsfOCkM+gHY3PadG+QHa7KI7mzTKgUTZImK6BZtfRBATDTthEUbbaTewY4H0MnWiCeeDhcbeQao6cFy1To8pE3RpmxnGnS8BsBn8w==" + } + + invalidID := "00000000000000000000000000000000" + + defaultParserConfig := map[string]interface{}{ + "layout_recognize": "DeepDOC", + "chunk_token_num": 512, + "delimiter": "\n", + "auto_keywords": 0, + "auto_questions": 0, + "html4excel": false, + "image_context_size": 0, + "table_context_size": 0, + "topn_tags": 3, + "llm_id": "glm-4-flash@CI@ZHIPU-AI", + "parent_child": map[string]interface{}{ + "use_parent_child": false, + "children_delimiter": "\n", + }, + "children_delimiter": "", + } + + serverTestConfig := ServerTestConfig{ + Priority: priority, + HostAddress: hostAddress, + APIVersion: "v1", + ZhipuAPIKey: zhipuAPIKey, + SiliconFlowAPIKey: siliconFlowAPIKey, + Email: email, + Password: password, + InvalidAPIKey: "invalidapikey", + InvalidID: invalidID, + DatasetNameLimit: 100, + DocumentNameLimit: 100, + ChatAssistantNameLimit: 100, + SessionWithChatNameLimit: 100, + DefaultDataSetParser: defaultParserConfig, + } + + //fmt.Fprintf(os.Stderr, "InitServerTestConfig init successfully\n") + return &serverTestConfig +} + +func (c *ServerTestConfig) apiBase() string { + return fmt.Sprintf("%s/api/%s", c.HostAddress, c.APIVersion) +} + +func (c *ServerTestConfig) buildHeaders(extra map[string]string) http.Header { + h := make(http.Header) + h.Set("Content-Type", "application/json") + for k, v := range extra { + h.Set(k, v) + } + if c.AuthToken != "" && h.Get("Authorization") == "" { + h.Set("Authorization", "Bearer "+c.AuthToken) + } else { + if c.APIKey != "" && h.Get("Authorization") == "" { + h.Set("Authorization", "Bearer "+c.APIKey) + } + } + + return h +} + +func (c *ServerTestConfig) RequestJSON(method, path string, body, params map[string]interface{}, extraHeaders map[string]string) (*http.Response, error) { + var bodyReader io.Reader + if body != nil { + b, err := json.Marshal(body) + if err != nil { + return nil, err + } + bodyReader = bytes.NewReader(b) + } + + u, err := url.Parse(c.apiBase() + "/" + strings.TrimLeft(path, "/")) + if err != nil { + return nil, err + } + q := u.Query() + for k, v := range params { + q.Set(k, fmt.Sprint(v)) + } + u.RawQuery = q.Encode() + + req, err := http.NewRequest(method, u.String(), bodyReader) + if err != nil { + return nil, err + } + req.Header = c.buildHeaders(extraHeaders) + return http.DefaultClient.Do(req) +} + +func (c *ServerTestConfig) GetJSON(path string, params map[string]interface{}, extraHeaders map[string]string) (*http.Response, error) { + return c.RequestJSON(http.MethodGet, path, nil, params, extraHeaders) +} + +func (c *ServerTestConfig) PostJSON(path string, body map[string]interface{}, extraHeaders map[string]string) (*http.Response, error) { + return c.RequestJSON(http.MethodPost, path, body, nil, extraHeaders) +} + +func (c *ServerTestConfig) DeleteJSON(path string, body map[string]interface{}, extraHeaders map[string]string) (*http.Response, error) { + return c.RequestJSON(http.MethodDelete, path, body, nil, extraHeaders) +} + +func (c *ServerTestConfig) PutJSON(path string, body map[string]interface{}, extraHeaders map[string]string) (*http.Response, error) { + return c.RequestJSON(http.MethodPut, path, body, nil, extraHeaders) +} + +func (c *ServerTestConfig) PatchJSON(path string, body map[string]interface{}, extraHeaders map[string]string) (*http.Response, error) { + return c.RequestJSON(http.MethodPatch, path, body, nil, extraHeaders) +} + +func (c *ServerTestConfig) decodeJSONBody(body io.Reader) (map[string]interface{}, error) { + b, err := io.ReadAll(body) + if err != nil { + return nil, err + } + var payload map[string]interface{} + if err = json.Unmarshal(b, &payload); err != nil { + return nil, err + } + return payload, nil +} + +func (c *ServerTestConfig) Login() error { + // Register (ignore already registered error) + registerResp, err := c.PostJSON("/users", map[string]interface{}{ + "email": c.Email, + "nickname": "qa", + "password": c.Password, + }, nil) + if err != nil { + return fmt.Errorf("register request failed: %w", err) + } + registerPayload, err := c.decodeJSONBody(registerResp.Body) + registerResp.Body.Close() + if err != nil { + return fmt.Errorf("failed to decode register response: %w", err) + } + if registerResp.StatusCode != http.StatusOK { + return fmt.Errorf("register failed: status=%d, payload=%v", registerResp.StatusCode, registerPayload) + } + registerCode, _ := registerPayload["code"].(float64) + registerMessage, _ := registerPayload["message"].(string) + if int(registerCode) != 0 && !strings.Contains(registerMessage, "has already registered") { + return fmt.Errorf("register failed: code=%v, message=%s", registerPayload["code"], registerMessage) + } + + // Login + loginResp, err := c.PostJSON("/auth/login", map[string]interface{}{ + "email": c.Email, + "password": c.Password, + }, nil) + if err != nil { + return fmt.Errorf("login request failed: %w", err) + } + authToken := loginResp.Header.Get("Authorization") + loginResp.Body.Close() + if authToken == "" { + return fmt.Errorf("login response missing Authorization header") + } + + c.AuthToken = authToken + + // Get system token + tokenResp, err := c.PostJSON("/system/tokens", nil, map[string]string{ + "Authorization": authToken, + }) + if err != nil { + return fmt.Errorf("system token request failed: %w", err) + } + tokenPayload, err := c.decodeJSONBody(tokenResp.Body) + tokenResp.Body.Close() + if err != nil { + return fmt.Errorf("failed to decode token response: %w", err) + } + if tokenResp.StatusCode != http.StatusOK { + return fmt.Errorf("system token failed: status=%d, payload=%v", tokenResp.StatusCode, tokenPayload) + } + tokenData, ok := tokenPayload["data"].(map[string]interface{}) + if !ok { + return fmt.Errorf("system token response data is not an object: %v", tokenPayload) + } + apiKey, ok := tokenData["token"].(string) + if !ok || apiKey == "" { + return fmt.Errorf("system token response data.token is not a valid string: %v", tokenData) + } + + c.APIKey = apiKey + return nil +} + +func (c *ServerTestConfig) Logout() error { + resp, err := c.PostJSON("/auth/logout", nil, nil) + if err != nil { + return err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return fmt.Errorf("failed to read logout response: %w", err) + } + var payload map[string]interface{} + if err = json.Unmarshal(body, &payload); err != nil { + return fmt.Errorf("failed to decode logout response: %w", err) + } + + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("logout failed: status=%d, payload=%v", resp.StatusCode, payload) + } + code, _ := payload["code"].(float64) + if int(code) != 0 { + return fmt.Errorf("logout failed: code=%v, message=%v", payload["code"], payload["message"]) + } + + c.APIKey = "" + c.AuthToken = "" + return nil +} diff --git a/test/api/dataset_api_test.go b/test/api/dataset_api_test.go new file mode 100644 index 00000000000..c1918790736 --- /dev/null +++ b/test/api/dataset_api_test.go @@ -0,0 +1,581 @@ +//go:build integration + +// +// 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. +// + +package api + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "fmt" + "image" + "image/color" + "image/draw" + "image/png" + "io" + "net/http" + "strings" + "testing" +) + +func decodeResponseJSON(resp *http.Response) (map[string]interface{}, error) { + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + var payload map[string]interface{} + if err = json.Unmarshal(body, &payload); err != nil { + return nil, err + } + return payload, nil +} + +func requireStatusCode(t *testing.T, resp *http.Response, expected int) map[string]interface{} { + t.Helper() + if resp.StatusCode != expected { + t.Fatalf("expected status code %d, got %d", expected, resp.StatusCode) + } + payload, err := decodeResponseJSON(resp) + if err != nil { + t.Fatalf("failed to decode response: %v", err) + } + return payload +} + +func requireCodeZero(t *testing.T, payload map[string]interface{}) { + t.Helper() + code, ok := payload["code"].(float64) + if !ok || int(code) != 0 { + t.Fatalf("expected code 0, got %v, payload: %v", payload["code"], payload) + } +} + +func clearDatasets(t *testing.T) { + t.Helper() + resp, err := TestConfig.DeleteJSON("/datasets", map[string]interface{}{"ids": nil, "delete_all": true}, nil) + if err != nil { + t.Fatalf("clear datasets request failed: %v", err) + } + payload := requireStatusCode(t, resp, http.StatusOK) + code, _ := payload["code"].(float64) + if int(code) != 0 && int(code) != 102 { + t.Fatalf("clear datasets failed: code=%v, payload=%v", payload["code"], payload) + } +} + +func jsonDeepEqual(a, b interface{}) bool { + switch av := a.(type) { + case float64: + switch bv := b.(type) { + case float64: + return av == bv + case int: + return av == float64(bv) + case int64: + return av == float64(bv) + default: + return false + } + case int: + return jsonDeepEqual(float64(av), b) + case int64: + return jsonDeepEqual(float64(av), b) + case string, bool, nil: + return a == b + case []interface{}: + bv, ok := b.([]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for i := range av { + if !jsonDeepEqual(av[i], bv[i]) { + return false + } + } + return true + case map[string]interface{}: + bv, ok := b.(map[string]interface{}) + if !ok || len(av) != len(bv) { + return false + } + for k, v := range av { + bvVal, ok := bv[k] + if !ok || !jsonDeepEqual(v, bvVal) { + return false + } + } + return true + default: + return a == b + } +} + +func TestDatasetCRUDCycle(t *testing.T) { + clearDatasets(t) + // Create + createResp, err := TestConfig.PostJSON("/datasets", map[string]interface{}{"name": "restful_dataset_crud"}, nil) + if err != nil { + t.Fatalf("create dataset request failed: %v", err) + } + createPayload := requireStatusCode(t, createResp, http.StatusOK) + requireCodeZero(t, createPayload) + createData, ok := createPayload["data"].(map[string]interface{}) + if !ok { + t.Fatalf("create response data is not an object: %v", createPayload) + } + datasetID, ok := createData["id"].(string) + if !ok || datasetID == "" { + t.Fatalf("create response data.id is not a valid string: %v", createData) + } + + // Get by id + getResp, err := TestConfig.GetJSON(fmt.Sprintf("/datasets/%s", datasetID), nil, nil) + if err != nil { + t.Fatalf("get dataset request failed: %v", err) + } + getPayload := requireStatusCode(t, getResp, http.StatusOK) + requireCodeZero(t, getPayload) + getData, ok := getPayload["data"].(map[string]interface{}) + if !ok || getData["id"] != datasetID { + t.Fatalf("get response data.id mismatch: %v", getPayload) + } + + // Update + updateResp, err := TestConfig.PutJSON(fmt.Sprintf("/datasets/%s", datasetID), map[string]interface{}{"name": "restful_dataset_crud_updated"}, nil) + if err != nil { + t.Fatalf("update dataset request failed: %v", err) + } + updatePayload := requireStatusCode(t, updateResp, http.StatusOK) + requireCodeZero(t, updatePayload) + updateData, ok := updatePayload["data"].(map[string]interface{}) + if !ok || updateData["name"] != "restful_dataset_crud_updated" { + t.Fatalf("update response data.name mismatch: %v", updatePayload) + } + + // List with id filter + listResp, err := TestConfig.GetJSON("/datasets", map[string]interface{}{"id": datasetID}, nil) + if err != nil { + t.Fatalf("list dataset request failed: %v", err) + } + listPayload := requireStatusCode(t, listResp, http.StatusOK) + requireCodeZero(t, listPayload) + listData, ok := listPayload["data"].([]interface{}) + if !ok || len(listData) != 1 { + t.Fatalf("expected 1 dataset in list, got %v", listPayload) + } + firstItem, ok := listData[0].(map[string]interface{}) + if !ok || firstItem["id"] != datasetID { + t.Fatalf("list response data[0].id mismatch: %v", listPayload) + } + + // Delete + deleteResp, err := TestConfig.DeleteJSON("/datasets", map[string]interface{}{"ids": []interface{}{datasetID}}, nil) + if err != nil { + t.Fatalf("delete dataset request failed: %v", err) + } + deletePayload := requireStatusCode(t, deleteResp, http.StatusOK) + requireCodeZero(t, deletePayload) + + // List after delete + listAfterResp, err := TestConfig.GetJSON("/datasets", nil, nil) + if err != nil { + t.Fatalf("list after delete request failed: %v", err) + } + listAfterPayload := requireStatusCode(t, listAfterResp, http.StatusOK) + requireCodeZero(t, listAfterPayload) + listAfterData, ok := listAfterPayload["data"].([]interface{}) + if !ok { + t.Fatalf("list after delete data is not an array: %v", listAfterPayload) + } + for _, item := range listAfterData { + dataset, ok := item.(map[string]interface{}) + if !ok { + continue + } + if dataset["id"] == datasetID { + t.Fatalf("deleted dataset %s still present in list: %v", datasetID, listAfterPayload) + } + } +} + +func TestDatasetUpdateNameAndCaseInsensitiveContract(t *testing.T) { + clearDatasets(t) + + // Create first dataset + firstResp, err := TestConfig.PostJSON("/datasets", map[string]interface{}{"name": "dataset_update_name_source"}, nil) + if err != nil { + t.Fatalf("create first dataset request failed: %v", err) + } + firstPayload := requireStatusCode(t, firstResp, http.StatusOK) + requireCodeZero(t, firstPayload) + firstData, ok := firstPayload["data"].(map[string]interface{}) + if !ok { + t.Fatalf("first response data is not an object: %v", firstPayload) + } + firstDatasetID, ok := firstData["id"].(string) + if !ok || firstDatasetID == "" { + t.Fatalf("first dataset id is invalid: %v", firstData) + } + + // Create second dataset + secondResp, err := TestConfig.PostJSON("/datasets", map[string]interface{}{"name": "dataset_update_name_target"}, nil) + if err != nil { + t.Fatalf("create second dataset request failed: %v", err) + } + secondPayload := requireStatusCode(t, secondResp, http.StatusOK) + requireCodeZero(t, secondPayload) + secondData, ok := secondPayload["data"].(map[string]interface{}) + if !ok { + t.Fatalf("second response data is not an object: %v", secondPayload) + } + secondDatasetName, ok := secondData["name"].(string) + if !ok || secondDatasetName == "" { + t.Fatalf("second dataset name is invalid: %v", secondData) + } + + // Rename first dataset + renameResp, err := TestConfig.PutJSON(fmt.Sprintf("/datasets/%s", firstDatasetID), map[string]interface{}{"name": "dataset_update_name_renamed"}, nil) + if err != nil { + t.Fatalf("rename dataset request failed: %v", err) + } + renamePayload := requireStatusCode(t, renameResp, http.StatusOK) + requireCodeZero(t, renamePayload) + renameData, ok := renamePayload["data"].(map[string]interface{}) + if !ok || renameData["name"] != "dataset_update_name_renamed" { + t.Fatalf("rename response data.name mismatch: %v", renamePayload) + } + + // List with id filter + listResp, err := TestConfig.GetJSON("/datasets", map[string]interface{}{"id": firstDatasetID}, nil) + if err != nil { + t.Fatalf("list dataset request failed: %v", err) + } + listPayload := requireStatusCode(t, listResp, http.StatusOK) + requireCodeZero(t, listPayload) + listData, ok := listPayload["data"].([]interface{}) + if !ok || len(listData) != 1 { + t.Fatalf("expected 1 dataset in list, got %v", listPayload) + } + firstItem, ok := listData[0].(map[string]interface{}) + if !ok || firstItem["name"] != "dataset_update_name_renamed" { + t.Fatalf("list response data[0].name mismatch: %v", listPayload) + } + + // Try duplicate name (case-insensitive) + duplicateResp, err := TestConfig.PutJSON(fmt.Sprintf("/datasets/%s", firstDatasetID), map[string]interface{}{"name": strings.ToUpper(secondDatasetName)}, nil) + if err != nil { + t.Fatalf("duplicate case rename request failed: %v", err) + } + duplicatePayload := requireStatusCode(t, duplicateResp, http.StatusOK) + duplicateCode, ok := duplicatePayload["code"].(float64) + if !ok || int(duplicateCode) != 102 { + t.Fatalf("expected code 102 for duplicate case rename, got %v, payload: %v", duplicatePayload["code"], duplicatePayload) + } + duplicateMessage, _ := duplicatePayload["message"].(string) + if !strings.Contains(duplicateMessage, "already exists") { + t.Fatalf("expected message to contain 'already exists', got %q, payload: %v", duplicateMessage, duplicatePayload) + } +} + +func encodeAvatar() (string, error) { + img := image.NewRGBA(image.Rectangle{ + Min: image.Point{X: 0, Y: 0}, + Max: image.Point{X: 100, Y: 100}, + }) + draw.Draw(img, img.Bounds(), &image.Uniform{color.RGBA{R: 0, G: 0, B: 255, A: 255}}, image.Point{}, draw.Src) + var buf bytes.Buffer + if err := png.Encode(&buf, img); err != nil { + return "", err + } + encoded := base64.StdEncoding.EncodeToString(buf.Bytes()) + return fmt.Sprintf("data:image/png;base64,%s", encoded), nil +} + +func TestDatasetUpdateLanguageConnectorsAvatarAndDescriptionContract(t *testing.T) { + clearDatasets(t) + + createResp, err := TestConfig.PostJSON("/datasets", map[string]interface{}{"name": "dataset_update_lang_connectors"}, nil) + if err != nil { + t.Fatalf("create dataset request failed: %v", err) + } + createPayload := requireStatusCode(t, createResp, http.StatusOK) + requireCodeZero(t, createPayload) + createData, ok := createPayload["data"].(map[string]interface{}) + if !ok { + t.Fatalf("create response data is not an object: %v", createPayload) + } + datasetID, ok := createData["id"].(string) + if !ok || datasetID == "" { + t.Fatalf("dataset id is invalid: %v", createData) + } + + avatarValue, err := encodeAvatar() + if err != nil { + t.Fatalf("failed to encode avatar: %v", err) + } + + updateResp, err := TestConfig.PutJSON(fmt.Sprintf("/datasets/%s", datasetID), map[string]interface{}{ + "name": "dataset_update_lang_connectors", + "description": "", + "parser_id": "naive", + "parse_type": 1, + "language": "English", + "connectors": []interface{}{}, + "avatar": avatarValue, + }, nil) + if err != nil { + t.Fatalf("update dataset request failed: %v", err) + } + updatePayload := requireStatusCode(t, updateResp, http.StatusOK) + requireCodeZero(t, updatePayload) + updateData, ok := updatePayload["data"].(map[string]interface{}) + if !ok { + t.Fatalf("update response data is not an object: %v", updatePayload) + } + if updateData["language"] != "English" { + t.Fatalf("language mismatch: expected English, got %v", updatePayload) + } + connectors, ok := updateData["connectors"].([]interface{}) + if !ok { + t.Fatalf("connectors is not an array: %v", updatePayload) + } + if len(connectors) != 0 { + t.Fatalf("connectors should be empty: %v", updatePayload) + } + if updateData["avatar"] != avatarValue { + t.Fatalf("avatar mismatch: %v", updatePayload) + } + + descriptionResp, err := TestConfig.PutJSON(fmt.Sprintf("/datasets/%s", datasetID), map[string]interface{}{"description": "description"}, nil) + if err != nil { + t.Fatalf("update description request failed: %v", err) + } + descriptionPayload := requireStatusCode(t, descriptionResp, http.StatusOK) + requireCodeZero(t, descriptionPayload) + descriptionData, ok := descriptionPayload["data"].(map[string]interface{}) + if !ok || descriptionData["description"] != "description" { + t.Fatalf("description mismatch: %v", descriptionPayload) + } +} + +func TestDatasetUpdateParserConfigValidMatrixContract(t *testing.T) { + clearDatasets(t) + t.Skip("Go validation or response contract does not match the established API contract") + + cases := []struct { + name string + parserConfig map[string]interface{} + }{ + {name: "auto_keywords_min", parserConfig: map[string]interface{}{"auto_keywords": 0}}, + {name: "auto_keywords_mid", parserConfig: map[string]interface{}{"auto_keywords": 16}}, + {name: "auto_keywords_max", parserConfig: map[string]interface{}{"auto_keywords": 32}}, + {name: "auto_questions_min", parserConfig: map[string]interface{}{"auto_questions": 0}}, + {name: "auto_questions_mid", parserConfig: map[string]interface{}{"auto_questions": 5}}, + {name: "auto_questions_max", parserConfig: map[string]interface{}{"auto_questions": 10}}, + {name: "chunk_token_num_min", parserConfig: map[string]interface{}{"chunk_token_num": 1}}, + {name: "chunk_token_num_mid", parserConfig: map[string]interface{}{"chunk_token_num": 1024}}, + {name: "chunk_token_num_max", parserConfig: map[string]interface{}{"chunk_token_num": 2048}}, + {name: "delimiter", parserConfig: map[string]interface{}{"delimiter": "\n"}}, + {name: "delimiter_space", parserConfig: map[string]interface{}{"delimiter": " "}}, + {name: "html4excel_true", parserConfig: map[string]interface{}{"html4excel": true}}, + {name: "html4excel_false", parserConfig: map[string]interface{}{"html4excel": false}}, + {name: "layout_recognize_DeepDOC", parserConfig: map[string]interface{}{"layout_recognize": "DeepDOC"}}, + {name: "layout_recognize_navie", parserConfig: map[string]interface{}{"layout_recognize": "Plain Text"}}, + {name: "tag_kb_ids", parserConfig: map[string]interface{}{"tag_kb_ids": []interface{}{"1", "2"}}}, + {name: "topn_tags_min", parserConfig: map[string]interface{}{"topn_tags": 1}}, + {name: "topn_tags_mid", parserConfig: map[string]interface{}{"topn_tags": 5}}, + {name: "topn_tags_max", parserConfig: map[string]interface{}{"topn_tags": 10}}, + {name: "filename_embd_weight_min", parserConfig: map[string]interface{}{"filename_embd_weight": 0.1}}, + {name: "filename_embd_weight_mid", parserConfig: map[string]interface{}{"filename_embd_weight": 0.5}}, + {name: "filename_embd_weight_max", parserConfig: map[string]interface{}{"filename_embd_weight": 1.0}}, + {name: "task_page_size_min", parserConfig: map[string]interface{}{"task_page_size": 1}}, + {name: "task_page_size_None", parserConfig: map[string]interface{}{"task_page_size": nil}}, + {name: "pages", parserConfig: map[string]interface{}{"pages": []interface{}{[]interface{}{1, 100}}}}, + {name: "pages_none", parserConfig: map[string]interface{}{"pages": nil}}, + {name: "graphrag_true", parserConfig: map[string]interface{}{"graphrag": map[string]interface{}{"use_graphrag": true}}}, + {name: "graphrag_false", parserConfig: map[string]interface{}{"graphrag": map[string]interface{}{"use_graphrag": false}}}, + {name: "graphrag_entity_types", parserConfig: map[string]interface{}{"graphrag": map[string]interface{}{"entity_types": []interface{}{"age", "sex", "height", "weight"}}}}, + {name: "graphrag_method_general", parserConfig: map[string]interface{}{"graphrag": map[string]interface{}{"method": "general"}}}, + {name: "graphrag_method_light", parserConfig: map[string]interface{}{"graphrag": map[string]interface{}{"method": "light"}}}, + {name: "graphrag_community_true", parserConfig: map[string]interface{}{"graphrag": map[string]interface{}{"community": true}}}, + {name: "graphrag_community_false", parserConfig: map[string]interface{}{"graphrag": map[string]interface{}{"community": false}}}, + {name: "graphrag_resolution_true", parserConfig: map[string]interface{}{"graphrag": map[string]interface{}{"resolution": true}}}, + {name: "graphrag_resolution_false", parserConfig: map[string]interface{}{"graphrag": map[string]interface{}{"resolution": false}}}, + {name: "raptor_true", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"use_raptor": true}}}, + {name: "raptor_false", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"use_raptor": false}}}, + {name: "raptor_prompt", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"prompt": "Who are you?"}}}, + {name: "raptor_max_token_min", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"max_token": 512}}}, + {name: "raptor_max_token_mid", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"max_token": 1024}}}, + {name: "raptor_max_token_max", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"max_token": 2048}}}, + {name: "raptor_clustering_threshold_min", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"clustering_threshold": 0.0}}}, + {name: "raptor_clustering_threshold_mid", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"clustering_threshold": 0.5}}}, + {name: "raptor_clustering_threshold_max", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"clustering_threshold": 1.0}}}, + {name: "raptor_max_cluster_min", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"max_cluster": 1}}}, + {name: "raptor_max_cluster_mid", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"max_cluster": 512}}}, + {name: "raptor_max_cluster_max", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"max_cluster": 1024}}}, + {name: "raptor_random_seed_min", parserConfig: map[string]interface{}{"raptor": map[string]interface{}{"random_seed": 0}}}, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + createResp, err := TestConfig.PostJSON("/datasets", map[string]interface{}{"name": fmt.Sprintf("dataset_update_parser_%s", tc.name)}, nil) + if err != nil { + t.Fatalf("create dataset request failed: %v", err) + } + createPayload := requireStatusCode(t, createResp, http.StatusOK) + requireCodeZero(t, createPayload) + createData, ok := createPayload["data"].(map[string]interface{}) + if !ok { + t.Fatalf("create response data is not an object: %v", createPayload) + } + datasetID, ok := createData["id"].(string) + if !ok || datasetID == "" { + t.Fatalf("dataset id is invalid: %v", createData) + } + + updateResp, err := TestConfig.PutJSON(fmt.Sprintf("/datasets/%s", datasetID), map[string]interface{}{"parser_config": tc.parserConfig}, nil) + if err != nil { + t.Fatalf("update parser_config request failed: %v", err) + } + updatePayload := requireStatusCode(t, updateResp, http.StatusOK) + requireCodeZero(t, updatePayload) + + listResp, err := TestConfig.GetJSON("/datasets", map[string]interface{}{"id": datasetID}, nil) + if err != nil { + t.Fatalf("list dataset request failed: %v", err) + } + listPayload := requireStatusCode(t, listResp, http.StatusOK) + requireCodeZero(t, listPayload) + listData, ok := listPayload["data"].([]interface{}) + if !ok || len(listData) != 1 { + t.Fatalf("expected 1 dataset in list, got %v", listPayload) + } + firstItem, ok := listData[0].(map[string]interface{}) + if !ok { + t.Fatalf("list data[0] is not an object: %v", listPayload) + } + actualParserConfig, ok := firstItem["parser_config"].(map[string]interface{}) + if !ok { + t.Fatalf("parser_config is not an object: %v", firstItem) + } + + for key, expectedValue := range tc.parserConfig { + if key == "graphrag" || key == "raptor" { + if _, exists := actualParserConfig[key]; exists { + t.Fatalf("expected %s not in parser_config, but got %v", key, actualParserConfig) + } + continue + } + actualValue, ok := actualParserConfig[key] + if !ok { + t.Fatalf("parser_config missing key %s: %v", key, actualParserConfig) + } + if !jsonDeepEqual(actualValue, expectedValue) { + t.Fatalf("parser_config.%s mismatch: expected %v, got %v", key, expectedValue, actualValue) + } + } + }) + } +} + +func TestDatasetUpdateParserConfigWithChunkMethodChangeContract(t *testing.T) { + clearDatasets(t) + + cases := []struct { + name string + updatePayload map[string]interface{} + }{ + { + name: "parser_config_empty", + updatePayload: map[string]interface{}{ + "parser_id": "qa", + "parse_type": 1, + "parser_config": map[string]interface{}{}, + }, + }, + { + name: "parser_config_none", + updatePayload: map[string]interface{}{ + "parser_id": "qa", + "parse_type": 1, + "parser_config": nil, + }, + }, + { + name: "parser_config_unset", + updatePayload: map[string]interface{}{ + "parser_id": "qa", + "parse_type": 1, + }, + }, + } + + for _, tc := range cases { + tc := tc + t.Run(tc.name, func(t *testing.T) { + createResp, err := TestConfig.PostJSON("/datasets", map[string]interface{}{"name": fmt.Sprintf("dataset_update_%s", tc.name)}, nil) + if err != nil { + t.Fatalf("create dataset request failed: %v", err) + } + createPayload := requireStatusCode(t, createResp, http.StatusOK) + requireCodeZero(t, createPayload) + createData, ok := createPayload["data"].(map[string]interface{}) + if !ok { + t.Fatalf("create response data is not an object: %v", createPayload) + } + datasetID, ok := createData["id"].(string) + if !ok || datasetID == "" { + t.Fatalf("dataset id is invalid: %v", createData) + } + + updateResp, err := TestConfig.PutJSON(fmt.Sprintf("/datasets/%s", datasetID), tc.updatePayload, nil) + if err != nil { + t.Fatalf("update dataset request failed: %v", err) + } + updatePayload := requireStatusCode(t, updateResp, http.StatusOK) + requireCodeZero(t, updatePayload) + + listResp, err := TestConfig.GetJSON("/datasets", map[string]interface{}{"id": datasetID}, nil) + if err != nil { + t.Fatalf("list dataset request failed: %v", err) + } + listPayload := requireStatusCode(t, listResp, http.StatusOK) + requireCodeZero(t, listPayload) + listData, ok := listPayload["data"].([]interface{}) + if !ok || len(listData) != 1 { + t.Fatalf("expected 1 dataset in list, got %v", listPayload) + } + firstItem, ok := listData[0].(map[string]interface{}) + if !ok { + t.Fatalf("list data[0] is not an object: %v", listPayload) + } + actualParserConfig, ok := firstItem["parser_config"].(map[string]interface{}) + if !ok || len(actualParserConfig) == 0 { + t.Fatalf("parser_config should be non-empty map: %v", firstItem) + } + if _, exists := actualParserConfig["raptor"]; exists { + t.Fatalf("raptor should not be in parser_config: %v", actualParserConfig) + } + if _, exists := actualParserConfig["graphrag"]; exists { + t.Fatalf("graphrag should not be in parser_config: %v", actualParserConfig) + } + }) + } +} diff --git a/test/api/main_test.go b/test/api/main_test.go new file mode 100644 index 00000000000..9654df23a70 --- /dev/null +++ b/test/api/main_test.go @@ -0,0 +1,47 @@ +//go:build integration + +// +// 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. +// + +package api + +import ( + "fmt" + "os" + "testing" +) + +func TestMain(m *testing.M) { + fmt.Fprintln(os.Stderr, "Login") + + err := TestConfig.Login() + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to login: %v\n", err) + os.Exit(1) + } + + // Run the test cases + code := m.Run() + + err = TestConfig.Logout() + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to logout: %v\n", err) + os.Exit(1) + } + + fmt.Fprintln(os.Stderr, "Logout") + os.Exit(code) +} diff --git a/test/api/user_api_test.go b/test/api/user_api_test.go new file mode 100644 index 00000000000..e410a21a5f3 --- /dev/null +++ b/test/api/user_api_test.go @@ -0,0 +1,30 @@ +//go:build integration + +// +// 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. +// + +package api + +import ( + "testing" +) + +func TestCreateUser(t *testing.T) { + //resp, err := http.Post(baseURL+"/users", "application/json", body) + //assert.NoError(t, err) + //assert.Equal(t, 201, resp.StatusCode) + t.Log("TestCreateUser") +} From 1406980e8676dff431013889498a15dfe425d537 Mon Sep 17 00:00:00 2001 From: balibabu Date: Fri, 11 Sep 2026 09:47:32 +0800 Subject: [PATCH 089/568] Fix: Modify the text color of the TreeSelect component. (#19507) --- .../originui/select-with-search.tsx | 4 ++-- web/src/components/tree-select.tsx | 23 +++++++++++-------- .../setting/go/embedding-model-form-field.tsx | 4 +--- .../python/configuration/common-item.tsx | 8 ++----- 4 files changed, 19 insertions(+), 20 deletions(-) diff --git a/web/src/components/originui/select-with-search.tsx b/web/src/components/originui/select-with-search.tsx index f968fb7b07d..ad4f45790c2 100644 --- a/web/src/components/originui/select-with-search.tsx +++ b/web/src/components/originui/select-with-search.tsx @@ -256,7 +256,7 @@ export const SelectWithSearch = forwardRef< )} > {selectLabel || value ? ( - + {selectLabel || value} ) : ( @@ -295,7 +295,7 @@ export const SelectWithSearch = forwardRef< ? t('common.searchOrEnterToAdd') + '...' : t('common.search') + '...' } - className=" placeholder:text-text-disabled" + className="placeholder:text-text-disabled" value={searchValue} onValueChange={setSearchValue} onKeyDown={handleInputKeyDown} diff --git a/web/src/components/tree-select.tsx b/web/src/components/tree-select.tsx index 4e90c0f8613..558067cf2f5 100644 --- a/web/src/components/tree-select.tsx +++ b/web/src/components/tree-select.tsx @@ -4,7 +4,13 @@ import { PopoverTrigger, } from '@/components/ui/popover'; import { cn } from '@/lib/utils'; -import { ChevronDown, ChevronRight, Search, TriangleAlert, X } from 'lucide-react'; +import { + ChevronDown, + ChevronRight, + Search, + TriangleAlert, + X, +} from 'lucide-react'; import { forwardRef, useCallback, useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; @@ -96,8 +102,7 @@ export const TreeSelect = forwardRef( // A value matching no node means the referenced option is gone (e.g. // deleted) — unless `data` may simply not have loaded yet. - const missingValue = - value && !selectedNode && !loading ? value : undefined; + const missingValue = value && !selectedNode && !loading ? value : undefined; const isLeaf = useCallback( (node: TreeSelectNode) => !node.children?.length, @@ -253,7 +258,9 @@ export const TreeSelect = forwardRef( className, )} > - + {missingValue ? ( renderMissingValue ? ( renderMissingValue(missingValue) @@ -266,9 +273,7 @@ export const TreeSelect = forwardRef( ) : renderSelected ? ( renderSelected(selectedNode) ) : ( - selectedNode?.title || - placeholder || - t('common.pleaseSelect') + selectedNode?.title || placeholder || t('common.pleaseSelect') )}
@@ -290,10 +295,10 @@ export const TreeSelect = forwardRef( > {showSearch && (
- + setSearchTerm(e.target.value)} diff --git a/web/src/pages/dataset/setting/go/embedding-model-form-field.tsx b/web/src/pages/dataset/setting/go/embedding-model-form-field.tsx index e472c594e7d..3adfb45ef3e 100644 --- a/web/src/pages/dataset/setting/go/embedding-model-form-field.tsx +++ b/web/src/pages/dataset/setting/go/embedding-model-form-field.tsx @@ -104,9 +104,7 @@ export function EmbeddingModelItem({ > {t('embeddingModel')} -
+
{t('embeddingModel')} -
+
{label ?? t('llmModel')} -
+
Date: Fri, 11 Sep 2026 09:47:55 +0800 Subject: [PATCH 090/568] Upon entering a wiki, the top-right corner indicates that modifications have been made, even though no changes were actually performed. (#19482) --- web/src/components/markdown-editor.tsx | 6 +- web/src/lib/editor/lexical-editor.tsx | 64 +++++++++++-------- .../editor/plugins/wiki-link-click-plugin.tsx | 5 +- .../hooks/use-wiki-detail-content.ts | 2 +- .../compilation/wiki-detail-editor-panel.tsx | 2 +- .../hooks/use-wiki-navigation.ts | 2 - .../wiki-link-util.test.ts} | 2 +- .../wiki-link-util.ts} | 0 8 files changed, 45 insertions(+), 38 deletions(-) rename web/src/{pages/dataset/compilation/utils/parse-wiki-link.test.ts => utils/wiki-link-util.test.ts} (89%) rename web/src/{pages/dataset/compilation/utils/parse-wiki-link.ts => utils/wiki-link-util.ts} (100%) diff --git a/web/src/components/markdown-editor.tsx b/web/src/components/markdown-editor.tsx index ea02a7218af..76ca65ed923 100644 --- a/web/src/components/markdown-editor.tsx +++ b/web/src/components/markdown-editor.tsx @@ -18,12 +18,13 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import LexicalEditor from '@/lib/editor/lexical-editor'; import RawMarkdownEditor from '@/lib/editor/raw-markdown-editor'; +import type { WikiPageType } from '@/utils/wiki-link-util'; interface MarkdownEditorProps { content: string; onChange?: (content: string) => void; readOnly?: boolean; - onWikiLinkClick?: (pageType: 'concept' | 'entity', slug: string) => void; + onWikiLinkClick?: (pageType: WikiPageType, slug: string) => void; } export default function MarkdownEditor({ @@ -40,6 +41,9 @@ export default function MarkdownEditor({ if (content === contentRef.current) { return; } + // External content change (e.g. page switch): keep the ref in sync so + // toggleSource picks up the new content. + contentRef.current = content; if (showSource) setRawContent(content); }, [showSource, content]); diff --git a/web/src/lib/editor/lexical-editor.tsx b/web/src/lib/editor/lexical-editor.tsx index 1914f6793ed..dc4317ab959 100644 --- a/web/src/lib/editor/lexical-editor.tsx +++ b/web/src/lib/editor/lexical-editor.tsx @@ -20,6 +20,8 @@ import { $createParagraphNode, $getRoot } from 'lexical'; import type { JSX } from 'react'; import { useEffect, useMemo, useRef } from 'react'; +import type { WikiPageType } from '@/utils/wiki-link-util'; + import ContentEditable from './content-editable'; import theme from './editor-theme'; import { @@ -33,6 +35,10 @@ import nodes from './nodes'; // Direct CSS import (more reliable than @import in App.css) import './editor-theme.css'; +// Updates that import externally-provided content carry this tag so +// ChangeListener can skip them — onChange should only fire for user edits. +const ExternalContentSyncTag = 'external-content-sync'; + interface Props { content: string; onChange?: (markdown: string) => void; @@ -40,7 +46,7 @@ interface Props { placeholder?: string; onToggleSource?: () => void; showSource?: boolean; - onWikiLinkClick?: (pageType: 'concept' | 'entity', slug: string) => void; + onWikiLinkClick?: (pageType: WikiPageType, slug: string) => void; } function InitialContentPlugin({ @@ -58,15 +64,18 @@ function InitialContentPlugin({ if (seeded.current) return; seeded.current = true; - editor.update(() => { - const root = $getRoot(); - root.clear(); - if (content && content.trim()) { - $convertFromEnhancedMarkdownString(content, transformers); - } else { - root.append($createParagraphNode()); - } - }); + editor.update( + () => { + const root = $getRoot(); + root.clear(); + if (content && content.trim()) { + $convertFromEnhancedMarkdownString(content, transformers); + } else { + root.append($createParagraphNode()); + } + }, + { tag: ExternalContentSyncTag }, + ); // oxlint-disable-next-line react/exhaustive-deps }, [editor]); @@ -83,18 +92,21 @@ function ContentSyncPlugin({ const [editor] = useLexicalComposerContext(); useEffect(() => { - editor.update(() => { - const currentMarkdown = $convertToEnhancedMarkdownString(transformers); - if (currentMarkdown === content) return; - - const root = $getRoot(); - root.clear(); - if (content && content.trim()) { - $convertFromEnhancedMarkdownString(content, transformers); - } else { - root.append($createParagraphNode()); - } - }); + editor.update( + () => { + const currentMarkdown = $convertToEnhancedMarkdownString(transformers); + if (currentMarkdown === content) return; + + const root = $getRoot(); + root.clear(); + if (content && content.trim()) { + $convertFromEnhancedMarkdownString(content, transformers); + } else { + root.append($createParagraphNode()); + } + }, + { tag: ExternalContentSyncTag }, + ); }, [content, editor, transformers]); return null; @@ -108,16 +120,12 @@ function ChangeListener({ transformers: Transformer[]; }) { const [editor] = useLexicalComposerContext(); - const initRef = useRef(false); useEffect(() => { if (!onChange) return; const removeListener = editor.registerUpdateListener( - ({ dirtyElements, dirtyLeaves }) => { - if (!initRef.current) { - initRef.current = true; - return; - } + ({ dirtyElements, dirtyLeaves, tags }) => { + if (tags.has(ExternalContentSyncTag)) return; if (dirtyElements.size === 0 && dirtyLeaves.size === 0) return; const markdown = editor.read(() => $convertToEnhancedMarkdownString(transformers), diff --git a/web/src/lib/editor/plugins/wiki-link-click-plugin.tsx b/web/src/lib/editor/plugins/wiki-link-click-plugin.tsx index 2bccc810a19..60be844a347 100644 --- a/web/src/lib/editor/plugins/wiki-link-click-plugin.tsx +++ b/web/src/lib/editor/plugins/wiki-link-click-plugin.tsx @@ -1,8 +1,5 @@ import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'; -import { - parseWikiLinkHref, - type WikiPageType, -} from '@/pages/dataset/compilation/utils/parse-wiki-link'; +import { parseWikiLinkHref, type WikiPageType } from '@/utils/wiki-link-util'; import { useEffect } from 'react'; type WikiLinkClickPluginProps = { diff --git a/web/src/pages/dataset/compilation/hooks/use-wiki-detail-content.ts b/web/src/pages/dataset/compilation/hooks/use-wiki-detail-content.ts index 3f79098f004..8d93cdb7a90 100644 --- a/web/src/pages/dataset/compilation/hooks/use-wiki-detail-content.ts +++ b/web/src/pages/dataset/compilation/hooks/use-wiki-detail-content.ts @@ -6,9 +6,9 @@ import { import { Docagg } from '@/interfaces/database/chat'; import { IArtifact, IWikiCommit } from '@/interfaces/database/dataset'; import { downloadMarkdownFile } from '@/utils/file-util'; +import type { WikiPageType } from '@/utils/wiki-link-util'; import { useCallback, useEffect, useMemo } from 'react'; -import type { WikiPageType } from '../utils/parse-wiki-link'; import { useCommitArtifact } from './use-commit-artifact'; import { useWikiEditor } from './use-wiki-editor'; import { useWikiLinkNavigation } from './use-wiki-link-navigation'; diff --git a/web/src/pages/dataset/compilation/wiki-detail-editor-panel.tsx b/web/src/pages/dataset/compilation/wiki-detail-editor-panel.tsx index 539c243482a..7a688f2c37e 100644 --- a/web/src/pages/dataset/compilation/wiki-detail-editor-panel.tsx +++ b/web/src/pages/dataset/compilation/wiki-detail-editor-panel.tsx @@ -10,8 +10,8 @@ import { import { Spin } from '@/components/ui/spin'; import type { Docagg } from '@/interfaces/database/chat'; import type { IWikiCommitDetail } from '@/interfaces/database/dataset'; +import type { WikiPageType } from '@/utils/wiki-link-util'; -import type { WikiPageType } from './utils/parse-wiki-link'; import { WikiVersionDiffPanel } from './wiki-version-diff-panel'; type WikiDetailEditorPanelProps = { diff --git a/web/src/pages/dataset/compilation/wiki-left-panel/hooks/use-wiki-navigation.ts b/web/src/pages/dataset/compilation/wiki-left-panel/hooks/use-wiki-navigation.ts index de9a1a428aa..781abea55a5 100644 --- a/web/src/pages/dataset/compilation/wiki-left-panel/hooks/use-wiki-navigation.ts +++ b/web/src/pages/dataset/compilation/wiki-left-panel/hooks/use-wiki-navigation.ts @@ -6,8 +6,6 @@ import { IArtifactTopic } from '@/interfaces/database/dataset'; import { useDebounce } from 'ahooks'; import { useCallback, useMemo, useRef, useState } from 'react'; -export type WikiPageType = 'concept' | 'entity' | 'topic'; - const normalizeTopicPath = (topic: string) => topic .split('/') diff --git a/web/src/pages/dataset/compilation/utils/parse-wiki-link.test.ts b/web/src/utils/wiki-link-util.test.ts similarity index 89% rename from web/src/pages/dataset/compilation/utils/parse-wiki-link.test.ts rename to web/src/utils/wiki-link-util.test.ts index f20ae983479..77bc8c39dd6 100644 --- a/web/src/pages/dataset/compilation/utils/parse-wiki-link.test.ts +++ b/web/src/utils/wiki-link-util.test.ts @@ -1,4 +1,4 @@ -import { parseWikiLinkHref } from './parse-wiki-link'; +import { parseWikiLinkHref } from './wiki-link-util'; describe('parseWikiLinkHref', () => { it('preserves nested typed slugs in artifact links', () => { diff --git a/web/src/pages/dataset/compilation/utils/parse-wiki-link.ts b/web/src/utils/wiki-link-util.ts similarity index 100% rename from web/src/pages/dataset/compilation/utils/parse-wiki-link.ts rename to web/src/utils/wiki-link-util.ts From 19ec6245c4fad1c73d500defcaf37f28e9cd77d8 Mon Sep 17 00:00:00 2001 From: Harsh Kashyap <55448981+Harsh23Kashyap@users.noreply.github.com> Date: Fri, 11 Sep 2026 07:23:09 +0530 Subject: [PATCH 091/568] fix(api): authorize task cancellation by dataset access (#19359) --- api/apps/restful_apis/task_api.py | 51 ++-- .../test_task_cancel_authz_unit.py | 266 ++++++++++++++++++ 2 files changed, 299 insertions(+), 18 deletions(-) create mode 100644 test/unit_test/api/apps/restful_apis/test_task_cancel_authz_unit.py diff --git a/api/apps/restful_apis/task_api.py b/api/apps/restful_apis/task_api.py index 3688e71bc88..1e016a43964 100644 --- a/api/apps/restful_apis/task_api.py +++ b/api/apps/restful_apis/task_api.py @@ -16,7 +16,7 @@ import logging from datetime import datetime -from api.apps import login_required +from api.apps import current_user, login_required from api.db.services.task_service import TaskService, CANVAS_DEBUG_DOC_ID, GRAPH_RAPTOR_FAKE_DOC_ID from api.utils.api_utils import ( get_json_result, @@ -55,6 +55,29 @@ async def _cancel_task(task_id): Sets a Redis cancel flag, updates the task progress to -1 (cancelled), and marks the associated document's run status as CANCEL if applicable. """ + exists, task = TaskService.get_by_id(task_id) + if not exists: + return get_json_result(data=True) + + # Cancelling flips the document to CANCEL and sets the worker cancel flag, + # so the caller must be able to access the dataset that owns the document - + # otherwise any logged-in user could stop another tenant's parsing tasks by + # guessing a task id. Tasks bound to fake doc ids (canvas debug, + # graph/raptor) carry no resolvable document and are cancelled through the + # kb-scoped flows instead. + doc_id = task.doc_id + doc = None + if doc_id and doc_id not in (CANVAS_DEBUG_DOC_ID, GRAPH_RAPTOR_FAKE_DOC_ID): + from api.db.services.document_service import DocumentService + + # DocumentService.accessible fails closed when the document no longer + # resolves, so a task whose document is gone cannot be cancelled cross + # tenant. + if not DocumentService.accessible(doc_id, current_user.id): + logging.warning("task cancel denied: task_id=%s user_id=%s", task_id, current_user.id) + return get_json_result(data=False, code=RetCode.AUTHENTICATION_ERROR, message="no authorization") + _, doc = DocumentService.get_by_id(doc_id) + try: REDIS_CONN.set(f"{task_id}-cancel", "x") except Exception as e: @@ -64,10 +87,6 @@ async def _cancel_task(task_id): message="Failed to stop task", ) - exists, task = TaskService.get_by_id(task_id) - if not exists: - return get_json_result(data=True) - # Append a cancellation message so the user can see it in progress_msg. try: cancel_msg = f"\n{datetime.now().strftime('%H:%M:%S')} Task stopped by user." @@ -81,20 +100,16 @@ async def _cancel_task(task_id): logging.warning("Failed to update task %s progress after cancellation: %s", task_id, str(e)) # If the task belongs to a document, also mark the document's run status as - # cancelled so that the UI reflects the state correctly. + # cancelled so that the UI reflects the state correctly. Reuses the document + # resolved during the authorization check above. try: - from api.db.services.document_service import DocumentService - - doc_id = task.doc_id - if doc_id and doc_id not in (CANVAS_DEBUG_DOC_ID, GRAPH_RAPTOR_FAKE_DOC_ID): - _, doc = DocumentService.get_by_id(doc_id) - if doc and str(doc.run) in (TaskStatus.RUNNING.value, TaskStatus.SCHEDULE.value): - cancel_doc_msg = f"\n{datetime.now().strftime('%H:%M:%S')} Task stopped by user." - DocumentService.update_by_id( - doc_id, - {"run": TaskStatus.CANCEL.value, "progress": 0, "progress_msg": (doc.progress_msg or "") + cancel_doc_msg}, - ) - logging.debug("Appended cancellation marker to progress_msg on task cancel: task_id=%s doc_id=%s", task_id, doc_id) + if doc is not None and str(doc.run) in (TaskStatus.RUNNING.value, TaskStatus.SCHEDULE.value): + cancel_doc_msg = f"\n{datetime.now().strftime('%H:%M:%S')} Task stopped by user." + DocumentService.update_by_id( + doc_id, + {"run": TaskStatus.CANCEL.value, "progress": 0, "progress_msg": (doc.progress_msg or "") + cancel_doc_msg}, + ) + logging.debug("Appended cancellation marker to progress_msg on task cancel: task_id=%s doc_id=%s", task_id, doc_id) except Exception as e: logging.warning("Failed to update document run status for task %s: %s", task_id, str(e)) diff --git a/test/unit_test/api/apps/restful_apis/test_task_cancel_authz_unit.py b/test/unit_test/api/apps/restful_apis/test_task_cancel_authz_unit.py new file mode 100644 index 00000000000..50cfe994c6c --- /dev/null +++ b/test/unit_test/api/apps/restful_apis/test_task_cancel_authz_unit.py @@ -0,0 +1,266 @@ +# +# 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. +# +"""Authorization tests for POST /tasks//cancel and PATCH /tasks/. + +Cancelling a task flips its document to CANCEL and sets the Redis cancel +flag, so the route must verify the caller can access the dataset that owns +the task's document. These tests stub the HTTP layer and services and drive +the real handler. +""" + +import asyncio +import importlib.util +import sys +from pathlib import Path +from types import ModuleType, SimpleNamespace + +import pytest + + +class _DummyManager: + def route(self, *_args, **_kwargs): + def decorator(func): + return func + + return decorator + + +def _run(coro): + return asyncio.run(coro) + + +REDIS_SETS: list = [] +REQUEST_JSON: dict = {"action": "stop"} + + +def _load_module(monkeypatch, *, accessible_kb_ids): + repo_root = Path(__file__).resolve().parents[5] + + quart_mod = ModuleType("quart") + monkeypatch.setitem(sys.modules, "quart", quart_mod) + + api_pkg = ModuleType("api") + api_pkg.__path__ = [str(repo_root / "api")] + monkeypatch.setitem(sys.modules, "api", api_pkg) + + apps_mod = ModuleType("api.apps") + apps_mod.__path__ = [str(repo_root / "api" / "apps")] + apps_mod.current_user = SimpleNamespace(id="user-a") + apps_mod.login_required = lambda func: func + monkeypatch.setitem(sys.modules, "api.apps", apps_mod) + api_pkg.apps = apps_mod + + api_utils_mod = ModuleType("api.utils.api_utils") + + def get_json_result(data=None, message="success", code=0): + return {"code": code, "data": data, "message": message} + + async def get_request_json(): + return REQUEST_JSON + + def validate_request(*_keys): + def _decorator(func): + async def _wrapper(*args, **kwargs): + return await func(*args, **kwargs) + + return _wrapper + + return _decorator + + api_utils_mod.get_json_result = get_json_result + api_utils_mod.get_request_json = get_request_json + api_utils_mod.validate_request = validate_request + monkeypatch.setitem(sys.modules, "api.utils.api_utils", api_utils_mod) + + constants_mod = ModuleType("common.constants") + + class RetCode: + ARGUMENT_ERROR = 101 + DATA_ERROR = 102 + AUTHENTICATION_ERROR = 109 + CONNECTION_ERROR = 503 + + class _Status: + def __init__(self, v): + self.value = v + + class TaskStatus: + RUNNING = _Status("1") + SCHEDULE = _Status("0") + CANCEL = _Status("4") + + constants_mod.RetCode = RetCode + constants_mod.TaskStatus = TaskStatus + monkeypatch.setitem(sys.modules, "common.constants", constants_mod) + + redis_mod = ModuleType("rag.utils.redis_conn") + + class _Redis: + @staticmethod + def set(key, value): + REDIS_SETS.append(key) + + redis_mod.REDIS_CONN = _Redis + monkeypatch.setitem(sys.modules, "rag.utils.redis_conn", redis_mod) + + # TaskService stub: task-1 -> doc-1 -> kb-mine; task-2 -> doc-2 -> kb-theirs + task_svc_mod = ModuleType("api.db.services.task_service") + + class _UpdateChain: + def where(self, *a): + return self + + def execute(self): + return 1 + + class _TaskModel: + id = "task-id" + progress_msg = "" + progress = 0 + + @staticmethod + def update(**_kw): + return _UpdateChain() + + class _TaskService: + model = _TaskModel + + @staticmethod + def get_by_id(task_id): + if task_id == "task-1": + return True, SimpleNamespace(id="task-1", doc_id="doc-1") + if task_id == "task-2": + return True, SimpleNamespace(id="task-2", doc_id="doc-2") + if task_id == "task-3": + return True, SimpleNamespace(id="task-3", doc_id="dataflow_x") + if task_id == "task-4": + return True, SimpleNamespace(id="task-4", doc_id="doc-gone") + return False, None + + task_svc_mod.TaskService = _TaskService + task_svc_mod.CANVAS_DEBUG_DOC_ID = "dataflow_x" + task_svc_mod.GRAPH_RAPTOR_FAKE_DOC_ID = "graph_raptor_x" + monkeypatch.setitem(sys.modules, "api.db.services.task_service", task_svc_mod) + + doc_svc_mod = ModuleType("api.db.services.document_service") + + class _DocumentService: + @staticmethod + def get_by_id(doc_id): + if doc_id == "doc-1": + return True, SimpleNamespace(id="doc-1", kb_id="kb-mine", run="1", progress_msg="") + if doc_id == "doc-2": + return True, SimpleNamespace(id="doc-2", kb_id="kb-theirs", run="1", progress_msg="") + return False, None + + @staticmethod + def accessible(doc_id, user_id): + ok, doc = _DocumentService.get_by_id(doc_id) + if not ok: + return False + return doc.kb_id in accessible_kb_ids + + @staticmethod + def update_by_id(_id, _data): + return 1 + + doc_svc_mod.DocumentService = _DocumentService + monkeypatch.setitem(sys.modules, "api.db.services.document_service", doc_svc_mod) + + kb_svc_mod = ModuleType("api.db.services.knowledgebase_service") + + class _KnowledgebaseService: + @staticmethod + def accessible(kb_id, user_id): + return kb_id in accessible_kb_ids + + kb_svc_mod.KnowledgebaseService = _KnowledgebaseService + monkeypatch.setitem(sys.modules, "api.db.services.knowledgebase_service", kb_svc_mod) + + for mod_name in list(sys.modules.keys()): + if mod_name.startswith("api.apps.restful_apis.task_api"): + del sys.modules[mod_name] + + module_name = "api.apps.restful_apis.task_api" + module_path = repo_root / "api" / "apps" / "restful_apis" / "task_api.py" + spec = importlib.util.spec_from_file_location(module_name, module_path) + module = importlib.util.module_from_spec(spec) + module.manager = _DummyManager() + monkeypatch.setitem(sys.modules, module_name, module) + spec.loader.exec_module(module) + return module + + +@pytest.fixture(autouse=True) +def _clean_redis_log(): + REDIS_SETS.clear() + + +@pytest.mark.p2 +def test_cancel_own_task_succeeds(monkeypatch): + module = _load_module(monkeypatch, accessible_kb_ids={"kb-mine"}) + res = _run(module.cancel_task("task-1")) + assert res["code"] == 0, res + assert "task-1-cancel" in REDIS_SETS + + +@pytest.mark.p2 +def test_cancel_other_tenants_task_denied(monkeypatch): + module = _load_module(monkeypatch, accessible_kb_ids={"kb-mine"}) + res = _run(module.cancel_task("task-2")) + assert res["code"] != 0, f"cross-tenant cancel must be denied, got {res}" + assert "task-2-cancel" not in REDIS_SETS, "cancel flag was set for another tenant's task" + + +@pytest.mark.p2 +def test_patch_stop_entry_point_enforces_same_authz(monkeypatch): + module = _load_module(monkeypatch, accessible_kb_ids={"kb-mine"}) + REQUEST_JSON["action"] = "stop" + res = _run(module.patch_task("task-2")) + assert res["code"] != 0, f"cross-tenant PATCH stop must be denied, got {res}" + assert "task-2-cancel" not in REDIS_SETS + res = _run(module.patch_task("task-1")) + assert res["code"] == 0, res + assert "task-1-cancel" in REDIS_SETS + + +@pytest.mark.p2 +def test_patch_rejects_unknown_action(monkeypatch): + module = _load_module(monkeypatch, accessible_kb_ids={"kb-mine"}) + REQUEST_JSON["action"] = "restart" + res = _run(module.patch_task("task-1")) + assert res["code"] != 0 + assert "task-1-cancel" not in REDIS_SETS + + +@pytest.mark.p2 +def test_fake_doc_id_tasks_still_cancel(monkeypatch): + # Canvas-debug / graph-raptor tasks carry fake doc ids and are cancelled + # through the kb-scoped flows; the authz change must not break them. + module = _load_module(monkeypatch, accessible_kb_ids=set()) + res = _run(module.cancel_task("task-3")) + assert res["code"] == 0, res + assert "task-3-cancel" in REDIS_SETS + + +@pytest.mark.p2 +def test_task_with_unresolved_document_is_denied(monkeypatch): + # accessible() fails closed: a task whose document no longer resolves + # cannot be cancelled cross tenant. + module = _load_module(monkeypatch, accessible_kb_ids={"kb-mine"}) + res = _run(module.cancel_task("task-4")) + assert res["code"] != 0, f"unresolved document must fail closed, got {res}" + assert "task-4-cancel" not in REDIS_SETS From 2aedd79b8fb6a3a7cee3f2c7ec3ff5ce7850b93d Mon Sep 17 00:00:00 2001 From: buua436 Date: Fri, 11 Sep 2026 10:15:53 +0800 Subject: [PATCH 092/568] refa: remove unused knowledge compilation code (#19437) --- api/apps/services/dataset_api_service.py | 4 +- .../runtime_configuration.md | 1 - rag/advanced_rag/knowlege_compile/__init__.py | 2 - rag/advanced_rag/knowlege_compile/_common.py | 134 ---- .../knowlege_compile/structure.py | 81 -- rag/advanced_rag/knowlege_compile/wiki.py | 408 +--------- .../knowlege_compile/wiki_incremental.py | 248 ------ .../chunk_post_processor.py | 13 - .../dataset_wiki_generator.py | 748 +----------------- .../advanced_rag/knowlege_compile/conftest.py | 1 + .../test_wiki_empty_eligible_message.py | 6 +- 11 files changed, 19 insertions(+), 1627 deletions(-) diff --git a/api/apps/services/dataset_api_service.py b/api/apps/services/dataset_api_service.py index 0b8c86966a1..6de92596af1 100644 --- a/api/apps/services/dataset_api_service.py +++ b/api/apps/services/dataset_api_service.py @@ -1596,8 +1596,8 @@ async def search_datasets(tenant_id: str, req: dict): # Artifact (knowledge compilation) page surface # # These three helpers power the dataset-level "Artifact" tab. They query rows -# with ``compile_kwd="wiki_page"`` written by TaskHandler's -# ``persist_wiki_pages``. The schema fields they rely on are: +# with ``compile_kwd="wiki_page"`` written by incremental Wiki REFINE. The +# schema fields they rely on are: # slug_kwd, title_kwd, page_type_kwd, content_with_weight, # topic_kwd, entity_names_kwd, outlinks_kwd, related_kb_pages_kwd, # source_chunk_ids, source_doc_ids diff --git a/docs/guides/knowledge_compilation/runtime_configuration.md b/docs/guides/knowledge_compilation/runtime_configuration.md index 1588fabfa11..1223f850084 100644 --- a/docs/guides/knowledge_compilation/runtime_configuration.md +++ b/docs/guides/knowledge_compilation/runtime_configuration.md @@ -28,7 +28,6 @@ the valid range and logged. | `WIKI_REFINE_WORKERS` | `4` | Number of page-refinement workers. Actual LLM concurrency is still limited by the shared pool. | | `WIKI_MAP_WORKERS` | `20` | Default worker count used by direct Wiki MAP calls. | | `WIKI_MAP_TIMEOUT` | `600` seconds | Timeout for one Wiki MAP extraction call. | -| `WIKI_REDUCE_TIMEOUT` | `60` seconds | Timeout for one Wiki REDUCE disambiguation call. | | `WIKI_PLAN_TIMEOUT` | `600` seconds | Timeout for Wiki PLAN calls, including page planning and MAYBE resolution. | | `WIKI_REFINE_TIMEOUT` | `300` seconds | Timeout for one Wiki page-writing call. | | `WIKI_MERGE_TIMEOUT` | `600` seconds | Timeout for merging an existing Wiki page with newly generated content. | diff --git a/rag/advanced_rag/knowlege_compile/__init__.py b/rag/advanced_rag/knowlege_compile/__init__.py index 2a848ac2f16..36fd2e1f2b1 100644 --- a/rag/advanced_rag/knowlege_compile/__init__.py +++ b/rag/advanced_rag/knowlege_compile/__init__.py @@ -23,7 +23,6 @@ WIKI_REDUCE_COMPILE_KWD, wiki_map_from_chunks, wiki_plan_from_reduction, - wiki_reduce_from_extracts, wiki_refine_from_plan, ) @@ -32,7 +31,6 @@ "compile_structure_from_text", "merge_compiled_structures", "wiki_map_from_chunks", - "wiki_reduce_from_extracts", "wiki_plan_from_reduction", "wiki_refine_from_plan", "WIKI_MAP_COMPILE_KWD", diff --git a/rag/advanced_rag/knowlege_compile/_common.py b/rag/advanced_rag/knowlege_compile/_common.py index 9cd36157c46..f7243c57535 100644 --- a/rag/advanced_rag/knowlege_compile/_common.py +++ b/rag/advanced_rag/knowlege_compile/_common.py @@ -197,30 +197,6 @@ def union_ordered(*lists: Optional[Iterable]) -> list[str]: return seen -# --------------------------------------------------------------------------- -# Token-budget calculation for split_chunks -# --------------------------------------------------------------------------- - - -def make_input_budget( - chat_mdl, - *prompts: str, - floor: int = 1024, - utilization: float = INPUT_UTILIZATION, -) -> int: - """``chat_mdl.max_length * utilization - num_tokens(sum of prompts)``, - floored at ``floor``. - - Mirrors the budget idiom used by ``compile_structure_from_text`` and - ``wiki_map_from_chunks``: caller passes the constant prompt scaffolding - (system prompt + user template) — ``split_chunks`` then sizes batches - to leave that much room. - """ - overhead = num_tokens_from_string("".join(p or "" for p in prompts)) - budget = int(chat_mdl.max_length * utilization) - overhead - return max(budget, floor) - - # --------------------------------------------------------------------------- # Defensive LLMBundle validation # --------------------------------------------------------------------------- @@ -256,111 +232,6 @@ def ensure_llm_bundle(mdl, method: str, *, label: str = "model"): return None -# --------------------------------------------------------------------------- -# ES I/O wrappers -# --------------------------------------------------------------------------- - - -async def doc_storage_search( - select_fields: list[str], - condition: dict, - *, - tenant_id: str, - kb_ids: list[str], - match_expressions: list | None = None, - offset: int = 0, - limit: int = 1000, - label: str = "doc_storage_search", -) -> dict: - """Thin wrapper around ``docStoreConn.search`` + ``get_fields``. - - Returns ``{row_id: row_dict}``. Returns ``{}`` on failure (with a - logged exception). ``label`` is included in the failure log so each - call site is identifiable. - """ - from common import settings - from common.doc_store.doc_store_base import OrderByExpr - from rag.nlp import search as _rag_search - - index = _rag_search.index_name(tenant_id) - try: - res = await thread_pool_exec( - settings.docStoreConn.search, - select_fields, - [], - condition, - match_expressions or [], - OrderByExpr(), - offset, - limit, - index, - kb_ids, - ) - return settings.docStoreConn.get_fields(res, select_fields) or {} - except Exception: - logging.exception("%s failed (condition=%r)", label, condition) - return {} - - -async def doc_storage_insert( - rows: list[dict], - tenant_id: str, - kb_id: str, - *, - label: str = "doc_storage_insert", -) -> None: - """Bulk insert wrapped in ``thread_pool_exec``. Logs on failure.""" - if not rows: - return - from common import settings - from rag.nlp import search as _rag_search - - index = _rag_search.index_name(tenant_id) - try: - await thread_pool_exec(settings.docStoreConn.insert, rows, index, kb_id) - except Exception: - logging.exception("%s failed (%d row(s))", label, len(rows)) - - -async def doc_storage_delete( - condition: dict, - tenant_id: str, - kb_id: str, - *, - label: str = "doc_storage_delete", -) -> None: - """Bulk delete wrapped in ``thread_pool_exec``. Best-effort; logs on - failure (some callers rely on id-based upsert as a fallback).""" - from common import settings - from rag.nlp import search as _rag_search - - index = _rag_search.index_name(tenant_id) - try: - await thread_pool_exec(settings.docStoreConn.delete, condition, index, kb_id) - except Exception: - logging.debug("%s failed (condition=%r); caller may rely on id-upsert", label, condition) - - -async def doc_storage_upsert_one( - filter_condition: dict, - row: dict, - tenant_id: str, - kb_id: str, - *, - label: str = "doc_storage_upsert_one", -) -> None: - """Delete-by-filter then insert. Used when an in-place update would - require knowing the existing row's id and we'd rather drop+re-create. - - Best-effort delete (failures are debug-logged) followed by the insert. - Set ``row["id"]`` to a stable value derived from the filter - (:func:`stable_row_id`) so id-based dedup at the connector catches any - race that bypasses the delete. - """ - await doc_storage_delete(filter_condition, tenant_id, kb_id, label=f"{label}.delete") - await doc_storage_insert([row], tenant_id, kb_id, label=f"{label}.insert") - - # --------------------------------------------------------------------------- # Doc-vector field discovery # --------------------------------------------------------------------------- @@ -1022,12 +893,7 @@ async def bulk_dedup_items( "encode", "tokenize_for_search", "union_ordered", - "make_input_budget", "ensure_llm_bundle", - "doc_storage_search", - "doc_storage_insert", - "doc_storage_delete", - "doc_storage_upsert_one", "find_vec_field", # New engines "normalize_key", diff --git a/rag/advanced_rag/knowlege_compile/structure.py b/rag/advanced_rag/knowlege_compile/structure.py index 638f99c699a..7a447b02ce8 100644 --- a/rag/advanced_rag/knowlege_compile/structure.py +++ b/rag/advanced_rag/knowlege_compile/structure.py @@ -1699,32 +1699,6 @@ async def _struct_doc_storage_knn_candidate( }} """ -ES_GROUP_BATCH_MERGE_PROMPT = """You are judging multiple independent ES deduplication groups. - -For every group, compare every incoming item with that group's existing item. -You must make a separate duplicated decision for every incoming item. Only -incoming items marked duplicated=true may contribute to that group's merged -payload. Incoming items marked duplicated=false must remain separate. Do not -merge items from different groups and do not invent data. - -Return ONLY JSON with this exact shape: -{{ - "groups": [ - {{ - "group_id": "", - "decisions": [ - {{"incoming_index": 0, "duplicated": true}}, - {{"incoming_index": 1, "duplicated": false}} - ], - "merged": - }} - ] -}} - -Groups: -{groups} -""" - ES_GROUP_DECISION_BATCH_PROMPT = """You are judging multiple independent ES deduplication groups. For every incoming item, independently decide whether it is a duplicate of @@ -1798,61 +1772,6 @@ async def _struct_judge_doc_storage_group_batch(group_specs: list[dict], chat_md return result -async def _struct_merge_doc_storage_group_batch(group_specs: list[dict], chat_mdl) -> dict[str, tuple[list[dict], dict | None]]: - """Judge multiple old_id groups in one LLM request.""" - prompt_groups = [] - for spec in group_specs: - old_doc = spec["old_doc"] - incoming_docs = spec["incoming_docs"] - try: - existing_payload = json.loads(old_doc.get("content_with_weight") or "{}") - incoming_payloads = [json.loads(d.get("content_with_weight") or "{}") for d in incoming_docs] - except Exception: - logging.exception("merge: failed to parse grouped content_with_weight") - continue - if not isinstance(existing_payload, dict) or not all(isinstance(p, dict) for p in incoming_payloads): - continue - prompt_groups.append( - { - "group_id": spec["old_id"], - "existing": existing_payload, - "incoming": [{"index": i, "item": payload} for i, payload in enumerate(incoming_payloads)], - } - ) - if not prompt_groups: - return {spec["old_id"]: (list(spec["incoming_docs"]), None) for spec in group_specs} - - user_prompt = ES_GROUP_BATCH_MERGE_PROMPT.format(groups=json.dumps(prompt_groups, ensure_ascii=False)) - system_prompt = MERGE_SYSTEM_PROMPT + "\n\n" + ES_GROUP_BATCH_MERGE_PROMPT.split("Groups:", 1)[0] - res = await gen_json(system_prompt, user_prompt, chat_mdl, gen_conf=_knowledge_compile_gen_conf(chat_mdl, {"temperature": 0.0})) - raw_groups = res.get("groups") if isinstance(res, dict) else None - if not isinstance(raw_groups, list): - return {spec["old_id"]: (list(spec["incoming_docs"]), None) for spec in group_specs} - - result = {} - by_id = {spec["old_id"]: spec for spec in group_specs} - for raw in raw_groups: - if not isinstance(raw, dict) or raw.get("group_id") not in by_id: - continue - spec = by_id[raw["group_id"]] - decisions = raw.get("decisions") - merged = raw.get("merged") - if not isinstance(decisions, list): - result[spec["old_id"]] = (list(spec["incoming_docs"]), None) - continue - duplicate_indices = {item.get("incoming_index") for item in decisions if isinstance(item, dict) and item.get("duplicated") is True and isinstance(item.get("incoming_index"), int)} - duplicate_indices = {i for i in duplicate_indices if 0 <= i < len(spec["incoming_docs"])} - if not duplicate_indices or not isinstance(merged, dict): - result[spec["old_id"]] = (list(spec["incoming_docs"]), None) - continue - separate = [d for i, d in enumerate(spec["incoming_docs"]) if i not in duplicate_indices] - result[spec["old_id"]] = (separate, merged) - - for spec in group_specs: - result.setdefault(spec["old_id"], (list(spec["incoming_docs"]), None)) - return result - - async def _struct_merge_doc_storage_group(old_doc: dict, incoming_docs: list[dict], chat_mdl) -> tuple[list[dict], dict | None]: """Judge one ES candidate group with one LLM request. diff --git a/rag/advanced_rag/knowlege_compile/wiki.py b/rag/advanced_rag/knowlege_compile/wiki.py index b6b277555fa..4d01f04c1ea 100644 --- a/rag/advanced_rag/knowlege_compile/wiki.py +++ b/rag/advanced_rag/knowlege_compile/wiki.py @@ -49,7 +49,6 @@ from ._common import ( build_chunk_batches as _build_chunk_batches, - bulk_dedup_items as _bulk_dedup_items, ensure_llm_bundle as _ensure_llm_bundle, knowledge_compile_gen_conf as _knowledge_compile_gen_conf, run_chunked_pipeline as _run_chunked_pipeline, @@ -1369,99 +1368,9 @@ async def _process_one(batch: list[dict], bi: int, total: int) -> dict: return merged -# --------------------------------------------------------------------------- -# REDUCE phase (KB-scoped) -# --------------------------------------------------------------------------- -# +# PLAN input cache WIKI_REDUCE_COMPILE_KWD = "wiki_reduce_result" -DEFAULT_WIKI_REDUCE_MERGE_THRESHOLD = 0.95 -DEFAULT_WIKI_REDUCE_AMBIGUOUS_LOW = 0.75 -DEFAULT_WIKI_REDUCE_AMBIGUOUS_BATCH = 50 -DEFAULT_WIKI_REDUCE_TIMEOUT = _env_int("WIKI_REDUCE_TIMEOUT", 60, minimum=1) - - -# System prompt for the LLM disambiguation batch. The shared engine -# (``_common.bulk_dedup_items``) defaults to the same wording via -# ``_common.DEFAULT_DISAMBIGUATE_SYSTEM``; we keep the local alias so the -# constant name stays usable by call sites and external imports. -WIKI_REDUCE_DISAMBIGUATE_SYSTEM = "You are a named-entity resolution assistant. Return only JSON." - - -# --- ES I/O ---------------------------------------------------------------- - - -async def _wiki_load_all_map_extracts(tenant_id: str, kb_id: str) -> dict: - """Aggregate every wiki_map_extract row in this KB into one merged dict. - - Pages through ES if the KB has more than the per-call cap. Returns a dict - in the same shape as wiki_map_from_chunks' return value. - """ - from common import settings - from common.doc_store.doc_store_base import OrderByExpr - from rag.nlp import search as _rag_search - - index = _rag_search.index_name(tenant_id) - disabled_doc_ids = await _wiki_disabled_doc_ids(kb_id) - condition = {"compile_kwd": [WIKI_MAP_COMPILE_KWD]} - select_fields = ["id", "content_with_weight", "doc_id"] - - PAGE_SIZE = 1000 - offset = 0 - merged = _wiki_empty_extract() - seen_topics: set[str] = set() - - while True: - try: - res = await thread_pool_exec( - settings.docStoreConn.search, - select_fields, - [], - condition, - [], - OrderByExpr(), - offset, - PAGE_SIZE, - index, - [kb_id], - ) - field_map = settings.docStoreConn.get_fields(res, select_fields) - except Exception: - logging.exception("wiki_reduce: failed to page wiki_map_extract rows") - break - - if not field_map: - break - - for row in field_map.values(): - if _wiki_doc_ids(row.get("doc_id")) & disabled_doc_ids: - continue - content = row.get("content_with_weight") - if not isinstance(content, str) or not content: - continue - try: - payload = json.loads(content) - except Exception: - logging.debug("wiki_reduce: skipping unparseable extract row") - continue - if not isinstance(payload, dict): - continue - for key in _EXTRACT_LIST_KEYS: - items = payload.get(key) - if isinstance(items, list): - merged[key].extend(item for item in items if isinstance(item, dict)) - topics = payload.get("topics") - if isinstance(topics, list): - for t in topics: - if isinstance(t, str) and t and t not in seen_topics: - seen_topics.add(t) - merged["topics"].append(t) - - if len(field_map) < PAGE_SIZE: - break - offset += PAGE_SIZE - - return merged async def _wiki_all_map_doc_ids(tenant_id: str, kb_id: str) -> list[str]: @@ -1516,84 +1425,6 @@ async def _wiki_all_map_doc_ids(tenant_id: str, kb_id: str) -> list[str]: return doc_ids -async def _wiki_compute_map_input_hash(tenant_id: str, kb_id: str) -> str: - """xxh64 fingerprint of the **current** ``wiki_map_extract`` rows for - this KB — used by REDUCE / PLAN to cache-bust when MAP changed. - - Built from ``sorted((chunk_id, chunk_hash))`` so: - * adding a new chunk → new pair appears → hash flips. - * editing a chunk → MAP row deleted + re-inserted with new hash → flips. - * deleting a chunk → MAP row gone → its pair drops → flips. - * everything stable → identical hash. - - Empty / missing ``chunk_hash_kwd`` (legacy rows) defaults to '' so a - legacy KB still produces a stable hash; once those rows are touched - by an incremental MAP run, the hash naturally upgrades. - - Pages through ES in windows of ``PAGE_SIZE`` rows — single-shot - "give me everything" reads hit doc-store limits on KBs with many - chunks. The accumulated ``pairs`` are sorted once at the end so the - fingerprint is independent of page order. - """ - from common import settings - from common.doc_store.doc_store_base import OrderByExpr - from rag.nlp import search as _rag_search - - index = _rag_search.index_name(tenant_id) - disabled_doc_ids = await _wiki_disabled_doc_ids(kb_id) - condition = {"compile_kwd": [WIKI_MAP_COMPILE_KWD]} - select_fields = ["id", "doc_id", "source_chunk_ids", "chunk_hash_kwd"] - - PAGE_SIZE = 128 - offset = 0 - pairs: list[tuple[str, str]] = [] - while True: - try: - res = await thread_pool_exec( - settings.docStoreConn.search, - select_fields, - [], - condition, - [], - OrderByExpr(), - offset, - PAGE_SIZE, - index, - [kb_id], - ) - field_map = settings.docStoreConn.get_fields(res, select_fields) - except Exception: - logging.exception( - "wiki: failed to compute MAP input hash for kb=%s (offset=%d)", - kb_id, - offset, - ) - # Partial scan → cannot trust the resulting hash; return "" - # so REDUCE / PLAN fall through to a full re-run rather than - # cache-hitting against an incomplete fingerprint. - return "" - if not field_map: - break - for row in field_map.values(): - if _wiki_doc_ids(row.get("doc_id")) & disabled_doc_ids: - continue - hh = row.get("chunk_hash_kwd") - if not isinstance(hh, str): - hh = "" - src = row.get("source_chunk_ids") or [] - if isinstance(src, list): - for cid in src: - if isinstance(cid, str) and cid: - pairs.append((cid, hh)) - if len(field_map) < PAGE_SIZE: - break - offset += PAGE_SIZE - - pairs.sort() - body = "|".join(f"{cid}:{hh}" for cid, hh in pairs) + "|" + _WIKI_PIPELINE_REV - return _xxhash.xxh64(body.encode("utf-8", "surrogatepass")).hexdigest() - - async def _wiki_load_reduce_resume( tenant_id: str, kb_id: str, @@ -1642,232 +1473,6 @@ async def _wiki_load_reduce_resume( return cached, stored_hash -async def _wiki_persist_reduce( - reduced: dict, - tenant_id: str, - kb_id: str, - input_hash: str = "", - source_doc_ids: Optional[list[str]] = None, -) -> None: - """Upsert the single non-searchable wiki_reduce_result row for this KB. - - ``input_hash`` records the MAP-state fingerprint this reduction was - computed from; the next call compares it before re-running. - ``source_doc_ids`` is the set of documents that fed this reduction, used - for delete-time reference counting. - """ - from common import settings - from rag.nlp import search as _rag_search - - index = _rag_search.index_name(tenant_id) - kb_id_str = str(kb_id) - content_with_weight = json.dumps(reduced, ensure_ascii=False) - # Stable id per KB so a re-run upserts the same row. - row_id = _stable_row_id(WIKI_REDUCE_COMPILE_KWD, kb_id_str) - doc = { - "id": row_id, - "doc_id": kb_id_str, # sentinel — KB-scoped row, not a real document - "compile_kwd": WIKI_REDUCE_COMPILE_KWD, - "source_id": [kb_id_str], - "source_doc_ids": list(source_doc_ids or []), - "input_hash_kwd": input_hash, - "content_with_weight": content_with_weight, - "available_int": 0, - } - try: - # Best-effort delete then insert so re-runs replace cleanly. - try: - await thread_pool_exec( - settings.docStoreConn.delete, - {"compile_kwd": WIKI_REDUCE_COMPILE_KWD}, - index, - kb_id, - ) - except Exception: - logging.debug("wiki_reduce: prior result delete failed; will overwrite by id") - await thread_pool_exec(settings.docStoreConn.insert, [doc], index, kb_id) - except Exception: - logging.exception("wiki_reduce: failed to persist result row") - - -# --- public entry ---------------------------------------------------------- - - -async def wiki_reduce_from_extracts( - chat_mdl, - embd_mdl, - tenant_id: str, - kb_id: str, - merge_threshold: float = DEFAULT_WIKI_REDUCE_MERGE_THRESHOLD, - ambiguous_low: float = DEFAULT_WIKI_REDUCE_AMBIGUOUS_LOW, - ambiguous_batch_size: int = DEFAULT_WIKI_REDUCE_AMBIGUOUS_BATCH, - llm_timeout: int = DEFAULT_WIKI_REDUCE_TIMEOUT, - force_rerun: bool = False, - callback: Optional[Callable] = None, -) -> dict: - """Phase 2 (REDUCE/Dedup) — KB-scoped. - - Loads every ``wiki_map_extract`` row in this KB (across all documents) and - produces a single canonical dict of entities/concepts via: - 1. Exact dedup by ``(normalize(name), type)`` for entities and by - ``normalize(term)`` for concepts. - 2. Embedding dedup of entity names: vectorized pairwise cosine over - ``embd_mdl.encode(...)`` output. Pairs of the same type with - similarity ≥ ``merge_threshold`` auto-merge; pairs in - ``[ambiguous_low, merge_threshold)`` go to step 3. - 3. LLM disambiguation: batches of ambiguous pairs are sent to - ``chat_mdl`` via ``gen_json``; true verdicts collapse via union-find. - 4. Apply merges: sum ``mention_count``, union ``aliases`` and - ``chunk_ids`` per canonical entity. - - The result is persisted to ES as a single non-searchable - ``wiki_reduce_result`` row per KB. Subsequent calls with - ``force_rerun=False`` (default) return the cached row immediately; pass - ``force_rerun=True`` after new ``wiki_map_extract`` rows have been added. - - Args: - chat_mdl, embd_mdl: ragflow LLMBundle instances. - tenant_id, kb_id: address the doc-store index. - merge_threshold: cosine ≥ this auto-merges. Default 0.90. - ambiguous_low: cosine in [ambiguous_low, merge_threshold) goes to LLM. - ambiguous_batch_size: max pairs per LLM disambiguation call. - llm_timeout: seconds per LLM disambiguation batch. - force_rerun: bypass the cached wiki_reduce_result. - callback: optional ``(progress: float, msg: str)`` callback. - - Returns the canonical extract dict:: - - { - "entities": [{"name","type","aliases","mention_count","chunk_ids"}, ...], - "concepts": [{"term","definition_excerpt","mention_count","chunk_ids"}, ...], - "claims": [...], # pass-through from MAP - "relations": [...], # pass-through from MAP - "topics": [...], # pass-through from MAP - } - """ - # Incremental gate: the current MAP-state fingerprint is the union - # of every MAP row's (chunk_id, chunk_hash). If a cached REDUCE row - # exists AND its stored input_hash equals the current fingerprint, - # the upstream chunks haven't changed → cached output is still - # correct. ``force_rerun=True`` bypasses both checks for the - # legacy / admin "rebuild from scratch" path. - current_input_hash = await _wiki_compute_map_input_hash(tenant_id, kb_id) - reduce_source_doc_ids = await _wiki_all_map_doc_ids(tenant_id, kb_id) - if not force_rerun: - cached_pair = await _wiki_load_reduce_resume(tenant_id, kb_id) - if cached_pair is not None: - cached, stored_hash = cached_pair - if stored_hash and stored_hash == current_input_hash: - if callback: - try: - callback(1.0, "wiki REDUCE: cache hit (input unchanged)") - except Exception: - pass - return cached - # Cache present but stale (no hash, or hash mismatch). Fall - # through to a full re-reduce and write a fresh stamp. - - if callback: - try: - callback(0.05, "wiki REDUCE: loading MAP extracts") - except Exception: - pass - - raw = await _wiki_load_all_map_extracts(tenant_id, kb_id) - raw_entities = raw.get("entities") or [] - raw_concepts = raw.get("concepts") or [] - logging.info( - "wiki_reduce: kb=%s loaded raw entities=%d concepts=%d claims=%d relations=%d", - kb_id, - len(raw_entities), - len(raw_concepts), - len(raw.get("claims") or []), - len(raw.get("relations") or []), - ) - - if not raw_entities and not raw_concepts: - # Nothing to reduce; persist an empty result so resume can short-circuit. - empty = _wiki_empty_extract() - await _wiki_persist_reduce(empty, tenant_id, kb_id, input_hash=current_input_hash, source_doc_ids=reduce_source_doc_ids) - return empty - - if callback: - try: - callback(0.25, "wiki REDUCE: dedup (exact + embedding + LLM)") - except Exception: - pass - - # Entities: full three-phase dedup keyed by (normalized name, type). - canonical_entities = await _bulk_dedup_items( - raw_entities, - name_key="name", - type_key="type", - chat_mdl=chat_mdl, - embd_mdl=embd_mdl, - merge_threshold=merge_threshold, - ambiguous_low=ambiguous_low, - ambiguous_batch_size=ambiguous_batch_size, - disambiguate_system_prompt=WIKI_REDUCE_DISAMBIGUATE_SYSTEM, - llm_timeout=llm_timeout, - ) - - # Concepts: exact-dedup only (current behaviour); keep the longest - # definition_excerpt across the group via aggregate_extra. - def _concept_extras(group: list[dict]) -> dict: - best_def = max( - ((c.get("definition_excerpt") or "") for c in group if isinstance(c, dict)), - key=lambda s: len(s) if isinstance(s, str) else 0, - default="", - ) - return {"definition_excerpt": best_def} - - canonical_concepts = await _bulk_dedup_items( - raw_concepts, - name_key="term", - type_key=None, - aggregate_extra=_concept_extras, - ) - - logging.info( - "wiki_reduce: after dedup entities=%d concepts=%d", - len(canonical_entities), - len(canonical_concepts), - ) - - reduced = { - "entities": canonical_entities, - "concepts": canonical_concepts, - "claims": list(raw.get("claims") or []), - "relations": list(raw.get("relations") or []), - "topics": list(raw.get("topics") or []), - } - - if callback: - try: - callback(0.9, "wiki REDUCE: persisting result") - except Exception: - pass - await _wiki_persist_reduce(reduced, tenant_id, kb_id, input_hash=current_input_hash, source_doc_ids=reduce_source_doc_ids) - - logging.info( - "wiki_reduce: kb=%s done — entities=%d concepts=%d claims=%d relations=%d topics=%d", - kb_id, - len(reduced["entities"]), - len(reduced["concepts"]), - len(reduced["claims"]), - len(reduced["relations"]), - len(reduced["topics"]), - ) - - if callback: - try: - callback(1.0, "wiki REDUCE: done") - except Exception: - pass - - return reduced - - # --------------------------------------------------------------------------- # PLAN phase (KB-scoped) # --------------------------------------------------------------------------- @@ -2844,9 +2449,7 @@ async def wiki_plan_from_reduction( # placeholder is filled in at request time so each artifact compilation # template can override the page-structure section without touching the # rest of the writer's guidance. Use ``_build_refine_writer_system`` to -# materialize a concrete prompt; ``WIKI_REFINE_WRITER_SYSTEM`` is -# kept as the default-filled value for back-compat with any code that -# still imports it. +# materialize a concrete prompt. WIKI_REFINE_WRITER_SYSTEM_TEMPLATE = ( "You are an enterprise knowledge compilation writer. Your job is to write a single, " "high-quality wiki page by reading the SOURCE TEXT provided and using the " @@ -2897,9 +2500,6 @@ def _build_refine_writer_system(instruction: str | None = None, example: str | N """Return the writer system prompt with separate instruction and page example overrides. Empty values use the built-in defaults. - The default-filled form is also exposed as - ``WIKI_REFINE_WRITER_SYSTEM`` for callers that don't have an - override to apply. """ instruction_body = (instruction or "").strip() or "Follow the page structure and writing requirements below." example_body = (example or "").strip() or WIKI_TEMPLATE_EXAMPLE @@ -2909,9 +2509,6 @@ def _build_refine_writer_system(instruction: str | None = None, example: str | N ) -WIKI_REFINE_WRITER_SYSTEM = _build_refine_writer_system(None) - - WIKI_REFINE_WRITER_USER_TEMPLATE = """\ ## Task {action} the following wiki page. @@ -4148,7 +3745,6 @@ async def _run() -> Optional[dict]: "WIKI_PAGE_COMPILE_KWD", "WIKI_DRAFT_COMPILE_KWD", "wiki_map_from_chunks", - "wiki_reduce_from_extracts", "wiki_plan_from_reduction", "wiki_refine_from_plan", ] diff --git a/rag/advanced_rag/knowlege_compile/wiki_incremental.py b/rag/advanced_rag/knowlege_compile/wiki_incremental.py index 02392f68b67..c7535aa0e5d 100644 --- a/rag/advanced_rag/knowlege_compile/wiki_incremental.py +++ b/rag/advanced_rag/knowlege_compile/wiki_incremental.py @@ -521,56 +521,6 @@ def _build_canonical_entity_doc( return doc -async def _save_canonical_entity( - tenant_id: str, - kb_id: str, - entity_name: str, - entity_type: str, - aliases: list[str], - source_doc_ids: list[str], - claim_count: int, - embedding: list[float] | None = None, - source_chunk_ids: list[str] | None = None, -) -> None: - """Insert or update a canonical entity row.""" - index = search.index_name(tenant_id) - doc = _build_canonical_entity_doc( - tenant_id, - kb_id, - entity_name, - entity_type, - aliases, - source_doc_ids, - claim_count, - embedding, - source_chunk_ids, - ) - - condition = {"compile_kwd": [WIKI_CANONICAL_ENTITY_COMPILE_KWD], "entity_kwd": [entity_name]} - existing = await thread_pool_exec( - settings.docStoreConn.search, - ["entity_kwd"], - [], - condition, - [], - OrderByExpr(), - 0, - 1, - index, - [kb_id], - ) - if settings.docStoreConn.get_fields(existing, ["entity_kwd"]): - await thread_pool_exec( - settings.docStoreConn.update, - {"compile_kwd": [WIKI_CANONICAL_ENTITY_COMPILE_KWD], "entity_kwd": entity_name}, - doc, - index, - kb_id, - ) - else: - await thread_pool_exec(settings.docStoreConn.insert, [doc], index, kb_id) - - async def _update_canonical_entity( tenant_id: str, kb_id: str, @@ -1935,24 +1885,6 @@ async def _wiki_load_doc_page_source( return None -async def _wiki_delete_doc_page_source( - tenant_id: str, - kb_id: str, - doc_id: str, -) -> None: - """Delete doc_page_source record when a document is removed.""" - index = search.index_name(tenant_id) - await thread_pool_exec( - settings.docStoreConn.delete, - { - "compile_kwd": [WIKI_DOC_PAGE_SOURCE_COMPILE_KWD], - "doc_id": [doc_id], - }, - index, - kb_id, - ) - - # ----- Mode A: no-plan REFINE ----------------------------------------------- @@ -4805,191 +4737,12 @@ async def _wiki_load_plan_group_members(tenant_id: str, kb_id: str) -> dict[str, return result -async def wiki_handle_document_deleted( - tenant_id: str, - kb_id: str, - doc_id: str, - chat_mdl, - embd_mdl, - mode: str, -) -> dict: - """Clean up wiki pages + canonical entities when a document is deleted. - - Args: - mode: ``topic`` updates plan groups; ``entity`` does not. - - Returns: {pages_modified, pages_deleted, errors} - """ - summary = {"pages_modified": 0, "pages_deleted": 0, "errors": []} - - # Step 1: Update canonical entity index (decrement claim_count) - dps = await _wiki_load_doc_page_source(tenant_id, kb_id, doc_id) - if not dps: - return summary - - entity_names = dps.get("entity_names", []) - if entity_names: - canonical_index = await _load_canonical_entities(tenant_id, kb_id) - for ename in entity_names: - centry = canonical_index.get(ename) - if centry: - src_ids = centry.get("source_doc_ids", []) - if isinstance(src_ids, str): - try: - src_ids = json.loads(src_ids) if src_ids else [] - except (json.JSONDecodeError, TypeError): - src_ids = [] - if doc_id in src_ids: - src_ids.remove(doc_id) - - if not src_ids: - await _delete_canonical_entity(tenant_id, kb_id, ename) - else: - # Keep existing mention_count_int; the next REFINE phase - # will recalculate claims precisely from wiki pages. - # Removing the doc_id from source_doc_ids prevents future - # incremental runs from re-tracking this deletion. - await _save_canonical_entity( - tenant_id, - kb_id, - ename, - centry.get("entity_type_kwd", "entity"), - centry.get("aliases", []), - src_ids, - centry.get("mention_count_int", len(src_ids)), - source_chunk_ids=centry.get("source_chunk_ids", []), - ) - - affected_page_ids = dps.get("page_ids", []) - if not affected_page_ids: - return summary - - # Step 2: Update wiki pages - all_existing_pages = await _search_existing_pages( - tenant_id, - kb_id, - ["slug_kwd", "title_kwd", "md_with_weight", "claims", "source_doc_ids", "page_version_int", "entity_names_kwd", "page_type_kwd", "topic_kwd"], - ) - - for page_id in affected_page_ids: - try: - existing = all_existing_pages.get(page_id) - if not existing: - continue - - source_doc_ids = existing.get("source_doc_ids", []) - if isinstance(source_doc_ids, str): - source_doc_ids = json.loads(source_doc_ids) if source_doc_ids else [] - - if doc_id in source_doc_ids: - source_doc_ids.remove(doc_id) - - page_type = existing.get("page_type_kwd", "concept" if mode == "entity" else "entity") - - if not source_doc_ids: - await _wiki_refine_page( - mode="delete", - page_id=page_id, - page_title=existing.get("title_kwd", page_id), - existing_page=existing, - page_type_kwd=page_type, - additions=None, - retractions=None, - source_chunks=[], - claims=[], - available_pages=[], - contextual_hints="", - chat_mdl=chat_mdl, - embd_mdl=embd_mdl, - tenant_id=tenant_id, - kb_id=kb_id, - page_version=existing.get("page_version_int", 0), - source_doc_ids=source_doc_ids, - ) - summary["pages_deleted"] += 1 - else: - existing_claims = existing.get("claims", []) - if isinstance(existing_claims, str): - existing_claims = json.loads(existing_claims) if existing_claims else [] - - retractions = [c for c in existing_claims if c.get("source_doc_id") == doc_id] - retained = [c for c in existing_claims if c.get("source_doc_id") != doc_id] - - await _wiki_refine_page( - mode="modify", - page_id=page_id, - page_title=existing.get("title_kwd", page_id), - existing_page=existing, - page_type_kwd=page_type, - additions=[], - retractions=retractions, - source_chunks=[], - claims=retained, - available_pages=list(all_existing_pages.keys()), - contextual_hints=_wiki_build_contextual_hints(page_id, existing, {}), - chat_mdl=chat_mdl, - embd_mdl=embd_mdl, - tenant_id=tenant_id, - kb_id=kb_id, - page_version=existing.get("page_version_int", 0), - ) - summary["pages_modified"] += 1 - - if mode == "topic": - plan_condition = { - "compile_kwd": [WIKI_PLAN_GROUP_COMPILE_KWD], - "page_id": [page_id], - } - index = search.index_name(tenant_id) - res_pg = await thread_pool_exec( - settings.docStoreConn.search, - ["entity_names", "source_doc_ids"], - [], - plan_condition, - [], - OrderByExpr(), - 0, - 1, - index, - [kb_id], - ) - pg_map = settings.docStoreConn.get_fields(res_pg, ["entity_names", "source_doc_ids"]) - for pg_row in pg_map.values(): - pg_src_ids = pg_row.get("source_doc_ids", []) - if isinstance(pg_src_ids, str): - pg_src_ids = json.loads(pg_src_ids) - if doc_id in pg_src_ids: - pg_src_ids.remove(doc_id) - await _wiki_update_plan_group( - tenant_id, - kb_id, - page_id, - entity_names=json.loads(pg_row.get("entity_names", "[]")) if isinstance(pg_row.get("entity_names"), str) else pg_row.get("entity_names", []), - page_version=existing.get("page_version_int", 0), - ) - break - - except Exception: - logging.exception("wiki: document deletion cleanup failed for page=%s doc=%s", page_id, doc_id) - summary["errors"].append(f"CLEANUP_FAILED:{page_id}") - - await _wiki_delete_doc_page_source(tenant_id, kb_id, doc_id) - - try: - await _wiki_finalize(tenant_id, kb_id, embd_mdl) - except Exception: - logging.exception("wiki: FINALIZE after deletion failed") - - return summary - - __all__ = [ "WIKI_PAGE_COMPILE_KWD", "WIKI_PLAN_GROUP_COMPILE_KWD", "WIKI_DOC_PAGE_SOURCE_COMPILE_KWD", "WIKI_CANONICAL_ENTITY_COMPILE_KWD", "wiki_compile_incremental", - "wiki_handle_document_deleted", "_wiki_reduce_entity", "_wiki_reduce_batch", "_wiki_match_entities", @@ -4998,7 +4751,6 @@ async def wiki_handle_document_deleted( "_wiki_refine_page", "_wiki_update_doc_page_source", "_load_canonical_entities", - "_save_canonical_entity", "_delete_canonical_entity", "_extract_raw_entities", ] diff --git a/rag/svr/task_executor_refactor/chunk_post_processor.py b/rag/svr/task_executor_refactor/chunk_post_processor.py index 4480e7983f2..492773406c0 100644 --- a/rag/svr/task_executor_refactor/chunk_post_processor.py +++ b/rag/svr/task_executor_refactor/chunk_post_processor.py @@ -355,19 +355,6 @@ async def doc_content_tagging(chat_mdl, d, topn_tags): ctx.progress_cb(msg=f"Tagging {len(docs)} chunks completed in {timer() - st:.2f}s") -def count_with_key(docs: list[dict], key: str) -> int: - """Count docs that have a specific key. - - Args: - docs: List of chunk dictionaries. - key: The key to check for. - - Returns: - Count of docs that have the key. - """ - return sum(1 for d in docs if d.get(key)) - - # ===================================================================== # Document post-chunking pipeline # --------------------------------------------------------------------- diff --git a/rag/svr/task_executor_refactor/dataset_wiki_generator.py b/rag/svr/task_executor_refactor/dataset_wiki_generator.py index fbd827391db..312800c4087 100644 --- a/rag/svr/task_executor_refactor/dataset_wiki_generator.py +++ b/rag/svr/task_executor_refactor/dataset_wiki_generator.py @@ -14,19 +14,12 @@ # limitations under the License. # -"""KB-wide wiki / artifact compilation. +"""KB-wide incremental wiki / artifact compilation. -Extracted from ``rag.svr.task_executor_refactor.task_handler`` where the -same pipeline previously lived as a set of ``_wiki_*`` / ``_persist_wiki_*`` -methods and one ``_run_wiki`` orchestrator. The public entry point is -:func:`run_wiki`. - -The pipeline runs MAP per (doc, template) — each MAP call resumes from -its own ``wiki_map_extract`` ES rows — then REDUCE / PLAN / REFINE -KB-wide via ``rag.advanced_rag.knowlege_compile.wiki``. Refined pages -land in ES as searchable ``wiki_page`` rows, one -``wiki_page_topic`` row per topic, and ``wiki_entity`` / -``wiki_relation`` rows for the dataset Artifact tab's canvas graph. +The public entry point is :func:`run_wiki_incremental`. MAP extraction and +its resume state live in ``rag.advanced_rag.knowlege_compile.wiki``; the +incremental REDUCE / REFINE / FINALIZE stages live in +``rag.advanced_rag.knowlege_compile.wiki_incremental``. Design notes: @@ -36,9 +29,6 @@ ``parser_config.compilation_template_group_id`` to a template list via the shared parser-config helper and ``CompilationTemplateGroupService.resolve_template_ids``. -* The persistence helpers (``persist_wiki_pages`` etc.) are - exposed at module level for testing but are only called from - :func:`run_wiki` in production. """ from __future__ import annotations @@ -46,8 +36,7 @@ import asyncio import json import logging -import re -from typing import AsyncIterator, Callable, Dict, List, Optional +from typing import AsyncIterator, Callable, Dict, List import xxhash @@ -66,9 +55,6 @@ _wiki_load_map_extracts_for_state, _wiki_scan_current_chunk_state, wiki_map_from_chunks, - wiki_plan_from_reduction, - wiki_reduce_from_extracts, - wiki_refine_from_plan, ) from rag.svr.task_executor_refactor.task_context import TaskContext @@ -93,10 +79,6 @@ # configured worker and pending limits, this bounds in-memory MAP work. WIKI_MAP_QUEUE_SIZE = 5 -# REFINE pages are independent. Keep enough page workers to feed the shared -# pool; the pool itself still caps actual LLM requests at the configured size. -WIKI_REFINE_WORKERS = env_int("WIKI_REFINE_WORKERS", 4, minimum=1) - def _create_wiki_llm_pool(progress: Callable) -> LLMCallPool: def _on_concurrency_change(old: int, new: int, reason: str) -> None: @@ -123,23 +105,16 @@ def _on_error(label: str, context: str | None, error_type: str) -> None: # ``wiki_page`` row the UI deep-links into. WIKI_GRAPH_MAX_CHUNK_IDS_PER_NODE = 64 -# Title + comments stamped on every ``wiki_commit`` row produced by -# :func:`run_wiki`'s regeneration path (as opposed to the dialog-edit -# path, which carries the user's own title/comments). -WIKI_REGEN_COMMIT_TITLE = "Regenerated by artifact compilation" -WIKI_REGEN_COMMIT_COMMENTS_TEMPLATE = "Auto-update via run_wiki (action={action})" -WIKI_MAP_COMPILE_KWD = "wiki_map_extract" WIKI_REDUCE_COMPILE_KWD = "wiki_reduce_result" WIKI_PLAN_COMPILE_KWD = "wiki_compilation_plan" WIKI_DRAFT_COMPILE_KWD = "wiki_page_draft" WIKI_PAGE_COMPILE_KWD = "wiki_page" -WIKI_PAGE_TOPIC_COMPILE_KWD = "wiki_page_topic" WIKI_DERIVED_COMPILE_KWDS = ( WIKI_REDUCE_COMPILE_KWD, WIKI_PLAN_COMPILE_KWD, WIKI_DRAFT_COMPILE_KWD, WIKI_PAGE_COMPILE_KWD, - WIKI_PAGE_TOPIC_COMPILE_KWD, + "wiki_page_topic", "wiki_entity", "wiki_relation", "wiki_page_graph", @@ -335,8 +310,7 @@ def _wiki_eligible_docs(all_docs, tenant_id: str, skip_doc_ids=None) -> list[tup pipeline path is essential for docs uploaded/parsed through a pipeline, which carry their compilation templates on the pipeline's compiler rather than in ``parser_config``. Returns ``(doc, template_id)`` for the first wiki template - matched per doc. Shared by :func:`run_wiki` and :func:`run_wiki_incremental` - so their eligibility can't drift. + matched per doc. """ from api.db.services.compilation_template_service import CompilationTemplateService from api.apps.restful_apis.chunk_api import _compilation_template_kind @@ -704,374 +678,6 @@ async def _wiki_reset_all_wiki_state(tenant_id: str, kb_id: str) -> None: logging.exception("wiki: failed to reset all wiki state for kb=%s", kb_id) -def _wiki_topic_from_page(page: Dict, fallback: str = "") -> str: - for key in ("topic", "title", "page_type"): - value = page.get(key) - if isinstance(value, str) and value.strip(): - return value.strip() - return fallback.strip() - - -def _wiki_topic_slug(topic: str) -> str: - slug = re.sub(r"[^a-z0-9]+", "-", topic.lower()).strip("-") - if not slug: - slug = xxhash.xxh64(topic.encode("utf-8", "surrogatepass")).hexdigest()[:12] - return f"topic/{slug[:80]}" - - -async def _ensure_wiki_topic_rows( - ctx: TaskContext, - index: str, - kb_id_str: str, - topics_by_name: dict[str, str], - topic_doc_ids: dict[str, list[str]] | None = None, -) -> None: - if not topics_by_name: - return - - from common.doc_store.doc_store_base import OrderByExpr - from rag.nlp import rag_tokenizer - - topic_doc_ids = topic_doc_ids or {} - topics = list(topics_by_name.keys()) - existing: set[str] = set() - try: - res = await thread_pool_exec( - settings.docStoreConn.search, - ["id", "topic_kwd"], - [], - { - "compile_kwd": [WIKI_PAGE_TOPIC_COMPILE_KWD], - "topic_kwd": topics, - }, - [], - OrderByExpr(), - 0, - max(len(topics), 1), - index, - [ctx.kb_id], - ) - field_map = settings.docStoreConn.get_fields(res, ["id", "topic_kwd"]) - for row in (field_map or {}).values(): - raw = row.get("topic_kwd") - if isinstance(raw, list): - existing.update(t for t in raw if isinstance(t, str) and t) - elif isinstance(raw, str) and raw: - existing.add(raw) - except Exception: - logging.exception( - "wiki_persist: topic existence read failed for kb=%s; inserting stable topic ids", - kb_id_str, - ) - - rows: list[dict] = [] - for topic, slug in topics_by_name.items(): - if topic in existing: - # Topic row already present — refresh only its doc provenance so - # delete-time ref-counting stays accurate as new docs contribute - # to (or stop contributing to) the topic across recompiles. - doc_ids = topic_doc_ids.get(topic) or [] - try: - await thread_pool_exec( - settings.docStoreConn.update, - {"compile_kwd": WIKI_PAGE_TOPIC_COMPILE_KWD, "topic_kwd": topic}, - {"source_doc_ids": list(doc_ids)}, - index, - ctx.kb_id, - ) - except Exception: - logging.exception( - "wiki_persist: topic provenance update failed for kb=%s topic=%s", - kb_id_str, - topic, - ) - continue - topic_id = xxhash.xxh64( - f"{kb_id_str}:{WIKI_PAGE_TOPIC_COMPILE_KWD}:{topic}".encode( - "utf-8", - "surrogatepass", - ), - ).hexdigest() - content_ltks = rag_tokenizer.tokenize(topic) - rows.append( - { - "id": topic_id, - "kb_id": kb_id_str, - "doc_id": kb_id_str, - "compile_kwd": WIKI_PAGE_TOPIC_COMPILE_KWD, - "topic_kwd": topic, - "title_kwd": topic, - "slug_kwd": slug, - "source_doc_ids": list(topic_doc_ids.get(topic) or []), - "content_with_weight": topic, - "content_ltks": content_ltks, - "content_sm_ltks": rag_tokenizer.fine_grained_tokenize(content_ltks), - "available_int": 1, - } - ) - - if rows: - await thread_pool_exec(settings.docStoreConn.insert, rows, index, ctx.kb_id) - - -# ----- persistence --------------------------------------------------- - - -async def persist_wiki_pages( - ctx: TaskContext, - pages: List[Dict], - embd_mdl, -) -> None: - """Insert one doc-store row per generated artifact page using the - knowledge-compilation schema: - - id xxh64(kb_id + ":" + slug) - compile_kwd "wiki_page" - slug_kwd page.slug - title_kwd page.title - page_type_kwd page.page_type - topic_kwd page.topic - entity_names_kwd page.entity_names - outlinks_kwd page.outlinks - related_kb_pages_kwd page.related_kb_pages - source_chunk_ids page.source_chunk_ids - source_doc_ids page.source_doc_ids - kb_id ctx.kb_id - content_with_weight rendered markdown - content_ltks / - content_sm_ltks tokenize(content_md + summary) - q__vec embed(summary) - - ``action`` is intentionally not stored — it's a planner artifact - and has no meaning post-write. - """ - if not pages: - return - - from rag.nlp import rag_tokenizer - from common.doc_store.doc_store_base import OrderByExpr - from api.db.services.file_commit_service import ( - FileCommitService as WikiCommitService, - ) - - index = search.index_name(ctx.tenant_id) - kb_id_str = str(ctx.kb_id) - - # Capture the prior rendered content for every slug we're about to - # overwrite, so the per-page commit row downstream has a real diff - # baseline. Prefer md_with_weight because that is the canonical field - # consumed by the Wiki page API, with content_with_weight as fallback. - # Single batch read by slug_kwd IN [...] — one round-trip regardless of - # page count. Failures here degrade gracefully. - target_slugs: list[str] = [(p.get("slug") or "").strip() for p in pages if isinstance(p.get("slug"), str) and p.get("slug")] - prior_by_slug: dict[str, str] = {} - if target_slugs: - try: - res = await thread_pool_exec( - settings.docStoreConn.search, - ["id", "slug_kwd", "md_with_weight", "content_with_weight"], - [], - {"compile_kwd": [WIKI_PAGE_COMPILE_KWD], "slug_kwd": list(target_slugs)}, - [], - OrderByExpr(), - 0, - max(len(target_slugs), 1), - index, - [ctx.kb_id], - ) - field_map = settings.docStoreConn.get_fields( - res, - ["id", "slug_kwd", "md_with_weight", "content_with_weight"], - ) - for row in (field_map or {}).values(): - s = row.get("slug_kwd") - c = row.get("md_with_weight") or row.get("content_with_weight") - if isinstance(s, str) and isinstance(c, str): - prior_by_slug[s] = c - except Exception: - logging.exception( - "wiki_persist: prior-content read failed for kb=%s; commit audit will treat all pages as creations", - kb_id_str, - ) - - # Batch the summary embeddings in one model call. Empty strings are - # swapped for a single space so the encoder doesn't reject them — - # they still yield a vector but contribute nothing meaningful. - summaries = [(p.get("summary") or "").strip() for p in pages] - embed_inputs = [s if s else " " for s in summaries] - try: - embeddings, _ = await thread_pool_exec(embd_mdl.encode, embed_inputs) - except Exception: - logging.exception( - "wiki_persist: summary embedding batch failed for kb=%s", - kb_id_str, - ) - return - try: - n_emb = len(embeddings) if embeddings is not None else 0 - except TypeError: - n_emb = 0 - if n_emb != len(pages): - logging.warning( - "wiki_persist: embedding count %d != pages %d for kb=%s; aborting", - n_emb, - len(pages), - kb_id_str, - ) - return - - rows: List[Dict] = [] - topics_by_name: dict[str, str] = {} - # Per-topic union of contributing doc ids, so topic rows can be - # reference-counted at document-delete time like every other product. - topic_doc_ids: dict[str, list[str]] = {} - for page, vec in zip(pages, embeddings): - slug = page.get("slug") or "" - if not slug: - continue - title = page.get("title") or slug - topic = _wiki_topic_from_page(page, title) - summary = page.get("summary") or "" - content_md = page.get("content_md_rendered") or page.get("content_md") or page.get("content_md_raw") or "" - - vec_list = vec.tolist() if hasattr(vec, "tolist") else list(vec) - if not vec_list: - logging.warning( - "wiki_persist: empty embedding for slug=%s; skipping", - slug, - ) - continue - - text_for_search = (content_md + "\n\n" + summary).strip() - content_ltks = rag_tokenizer.tokenize(text_for_search) if text_for_search else "" - content_sm_ltks = rag_tokenizer.fine_grained_tokenize(content_ltks) if content_ltks else "" - - row_id = xxhash.xxh64( - f"{kb_id_str}:{slug}".encode("utf-8", "surrogatepass"), - ).hexdigest() - - rows.append( - { - "id": row_id, - "kb_id": kb_id_str, - "doc_id": kb_id_str, # sentinel; KB-scoped row, real provenance in source_doc_ids - "compile_kwd": WIKI_PAGE_COMPILE_KWD, - "slug_kwd": slug, - "title_kwd": title, - "page_type_kwd": page.get("page_type") or "concept", - "topic_kwd": topic, - "entity_names_kwd": list(page.get("entity_names") or []), - "outlinks_kwd": list(page.get("outlinks") or []), - "outlinks_int": len(list(page.get("outlinks") or [])), - "related_kb_pages_kwd": list(page.get("related_kb_pages") or []), - "source_chunk_ids": list(page.get("source_chunk_ids") or []), - "source_doc_ids": list(page.get("source_doc_ids") or []), - "md_with_weight": content_md, - "content_with_weight": content_md, - # Summary kept verbatim alongside the rendered body so the - # viewer can render it as a distinct (smaller) block above - # the main content. - "summary_with_weight": summary, - "content_ltks": content_ltks, - "content_sm_ltks": content_sm_ltks, - f"q_{len(vec_list)}_vec": vec_list, - "available_int": 1, - } - ) - if topic: - topics_by_name.setdefault(topic, _wiki_topic_slug(topic)) - bucket = topic_doc_ids.setdefault(topic, []) - seen_bucket = set(bucket) - for d in page.get("source_doc_ids") or []: - if isinstance(d, str) and d and d not in seen_bucket: - seen_bucket.add(d) - bucket.append(d) - - if not rows: - return - - try: - insert_errors = await thread_pool_exec(settings.docStoreConn.insert, rows, index, ctx.kb_id) - except Exception: - logging.exception( - "wiki_persist: bulk insert failed for kb=%s (rows=%d)", - kb_id_str, - len(rows), - ) - return - - if insert_errors: - logging.warning( - "wiki_persist: page insert returned %d error(s) for kb=%s", - len(insert_errors), - kb_id_str, - ) - - # Verify the rows that are actually visible after the bulk operation. Some - # backends can report partial bulk failures without raising, so recording a - # version for every input page would create history for pages that were not - # persisted. - try: - persisted_res = await thread_pool_exec( - settings.docStoreConn.search, - ["id", "slug_kwd"], - [], - {"compile_kwd": [WIKI_PAGE_COMPILE_KWD], "id": [row["id"] for row in rows]}, - [], - OrderByExpr(), - 0, - len(rows), - index, - [ctx.kb_id], - ) - persisted_fields = settings.docStoreConn.get_fields(persisted_res, ["id", "slug_kwd"]) - persisted_page_slugs = {row.get("slug_kwd") for row in (persisted_fields or {}).values() if isinstance(row.get("slug_kwd"), str)} - except Exception: - logging.exception( - "wiki_persist: failed to verify persisted pages for kb=%s; skipping history records", - kb_id_str, - ) - return - - if topics_by_name: - try: - await _ensure_wiki_topic_rows(ctx, index, kb_id_str, topics_by_name, topic_doc_ids) - except Exception: - logging.exception( - "wiki_persist: topic row insert failed for kb=%s", - kb_id_str, - ) - - # Audit trail: one ArtifactCommit row per page whose rendered - # content actually changed (record_edit silently skips empty diffs). - # Best-effort — commit failures log but don't fail the artifact - # compile. - for page in pages: - slug = (page.get("slug") or "").strip() - if not slug or slug not in persisted_page_slugs: - continue - content_md = page.get("content_md_rendered") or page.get("content_md") or page.get("content_md_raw") or "" - action = (page.get("action") or "CREATE").upper() - try: - WikiCommitService.record_page_edit( - tenant_id=ctx.tenant_id, - kb_id=ctx.kb_id, - page_type=page.get("page_type") or "concept", - slug=slug, - content_before=prior_by_slug.get(slug, ""), - content_after=content_md, - title=WIKI_REGEN_COMMIT_TITLE, - comments=WIKI_REGEN_COMMIT_COMMENTS_TEMPLATE.format(action=action), - user_id=None, # system commit — no human author - ) - except Exception: - logging.exception( - "wiki_persist: commit record failed for kb=%s slug=%s", - kb_id_str, - slug, - ) - - def build_wiki_page_graph( pages: List[Dict], kb_id: str, @@ -1288,342 +894,6 @@ async def _sweep_legacy_blob() -> None: ) -# ----- main entry ---------------------------------------------------- - - -async def run_wiki( - ctx: TaskContext, - embedding_model, - load_chunks_for_doc: Callable[..., AsyncIterator[list[dict]]], -) -> None: - """KB-wide artifact compilation task. - - Runs after the user clicks the "Artifact" button in the dataset - generate menu. Iterates every doc in the KB whose parser_config - has a compilation template group resolving to an artifacts-kind - child, runs MAP per-doc (which uses ES-stored resume rows to skip - chunks already processed in a previous run), then runs REDUCE / - PLAN / REFINE KB-wide and persists pages. - - Batching: each MAP call uses ``batch_size_cap=8`` and - ``window_fraction=0.5`` — i.e. roll over to a new batch when the - current batch reaches 8 chunks OR its accumulated token count - exceeds 50% of the chat model's ``max_length``. - """ - # Local imports so this module doesn't drag in the API service - # layer at import time — that's a source of circular-import risk - # given how much lives under ``api.db.services``. - from api.db.services.document_service import DocumentService - from api.db.services.knowledgebase_service import KnowledgebaseService - from api.db.services.compilation_template_service import CompilationTemplateService - from api.db.services.llm_service import LLMBundle - from api.db.joint_services.tenant_model_service import resolve_model_config - - progress = ctx.progress_cb - map_llm_pool = _create_wiki_llm_pool(progress) - progress(0.0, "Loading documents for wiki compilation...") - - # 1. Resolve KB metadata for PLAN. - ok, kb = KnowledgebaseService.get_by_id(ctx.kb_id) - if not ok: - progress(-1, f"KB {ctx.kb_id} not found.") - return - kb_name = kb.name - kb_description = kb.description - - # 2. Pick docs eligible for artifact compilation (those whose - # configured template group resolves to at least one artifacts-kind - # child). The frontend Artifact button targets the KB, but the - # per-doc opt-in is what gates inclusion. - all_docs, _ = await thread_pool_exec( - DocumentService.get_by_kb_id, - kb_id=ctx.kb_id, - page_number=0, - items_per_page=0, - orderby="create_time", - desc=False, - keywords="", - run_status=[], - types=[], - suffix=[], - ) - current_doc_ids = {str(d.get("id")) for d in all_docs or [] if d.get("id")} - existing_map_doc_ids = await _wiki_existing_map_doc_ids(ctx.tenant_id, ctx.kb_id) - deleted_doc_ids = existing_map_doc_ids - current_doc_ids - if deleted_doc_ids: - progress( - 0.02, - f"Removing stale wiki state for {len(deleted_doc_ids)} deleted document(s)...", - ) - await _wiki_delete_deleted_doc_state( - ctx.tenant_id, - ctx.kb_id, - deleted_doc_ids, - ) - - eligible = _wiki_eligible_docs(all_docs, ctx.tenant_id) - if not eligible: - progress(1.0, _wiki_empty_eligible_message(all_docs)) - return - pipeline_chat_llm_ids = _validate_wiki_eligible_docs(eligible) - - # 3. Resolve chat models. MAP is per document, so each document uses - # its pipeline Compiler's ``llm_id``. REDUCE / PLAN / REFINE are - # KB-wide and need exactly one model — we pick the first eligible - # pipeline Compiler's ``llm_id`` as the canonical KB chat model. - llm_bundle_cache: dict[str, LLMBundle] = {} - - def _bundle_for(llm_id: str) -> LLMBundle: - key = llm_id.strip() - cached = llm_bundle_cache.get(key) - if cached is not None: - return cached - cfg = resolve_model_config( - ctx.tenant_id, - LLMType.CHAT, - key, - ) - bundle = LLMBundle(ctx.tenant_id, cfg, lang=ctx.language) - llm_bundle_cache[key] = bundle - return bundle - - def _stage_cb(prefix: str): - def _cb(*args, **kwargs): - try: - if args and isinstance(args[0], (int, float)): - msg = args[1] if len(args) > 1 else kwargs.get("msg", "") - progress(msg=f"{prefix} {msg}") - else: - msg = kwargs.get("msg") or (args[0] if args else "") - progress(msg=f"{prefix} {msg}") - except Exception: - logging.exception("wiki: progress callback failed") - - return _cb - - # 4. MAP per eligible doc. Historical extraction versions are keyed by - # doc_id + chunk_id + input hash, so unchanged or reverted content can - # reuse prior LLM output. - # - # Resolve templates before starting workers so the first eligible - # template remains the deterministic source for KB-wide REDUCE/PLAN/ - # REFINE, independent of which document worker happens to finish first. - resolved_eligible: list[tuple[dict, str, dict]] = [] - for doc, template_id in eligible: - template = CompilationTemplateService.get_saved(template_id, ctx.tenant_id) - if not template: - logging.warning( - "artifact: template %s not found for doc %s; skipping", - template_id, - doc["id"], - ) - continue - resolved_eligible.append((doc, template_id, template.get("config") or {})) - - if not resolved_eligible: - progress(1.0, "No valid templates resolved for wiki compilation.") - return - - # ``kb_chat_llm_id`` is captured from the first eligible pipeline and - # used as the canonical chat model for KB-wide REDUCE/PLAN/REFINE. - # Writer instructions and page examples follow the same first-template- - # wins rule. - first_doc = resolved_eligible[0][0] - first_parser_cfg = resolved_eligible[0][2] - first_parser_cfg = first_parser_cfg if isinstance(first_parser_cfg, dict) else {} - kb_chat_llm_id = pipeline_chat_llm_ids[str(first_doc.get("id") or "")] - first_instruction = first_parser_cfg.get("instruction") - first_example = first_parser_cfg.get("example") - kb_writer_instruction: Optional[str] = first_instruction if isinstance(first_instruction, str) and first_instruction.strip() else None - kb_writer_example: Optional[str] = first_example if isinstance(first_example, str) and first_example.strip() else None - n_docs = len(resolved_eligible) - map_queue: asyncio.Queue = asyncio.Queue(maxsize=WIKI_MAP_QUEUE_SIZE) - doc_stats = { - i: { - "doc": doc, - "batch_count": 0, - "saw_any": False, - "status": "ok", - "agg": {"entities": 0, "concepts": 0, "claims": 0, "relations": 0}, - "map": {"requested": 0, "cache_hits": 0, "extracted": 0}, - } - for i, (doc, _, _) in enumerate(resolved_eligible) - } - - async def _produce_document(i: int, job: tuple[dict, str, dict]) -> None: - doc, template_id, parser_cfg = job - doc_id = doc["id"] - stats = doc_stats[i] - progress(0.05 + 0.6 * (i / n_docs), f"MAP {i + 1}/{n_docs}: {doc.get('name', doc_id)}") - try: - async for batch in load_chunks_for_doc( - ctx.tenant_id, - ctx.kb_id, - doc_id, - batch_size=WIKI_MAP_BATCH_CHUNKS, - ): - stats["saw_any"] = True - stats["batch_count"] += 1 - await map_queue.put((i, doc, template_id, parser_cfg, batch, stats["batch_count"])) - except Exception: - logging.exception("wiki: loading MAP chunks failed for doc %s", doc_id) - stats["status"] = "error" - - async def _map_worker() -> None: - while True: - item = await map_queue.get() - try: - if item is None: - return - i, doc, template_id, parser_cfg, batch, batch_no = item - doc_id = doc["id"] - stats = doc_stats[i] - map_llm_id = pipeline_chat_llm_ids[str(doc_id)] - phase1 = await wiki_map_from_chunks( - chunks=batch, - chat_mdl=map_llm_pool.wrap( - _bundle_for(map_llm_id), - priority=30, - label=f"wiki-map:{doc_id}", - context=f"{ctx.kb_id}:{doc_id}:map", - ), - embd_mdl=embedding_model, - doc_id=doc_id, - tenant_id=ctx.tenant_id, - kb_id=ctx.kb_id, - language=ctx.language, - callback=_stage_cb(f"[wiki MAP {i + 1}/{n_docs} b{batch_no}]"), - parser_config=parser_cfg, - batch_size_cap=8, - window_fraction=0.5, - # Match the shared pool width. The pool is the single - # admission/concurrency control for actual MAP LLM calls. - max_workers=WIKI_MAP_LLM_POOL_SIZE, - ) - for key in stats["agg"]: - stats["agg"][key] += len(phase1.get(key) or []) - meta = phase1.get("_meta") or {} - if isinstance(meta, dict): - for key in stats["map"]: - stats["map"][key] += int(meta.get(key, 0) or 0) - except Exception: - logging.exception( - "wiki: MAP failed for doc %s batch %d", - doc_id, - batch_no, - ) - stats["status"] = "error" - finally: - map_queue.task_done() - - producers = [asyncio.create_task(_produce_document(i, job)) for i, job in enumerate(resolved_eligible)] - workers = [asyncio.create_task(_map_worker()) for _ in range(WIKI_MAP_LLM_POOL_SIZE)] - try: - await asyncio.gather(*producers) - await map_queue.join() - finally: - for task in producers + workers: - if not task.done(): - task.cancel() - await asyncio.gather(*producers, *workers, return_exceptions=True) - - for i, stats in doc_stats.items(): - doc = stats["doc"] - doc_id = doc["id"] - if not stats["saw_any"] and stats["status"] == "ok": - stats["status"] = "empty" - logging.info("wiki: no chunks for doc %s; skipping", doc_id) - agg = stats["agg"] - map_stats = stats["map"] - logging.info( - "wiki: MAP doc=%s entities=%d concepts=%d claims=%d relations=%d (batches=%d, requested=%d cache_hits=%d extracted=%d)", - doc_id, - agg["entities"], - agg["concepts"], - agg["claims"], - agg["relations"], - stats["batch_count"], - map_stats["requested"], - map_stats["cache_hits"], - map_stats["extracted"], - ) - - # 5. REDUCE / PLAN / REFINE KB-wide. Each phase has its own - # input_hash gate (REDUCE keys off the MAP-state hash, PLAN off - # REDUCE's hash, REFINE off PLAN's hash) so re-runs without an - # upstream delta short-circuit at the cache layer. - kb_chat_mdl = _bundle_for(kb_chat_llm_id) - - try: - progress(0.65, "Reducing extracts KB-wide...") - await wiki_reduce_from_extracts( - chat_mdl=map_llm_pool.wrap( - kb_chat_mdl, - priority=20, - label="wiki-reduce", - context=f"{ctx.kb_id}:reduce", - ), - embd_mdl=embedding_model, - tenant_id=ctx.tenant_id, - kb_id=ctx.kb_id, - callback=_stage_cb("[wiki REDUCE]"), - ) - - progress(0.75, "Planning wiki pages...") - await wiki_plan_from_reduction( - chat_mdl=map_llm_pool.wrap( - kb_chat_mdl, - priority=20, - label="wiki-plan", - context=f"{ctx.kb_id}:plan", - ), - embd_mdl=embedding_model, - tenant_id=ctx.tenant_id, - kb_id=ctx.kb_id, - kb_name=kb_name, - kb_description=kb_description, - callback=_stage_cb("[wiki PLAN]"), - ) - - progress(0.85, "Refining pages...") - pages = await wiki_refine_from_plan( - chat_mdl=map_llm_pool.wrap( - kb_chat_mdl, - priority=30, - label="wiki-refine", - context=f"{ctx.kb_id}:refine", - ), - embd_mdl=embedding_model, - tenant_id=ctx.tenant_id, - kb_id=ctx.kb_id, - max_workers=WIKI_REFINE_WORKERS, - callback=_stage_cb("[wiki REFINE]"), - instruction=kb_writer_instruction, - example=kb_writer_example, - ) - except Exception: - logging.exception("wiki: REDUCE/PLAN/REFINE failed for kb %s", ctx.kb_id) - progress(-1, "Wiki pipeline failed during REDUCE/PLAN/REFINE.") - return - - # 6. Persist searchable wiki_page rows. - try: - await persist_wiki_pages(ctx=ctx, pages=pages or [], embd_mdl=embedding_model) - except Exception: - logging.exception("wiki: persist failed for kb %s", ctx.kb_id) - - # 7. Materialize the canvas graph from the refined pages. - try: - await persist_wiki_page_graph(ctx=ctx, pages=pages or []) - except Exception: - logging.exception("wiki: page-graph persist failed for kb %s", ctx.kb_id) - - progress(1.0, f"Wiki compiled {len(pages or [])} page(s).") - - -# ----- dual-mode incremental entry point --------------------------------- - - async def run_wiki_incremental( ctx: TaskContext, embedding_model, @@ -1788,7 +1058,7 @@ def _bundle_for(llm_id: str) -> LLMBundle: kb_chat_llm_id = None first_template_found = False - # 4. MAP per doc (same as run_wiki's MAP phase) + # 4. MAP per eligible document. map_queue: asyncio.Queue = asyncio.Queue(maxsize=WIKI_MAP_QUEUE_SIZE) n_docs = len(eligible) diff --git a/test/unit_test/rag/advanced_rag/knowlege_compile/conftest.py b/test/unit_test/rag/advanced_rag/knowlege_compile/conftest.py index f7434c9814b..1f094978c1b 100644 --- a/test/unit_test/rag/advanced_rag/knowlege_compile/conftest.py +++ b/test/unit_test/rag/advanced_rag/knowlege_compile/conftest.py @@ -173,6 +173,7 @@ def _message_fit_in(*args, **kwargs): _common_mod.build_chunk_batches = lambda *a, **k: ([], {}) _common_mod.bulk_dedup_items = lambda items, *a, **k: items _common_mod.ensure_llm_bundle = lambda model: model +_common_mod.env_int = lambda _name, default, **_kwargs: default _common_mod.knowledge_compile_gen_conf = lambda *a, **k: {} _common_mod.run_chunked_pipeline = MagicMock(return_value={}) _common_mod.stable_row_id = lambda *a, **k: "" diff --git a/test/unit_test/rag/svr/task_executor_refactor/test_wiki_empty_eligible_message.py b/test/unit_test/rag/svr/task_executor_refactor/test_wiki_empty_eligible_message.py index 74084d5923b..848889aa696 100644 --- a/test/unit_test/rag/svr/task_executor_refactor/test_wiki_empty_eligible_message.py +++ b/test/unit_test/rag/svr/task_executor_refactor/test_wiki_empty_eligible_message.py @@ -66,6 +66,7 @@ def _stub_module(name, **attrs): "rag", "rag.advanced_rag", "rag.advanced_rag.knowlege_compile", + "rag.advanced_rag.knowlege_compile._common", "rag.nlp", "rag.utils", "rag.utils.es_connection", @@ -112,6 +113,10 @@ def _load_wiki_generator(monkeypatch): # Set __path__ on the knowlege_compile stub so that submodules like # ``structure`` resolve as packages rather than attribute lookups. sys.modules["rag.advanced_rag.knowlege_compile"].__path__ = [os.path.join(_REPO_ROOT, "rag", "advanced_rag", "knowlege_compile")] + _stub_module( + "rag.advanced_rag.knowlege_compile._common", + env_int=lambda _name, default, **_kwargs: default, + ) sys.modules["rag.advanced_rag.knowlege_compile"].structure = ModuleType("rag.advanced_rag.knowlege_compile.structure") sys.modules["rag.advanced_rag.knowlege_compile.structure"] = sys.modules["rag.advanced_rag.knowlege_compile"].structure sys.modules["rag.advanced_rag.knowlege_compile.structure"].LLMCallPool = type("LLMCallPool", (), {}) @@ -126,7 +131,6 @@ def _load_wiki_generator(monkeypatch): _wiki_scan_current_chunk_state=lambda *_args, **_kwargs: [], wiki_map_from_chunks=lambda *_args, **_kwargs: [], wiki_plan_from_reduction=lambda *_args, **_kwargs: [], - wiki_reduce_from_extracts=lambda *_args, **_kwargs: [], wiki_refine_from_plan=lambda *_args, **_kwargs: [], ) _stub_module("rag.nlp", search=ModuleType("rag.nlp.search")) From 289100188d83889cc60a4a4a8e58c362bd600ff5 Mon Sep 17 00:00:00 2001 From: buua436 Date: Fri, 11 Sep 2026 10:17:12 +0800 Subject: [PATCH 093/568] fix: avoid nested compiler pool embedding deadlock (#19486) --- internal/entity/models/base_model.go | 2 +- internal/entity/models/xai.go | 6 ++-- .../knowledge_compiler/structure/structure.go | 28 +++++++++++++++---- .../task/knowledge_compiler_wiring.go | 2 +- 4 files changed, 27 insertions(+), 11 deletions(-) diff --git a/internal/entity/models/base_model.go b/internal/entity/models/base_model.go index a642d097eda..992da05fe1d 100644 --- a/internal/entity/models/base_model.go +++ b/internal/entity/models/base_model.go @@ -466,7 +466,7 @@ func NewDriverHTTPClient(allowPrivate bool) *http.Client { t.MaxIdleConnsPerHost = 10 t.IdleConnTimeout = 90 * time.Second t.DisableCompression = false - t.ResponseHeaderTimeout = 5 * 60 * time.Second + t.ResponseHeaderTimeout = 20 * time.Minute t.TLSHandshakeTimeout = 30 * time.Second var rt http.RoundTripper = t diff --git a/internal/entity/models/xai.go b/internal/entity/models/xai.go index 50d3d338040..00ae4b2b20f 100644 --- a/internal/entity/models/xai.go +++ b/internal/entity/models/xai.go @@ -33,9 +33,9 @@ import ( ) var ( - nonStreamCallTimeout = 300 * time.Second - streamCallTimeout = 10 * time.Minute - longOpCallTimeout = 10 * time.Minute + nonStreamCallTimeout = 20 * time.Minute + streamCallTimeout = 20 * time.Minute + longOpCallTimeout = 20 * time.Minute ) // XAIModel implements ModelDriver for xAI (Grok models) diff --git a/internal/ingestion/component/knowledge_compiler/structure/structure.go b/internal/ingestion/component/knowledge_compiler/structure/structure.go index 60f207564d8..d3af89ad92f 100644 --- a/internal/ingestion/component/knowledge_compiler/structure/structure.go +++ b/internal/ingestion/component/knowledge_compiler/structure/structure.go @@ -84,9 +84,15 @@ func Run(ctx context.Context, deps common.Deps, param common.Param, inputs commo // ---- MAP ---- batches := common.PackBatches(inputs.Chunks, structureBatchTokenBudget, deps.Tokenizer) + type extractedBatch struct { + nodes, edges []map[string]any + batchIDs []string + } + extracted := make([]extractedBatch, len(batches)) perBatch := make([][]common.Product, len(batches)) jobs := make([]func() error, 0, len(batches)) for i, batch := range batches { + i, batch := i, batch jobs = append(jobs, func() error { packed, batchIDs := PackBatch(batch) if len(batchIDs) == 0 { @@ -96,12 +102,9 @@ func Run(ctx context.Context, deps common.Deps, param common.Param, inputs commo if err != nil { return err } - rows, err := buildRows(ctx, deps, cfg, nodes, edges, batchIDs) - if err != nil { - return err - } - // Distinct slice index per batch → no cross-goroutine contention. - perBatch[i] = rows + // Keep embedding out of the compiler-pool worker. buildRows calls + // Embed.Encode, which may submit its own batch jobs to that pool. + extracted[i] = extractedBatch{nodes: nodes, edges: edges, batchIDs: batchIDs} return nil }) } @@ -111,6 +114,19 @@ func Run(ctx context.Context, deps common.Deps, param common.Param, inputs commo if err := runBatches(ctx, jobs); err != nil { return common.Outputs{}, err } + // Embed each extracted batch serially after all MAP jobs have returned. + // This avoids nesting Embed.Encode (and its batch jobs) inside a worker + // already occupied by the shared compiler pool. + for i, result := range extracted { + if len(result.batchIDs) == 0 { + continue + } + rows, err := buildRows(ctx, deps, cfg, result.nodes, result.edges, result.batchIDs) + if err != nil { + return common.Outputs{}, err + } + perBatch[i] = rows + } // ---- DEDUP ---- // Sequential in batch order so merge outcomes are deterministic and match diff --git a/internal/ingestion/task/knowledge_compiler_wiring.go b/internal/ingestion/task/knowledge_compiler_wiring.go index 9a60b132699..9a0dcaca1ca 100644 --- a/internal/ingestion/task/knowledge_compiler_wiring.go +++ b/internal/ingestion/task/knowledge_compiler_wiring.go @@ -642,7 +642,7 @@ const kcChatRetryMax = 5 // kcChatAttemptTimeout bounds a single Chat call per retry attempt. It matches // the non-streaming provider deadline so the knowledge-compiler adapter does // not cancel a valid long-running response before the provider does. -const kcChatAttemptTimeout = 3 * time.Minute +const kcChatAttemptTimeout = 20 * time.Minute // kcChatRetryDelay is the initial exponential-backoff delay between retries. const kcChatRetryDelay = 2 * time.Second From 681f418424f6cce6d880c1805f01f8863253ee7b Mon Sep 17 00:00:00 2001 From: Sbaaoui Idriss <112825897+6ba3i@users.noreply.github.com> Date: Fri, 11 Sep 2026 10:21:25 +0800 Subject: [PATCH 094/568] fix(invoke): tolerate invalid headers across runtimes (#19481) --- agent/component/invoke.py | 23 +++++++-- internal/agent/component/invoke.go | 19 ++++--- internal/agent/component/invoke_test.go | 50 +++++++++++++++++++ .../test_invoke_component_unit.py | 32 ++++++++++++ 4 files changed, 115 insertions(+), 9 deletions(-) diff --git a/agent/component/invoke.py b/agent/component/invoke.py index 4ace2197b45..67b41bce1a9 100644 --- a/agent/component/invoke.py +++ b/agent/component/invoke.py @@ -185,12 +185,29 @@ def _build_url(self, kwargs: dict) -> str: return url def _build_headers(self, kwargs: dict) -> dict: - if not self._param.headers: + raw_headers = self._param.headers + if raw_headers is None or (isinstance(raw_headers, str) and not raw_headers.strip()): + return {} + + if isinstance(raw_headers, dict): + headers = raw_headers + elif isinstance(raw_headers, str): + try: + headers = json.loads(raw_headers) + except json.JSONDecodeError as exc: + logging.warning( + "Invoke headers ignored: invalid JSON (line=%s column=%s)", + exc.lineno, + exc.colno, + ) + return {} + else: + logging.warning("Invoke headers ignored: unsupported type=%s", type(raw_headers).__name__) return {} - headers = json.loads(self._param.headers) if not isinstance(headers, dict): - raise ValueError("Invoke headers must be a JSON object.") + logging.warning("Invoke headers ignored: decoded type=%s", type(headers).__name__) + return {} return {key: self._resolve_header_text(value, kwargs) if isinstance(value, str) else value for key, value in headers.items()} diff --git a/internal/agent/component/invoke.go b/internal/agent/component/invoke.go index 2ee8e75f725..e2591cd988b 100644 --- a/internal/agent/component/invoke.go +++ b/internal/agent/component/invoke.go @@ -354,15 +354,22 @@ func invokeHeaders(raw any) (map[string]any, error) { return headers, nil } text, ok := raw.(string) - if !ok || strings.TrimSpace(text) == "" { + if !ok { + zap.L().Warn("Invoke headers ignored: unsupported type", zap.String("type", fmt.Sprintf("%T", raw))) return nil, nil } - var headers map[string]any - if err := json.Unmarshal([]byte(text), &headers); err != nil { - return nil, fmt.Errorf("Invoke: headers must be a JSON object: %w", err) + if strings.TrimSpace(text) == "" { + return nil, nil + } + var decoded any + if err := json.Unmarshal([]byte(text), &decoded); err != nil { + zap.L().Warn("Invoke headers ignored: invalid JSON", zap.Error(err)) + return nil, nil } - if headers == nil { - return nil, errors.New("Invoke: headers must be a JSON object") + headers, ok := decoded.(map[string]any) + if !ok { + zap.L().Warn("Invoke headers ignored: decoded type", zap.String("type", fmt.Sprintf("%T", decoded))) + return nil, nil } return headers, nil } diff --git a/internal/agent/component/invoke_test.go b/internal/agent/component/invoke_test.go index 5c19ee17922..228ea6d1b6f 100644 --- a/internal/agent/component/invoke_test.go +++ b/internal/agent/component/invoke_test.go @@ -18,15 +18,19 @@ package component import ( "context" + "fmt" "io" "net" "net/http" "net/http/httptest" "net/url" + "reflect" "strings" "testing" "time" + "go.uber.org/zap" + "go.uber.org/zap/zaptest/observer" "ragflow/internal/utility" ) @@ -148,6 +152,52 @@ func TestInvoke_UsesNodeParams(t *testing.T) { } } +func TestInvokeHeadersToleratesInvalidInput(t *testing.T) { + tests := []struct { + name string + raw any + want map[string]any + }{ + {name: "malformed JSON", raw: `{"Authorization":"Bearer secret-token"`, want: nil}, + {name: "empty", raw: "", want: nil}, + {name: "array", raw: `["secret-token"]`, want: nil}, + {name: "scalar", raw: `true`, want: nil}, + {name: "null", raw: "null", want: nil}, + {name: "unsupported", raw: 42, want: nil}, + {name: "object", raw: `{"X-Test":"yes"}`, want: map[string]any{"X-Test": "yes"}}, + {name: "direct map", raw: map[string]any{"X-Test": "yes"}, want: map[string]any{"X-Test": "yes"}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := invokeHeaders(tt.raw) + if err != nil { + t.Fatalf("invokeHeaders() error = %v", err) + } + if !reflect.DeepEqual(got, tt.want) { + t.Fatalf("invokeHeaders() = %#v, want %#v", got, tt.want) + } + }) + } +} + +func TestInvokeHeadersDoesNotLogRawPayload(t *testing.T) { + previous := zap.L() + core, logs := observer.New(zap.WarnLevel) + zap.ReplaceGlobals(zap.New(core)) + t.Cleanup(func() { zap.ReplaceGlobals(previous) }) + + const secret = "Bearer secret-token" + if _, err := invokeHeaders(`{"Authorization":"` + secret); err != nil { + t.Fatalf("invokeHeaders() error = %v", err) + } + for _, entry := range logs.All() { + if strings.Contains(entry.Message, secret) || strings.Contains(fmt.Sprint(entry.ContextMap()), secret) { + t.Fatalf("log contains raw header payload: %#v", entry) + } + } +} + func TestInvoke_GetInputForm(t *testing.T) { c, err := NewInvokeComponent(map[string]any{ "variables": []any{ diff --git a/test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py b/test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py index 79f6abed370..5823eae21c8 100644 --- a/test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py +++ b/test/testcases/test_web_api/test_canvas_app/test_invoke_component_unit.py @@ -201,6 +201,38 @@ def test_header_empty(monkeypatch): assert mock_get.call_args[1]["headers"] == {} +@pytest.mark.parametrize("headers", ['{"Authorization":"Bearer secret-token"', '["secret-token"]', "null"]) +def test_header_invalid_input_is_ignored_without_logging_raw_value(monkeypatch, caplog, headers): + module = _load_invoke_module(monkeypatch) + invoke = _make_invoke(module, headers=headers) + + with caplog.at_level("WARNING"): + assert invoke._build_headers({}) == {} + + assert "secret-token" not in caplog.text + + +def test_header_dict_is_accepted_and_interpolated(monkeypatch): + module = _load_invoke_module(monkeypatch) + invoke = _make_invoke( + module, + headers={"Authorization": "Bearer {token}"}, + variable_values={"token": "secret-token"}, + ) + + assert invoke._build_headers({}) == {"Authorization": "Bearer secret-token"} + + +def test_header_unsupported_type_is_ignored(monkeypatch, caplog): + module = _load_invoke_module(monkeypatch) + invoke = _make_invoke(module, headers=object()) + + with caplog.at_level("WARNING"): + assert invoke._build_headers({}) == {} + + assert "object" in caplog.text + + @pytest.mark.p2 def test_header_component_ref_variable(monkeypatch): module = _load_invoke_module(monkeypatch) From 0c3902afdbeaf8830b15a8d77753b4a62daafa09 Mon Sep 17 00:00:00 2001 From: Zhu Lei <123629497+kabishou11@users.noreply.github.com> Date: Fri, 11 Sep 2026 10:47:50 +0800 Subject: [PATCH 095/568] fix(wiki): treat MAP-extracted chunks as cache hits instead of missing (#19208) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix #19092 — stamp kb_id on Wiki MAP resume rows so OpenSearch completeness check can see persisted extracts (was reporting all as missing). --- rag/advanced_rag/knowlege_compile/wiki.py | 7 + .../knowlege_compile/test_wiki_map_state.py | 204 ++++++++++++++++++ 2 files changed, 211 insertions(+) diff --git a/rag/advanced_rag/knowlege_compile/wiki.py b/rag/advanced_rag/knowlege_compile/wiki.py index 4d01f04c1ea..619f8d6a6bf 100644 --- a/rag/advanced_rag/knowlege_compile/wiki.py +++ b/rag/advanced_rag/knowlege_compile/wiki.py @@ -692,6 +692,7 @@ def _wiki_build_resume_doc( doc_id: str, per_chunk_extract: dict, chunk_hash: str = "", + kb_id: str = "", ) -> dict: """Build the non-searchable ES doc that records a per-chunk MAP extract. @@ -702,6 +703,10 @@ def _wiki_build_resume_doc( ``chunk_hash`` fingerprints the chunk's content as of extraction time. The incremental MAP re-run reads it back and compares against the current chunk's hash to decide whether to re-extract. + + ``kb_id`` is stamped on the row because every doc-store search in this + pipeline injects a ``kb_id`` filter. A MAP row without it is invisible + to cache resolution even after a successful bulk write. """ content_with_weight = json.dumps(per_chunk_extract, ensure_ascii=False) doc_id_str = str(doc_id) @@ -710,6 +715,7 @@ def _wiki_build_resume_doc( # identity lets A -> B -> A reuse the first extraction instead of # replacing it when B is compiled. "id": _stable_row_id(WIKI_MAP_COMPILE_KWD, doc_id_str, chunk_id, chunk_hash), + "kb_id": str(kb_id), "doc_id": doc_id_str, "compile_kwd": WIKI_MAP_COMPILE_KWD, "source_chunk_ids": [chunk_id], @@ -813,6 +819,7 @@ async def _wiki_persist_extracts( doc_id, extract, chunk_hash=hashes.get(chunk_id, ""), + kb_id=kb_id, ) for chunk_id, extract in per_chunk.items() if chunk_id diff --git a/test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_map_state.py b/test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_map_state.py index 7961e819dfe..e3afd78ae28 100644 --- a/test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_map_state.py +++ b/test/unit_test/rag/advanced_rag/knowlege_compile/test_wiki_map_state.py @@ -73,6 +73,50 @@ def delete(self, condition, _index, _dataset_id): del self.rows[row_id] +class _KbScopedDocStore(_StateDocStore): + """Mirrors ES/OpenSearch search: every query is pinned to ``kb_id``.""" + + def search(self, fields, highlights, condition, matches, order, offset, limit, index, dataset_ids): + scoped = dict(condition or {}) + if dataset_ids: + scoped["kb_id"] = list(dataset_ids) + rows = [] + for row in self.rows.values(): + if scoped.get("kb_id") and row.get("kb_id") not in scoped["kb_id"]: + continue + if any(scoped.get(key) and row.get(key) not in scoped[key] for key in ("id", "compile_kwd", "type_kwd")): + continue + if scoped.get("doc_id") and row.get("doc_id") not in scoped["doc_id"]: + continue + if scoped.get("source_chunk_ids") and not set(row.get("source_chunk_ids") or []) & set(scoped["source_chunk_ids"]): + continue + if scoped.get("chunk_hash_kwd") and row.get("chunk_hash_kwd") not in scoped["chunk_hash_kwd"]: + continue + rows.append(row) + return rows[offset : offset + limit] + + +# Reporter chunk ids from infiniflow/ragflow#19092. MAP logged extracted=9 then +# immediately listed these same ids as missing_chunks. +_REPORTER_CHUNK_IDS = [ + "0b9beb4afcaf7717", + "2382483997f1183d", + "31c63a0feb6b8207", + "39feff69089a3d59", + "5467040776c88761", + "60ffd6504434bae2", + "87b76b7a1ebb3dc5", + "d96c875495acd52c", + "e96857ea65980dec", +] + + +def _missing_after_resolve(wiki, tenant_id, kb_id, state, target_chunk_ids): + resolved = asyncio.run(wiki._wiki_load_map_extracts_for_state(tenant_id, kb_id, state, target_chunk_ids)) + resolved_ids = {str((extract.get("_map_version") or {}).get("chunk_id") or "") for extract in resolved} + return set(target_chunk_ids) - resolved_ids + + def test_active_map_state_switches_marker_after_new_generation(monkeypatch): wiki = _load_wiki_module(monkeypatch) marker_id = wiki._stable_row_id(wiki.WIKI_MAP_STATE_META_COMPILE_KWD, "kb-1") @@ -165,3 +209,163 @@ def insert(self, rows, index, dataset_id): asyncio.run(wiki._wiki_commit_active_map_state("tenant-1", "kb-1", {"chunk-new": {"doc_id": "doc-new", "hash": "hash-new"}})) assert asyncio.run(wiki._wiki_load_active_map_state("tenant-1", "kb-1")) == {"chunk-old": {"doc_id": "doc-old", "hash": "hash-old"}} + + +def test_persisted_map_extracts_are_not_missing_from_completeness_check(monkeypatch): + """Successful MAP persist must satisfy the incremental completeness check. + + Issue 19092: wiki_map logged requested=9 cache_hits=0 extracted=9, then the + follow-up cache resolution reported the same 9 source-chunk ids as missing. + The rows were written, but searches always filter by kb_id and the resume + doc omitted that field, so every extracted chunk looked absent. + """ + wiki = _load_wiki_module(monkeypatch) + store = _KbScopedDocStore() + monkeypatch.setattr(sys.modules["common.settings"], "docStoreConn", store) + + doc_id = "6dc70e7aa5a411f19c0109b856bc47ac" + kb_id = "ff675c34a5a111f19c0109b856bc47ac" + per_chunk = {chunk_id: wiki._wiki_empty_extract() for chunk_id in _REPORTER_CHUNK_IDS} + hashes = {chunk_id: f"hash-{chunk_id}" for chunk_id in _REPORTER_CHUNK_IDS} + state = {chunk_id: {"doc_id": doc_id, "hash": hashes[chunk_id]} for chunk_id in _REPORTER_CHUNK_IDS} + target = set(_REPORTER_CHUNK_IDS) + + asyncio.run(wiki._wiki_persist_extracts(per_chunk, doc_id, "tenant-1", kb_id, chunk_hashes=hashes)) + + written = [row for batch in store.insert_calls for row in batch] + assert {row["kb_id"] for row in written} == {kb_id} + assert {row["source_chunk_ids"][0] for row in written} == target + assert _missing_after_resolve(wiki, "tenant-1", kb_id, state, target) == set() + + +def test_completeness_check_still_reports_chunks_that_were_never_persisted(monkeypatch): + wiki = _load_wiki_module(monkeypatch) + store = _KbScopedDocStore() + monkeypatch.setattr(sys.modules["common.settings"], "docStoreConn", store) + + doc_id = "doc-1" + kb_id = "kb-1" + persisted = _REPORTER_CHUNK_IDS[:-1] + missing_id = _REPORTER_CHUNK_IDS[-1] + hashes = {chunk_id: f"hash-{chunk_id}" for chunk_id in _REPORTER_CHUNK_IDS} + state = {chunk_id: {"doc_id": doc_id, "hash": hashes[chunk_id]} for chunk_id in _REPORTER_CHUNK_IDS} + per_chunk = {chunk_id: wiki._wiki_empty_extract() for chunk_id in persisted} + + asyncio.run(wiki._wiki_persist_extracts(per_chunk, doc_id, "tenant-1", kb_id, chunk_hashes=hashes)) + + assert _missing_after_resolve(wiki, "tenant-1", kb_id, state, set(_REPORTER_CHUNK_IDS)) == {missing_id} + + +def test_map_extract_without_kb_id_is_invisible_to_completeness_check(monkeypatch): + """Rows that omit kb_id must not count as resolved under a kb-scoped search.""" + wiki = _load_wiki_module(monkeypatch) + store = _KbScopedDocStore() + monkeypatch.setattr(sys.modules["common.settings"], "docStoreConn", store) + + chunk_id = _REPORTER_CHUNK_IDS[0] + doc_id = "doc-1" + kb_id = "kb-1" + chunk_hash = "hash-1" + store.rows["orphan"] = { + "id": "orphan", + "doc_id": doc_id, + "compile_kwd": wiki.WIKI_MAP_COMPILE_KWD, + "source_chunk_ids": [chunk_id], + "chunk_hash_kwd": chunk_hash, + "content_with_weight": json.dumps({"entities": []}), + } + state = {chunk_id: {"doc_id": doc_id, "hash": chunk_hash}} + + assert _missing_after_resolve(wiki, "tenant-1", kb_id, state, {chunk_id}) == {chunk_id} + + +def test_wiki_map_from_chunks_successful_extract_is_not_reported_missing(monkeypatch): + """Successful MAP through wiki_map_from_chunks must not look missing afterward. + + Issue 19092: wiki_map logged extracted=9 then the generator completeness + check listed the same source-chunk ids as missing_chunks. The isolated + persist + lookup tests cover the row shape; this drives the public MAP + entry so extract → persist → kb-scoped completeness run as one flow. + Extraction is stubbed; persist and completeness use the real helpers + against a kb-scoped fake doc store. + """ + wiki = _load_wiki_module(monkeypatch) + store = _KbScopedDocStore() + monkeypatch.setattr(sys.modules["common.settings"], "docStoreConn", store) + + def _pack_batches(chunks, _chat_mdl, **kwargs): + resume = kwargs.get("resume_chunk_ids") or set() + picker = kwargs.get("chunk_text_picker") or (lambda chunk: chunk.get("text") or "") + packed = [] + for idx, chunk in enumerate(chunks): + chunk_id = chunk.get("id") or chunk.get("chunk_id") + if not isinstance(chunk_id, str) or not chunk_id or chunk_id in resume: + continue + packed.append({"label": f"C{idx + 1}", "chunk_id": chunk_id, "text": picker(chunk) or ""}) + return ([packed] if packed else [], {"n_batches": int(bool(packed))}) + + async def _run_pipeline(batches, *, process_batch, aggregate=None, **_kwargs): + if not batches: + return aggregate([]) if aggregate else [] + results = [await process_batch(batch, idx, len(batches)) for idx, batch in enumerate(batches)] + return aggregate(results) if aggregate else results + + extracted_from_llm = [] + + async def _extract_ok(packed, *_args, **_kwargs): + extracted_from_llm.extend(entry["chunk_id"] for entry in packed) + return wiki._wiki_empty_extract() + + monkeypatch.setattr(wiki, "_build_chunk_batches", _pack_batches) + monkeypatch.setattr(wiki, "_run_chunked_pipeline", _run_pipeline) + monkeypatch.setattr(wiki, "_wiki_extract_one_batch", _extract_ok) + + doc_id = "6dc70e7aa5a411f19c0109b856bc47ac" + kb_id = "ff675c34a5a111f19c0109b856bc47ac" + tenant_id = "tenant-1" + never_extracted_id = "never-extracted-chunk" + chunks = [{"id": chunk_id, "text": f"body of {chunk_id}"} for chunk_id in _REPORTER_CHUNK_IDS] + chat_mdl = SimpleNamespace(max_length=8192, llm_name="mock-chat") + + first = asyncio.run( + wiki.wiki_map_from_chunks( + chunks=chunks, + chat_mdl=chat_mdl, + embd_mdl=None, + doc_id=doc_id, + tenant_id=tenant_id, + kb_id=kb_id, + ) + ) + + assert first["_meta"]["requested"] == len(_REPORTER_CHUNK_IDS) + assert first["_meta"]["extracted"] == len(_REPORTER_CHUNK_IDS) + assert first["_meta"]["cache_hits"] == 0 + assert set(extracted_from_llm) == set(_REPORTER_CHUNK_IDS) + + written = [row for batch in store.insert_calls for row in batch] + assert {row["kb_id"] for row in written} == {kb_id} + assert {row["source_chunk_ids"][0] for row in written} == set(_REPORTER_CHUNK_IDS) + + hashes = {chunk_id: wiki._chunk_hash(f"body of {chunk_id}") for chunk_id in _REPORTER_CHUNK_IDS} + state = {chunk_id: {"doc_id": doc_id, "hash": hashes[chunk_id]} for chunk_id in _REPORTER_CHUNK_IDS} + state[never_extracted_id] = {"doc_id": doc_id, "hash": "hash-never"} + target = set(_REPORTER_CHUNK_IDS) | {never_extracted_id} + + # Same completeness path as run_wiki_incremental after MAP: load extracts + # for the current chunk state and treat unresolved ids as missing_chunks. + assert _missing_after_resolve(wiki, tenant_id, kb_id, state, target) == {never_extracted_id} + + second = asyncio.run( + wiki.wiki_map_from_chunks( + chunks=chunks, + chat_mdl=chat_mdl, + embd_mdl=None, + doc_id=doc_id, + tenant_id=tenant_id, + kb_id=kb_id, + ) + ) + assert second["_meta"]["cache_hits"] == len(_REPORTER_CHUNK_IDS) + assert second["_meta"]["extracted"] == 0 + assert extracted_from_llm == list(_REPORTER_CHUNK_IDS) From f99dd22dfd3c883d46d6a1b71a0b801fd84e56a1 Mon Sep 17 00:00:00 2001 From: Sourav Rajvi <144546710+Souravrajvi0@users.noreply.github.com> Date: Fri, 11 Sep 2026 08:58:25 +0530 Subject: [PATCH 096/568] fix(web): prevent DOCX preview infinite update loop (#19475) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix #19464 — DOCX preview infinite update loop. Fixed unstable importDocxFile dependency via ref, and disabled library page virtualization. --- .../document-preview/doc-preview.test.tsx | 133 ++++++++++++++++++ .../document-preview/doc-preview.tsx | 9 +- 2 files changed, 140 insertions(+), 2 deletions(-) create mode 100644 web/src/components/document-preview/doc-preview.test.tsx diff --git a/web/src/components/document-preview/doc-preview.test.tsx b/web/src/components/document-preview/doc-preview.test.tsx new file mode 100644 index 00000000000..8786fd2ee7f --- /dev/null +++ b/web/src/components/document-preview/doc-preview.test.tsx @@ -0,0 +1,133 @@ +/* + * 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. + */ + +import request from '@/utils/request'; +import { render, screen, waitFor } from '@testing-library/react'; +import { DocPreviewer } from './doc-preview'; + +const mockImportDocxFile = jest.fn().mockResolvedValue(undefined); +let mockEditorImportDocxFile = mockImportDocxFile; + +jest.mock('@/utils/request', () => ({ + __esModule: true, + default: jest.fn(), +})); + +jest.mock('@/components/ui/message', () => ({ + __esModule: true, + default: { error: jest.fn() }, +})); + +jest.mock('@/components/ui/spin', () => ({ + Spin: () =>
, +})); + +jest.mock('./hooks', () => ({ + isZipLikeBlob: jest.fn().mockResolvedValue(true), + useDocumentResizeObserver: () => ({ + containerWidth: 800, + setContainerRef: jest.fn(), + }), + useDocxPreviewZoom: () => ({ + zoomScale: 100, + minZoom: 50, + maxZoom: 200, + handleZoomIn: jest.fn(), + handleZoomOut: jest.fn(), + }), +})); + +jest.mock('@extend-ai/react-docx', () => ({ + DocxEditorViewer: ({ + pageVirtualization, + }: { + pageVirtualization?: { enabled?: boolean }; + }) => ( +
+ ), + useDocxEditor: () => ({ + importDocxFile: mockEditorImportDocxFile, + status: 'ready', + totalPages: 2, + }), + useDocxPageLayout: () => ({ layout: { pageWidthPx: 800 } }), + parseDocx: jest.fn(), + packageToArrayBuffer: jest.fn(), +})); + +const MockRequest = jest.mocked(request); +const OriginalResizeObserver = globalThis.ResizeObserver; + +beforeAll(() => { + globalThis.ResizeObserver = jest.fn().mockImplementation(() => ({ + observe: jest.fn(), + unobserve: jest.fn(), + disconnect: jest.fn(), + })); +}); + +afterAll(() => { + globalThis.ResizeObserver = OriginalResizeObserver; +}); + +describe('DocPreviewer', () => { + beforeEach(() => { + mockEditorImportDocxFile = mockImportDocxFile; + mockImportDocxFile.mockClear(); + mockImportDocxFile.mockImplementation(async () => { + // Mimic @extend-ai/react-docx returning a new callback after import. + mockEditorImportDocxFile = jest.fn().mockResolvedValue(undefined); + }); + MockRequest.mockResolvedValue({ + data: new Blob([new Uint8Array([0x50, 0x4b, 0x03, 0x04])], { + type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + }), + } as never); + }); + + it('loads the document once even when importDocxFile identity changes', async () => { + const { rerender } = render( + , + ); + + await waitFor(() => { + expect(mockImportDocxFile).toHaveBeenCalledTimes(1); + }); + + rerender(); + + await waitFor(() => { + expect(screen.getByTestId('docx-viewer')).toBeInTheDocument(); + }); + expect(mockImportDocxFile).toHaveBeenCalledTimes(1); + }); + + it('disables internal DOCX page virtualization to avoid update loops', async () => { + render(); + + await waitFor(() => { + expect(screen.getByTestId('docx-viewer')).toBeInTheDocument(); + }); + + expect(screen.getByTestId('docx-viewer')).toHaveAttribute( + 'data-page-virtualization', + JSON.stringify({ enabled: false }), + ); + }); +}); diff --git a/web/src/components/document-preview/doc-preview.tsx b/web/src/components/document-preview/doc-preview.tsx index 8176d262630..457e3f712e1 100644 --- a/web/src/components/document-preview/doc-preview.tsx +++ b/web/src/components/document-preview/doc-preview.tsx @@ -162,6 +162,10 @@ export const DocPreviewer: React.FC = ({ }) => { const editor = useDocxEditor({ initialFileName: 'document.docx' }); const { importDocxFile, status, totalPages } = editor; + // importDocxFile is recreated whenever the library's internal state changes + // (after each import), which would re-trigger the fetch effect endlessly. + const importDocxFileRef = useRef(importDocxFile); + importDocxFileRef.current = importDocxFile; const { layout } = useDocxPageLayout(editor); const { containerWidth, setContainerRef } = useDocumentResizeObserver(); const [loading, setLoading] = useState(false); @@ -227,7 +231,7 @@ export const DocPreviewer: React.FC = ({ type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', }); - await importDocxFile(file); + await importDocxFileRef.current(file); if (!cancelledRef.current) { setLoading(false); @@ -239,7 +243,7 @@ export const DocPreviewer: React.FC = ({ setLoading(false); } } - }, [url, importDocxFile]); + }, [url]); useEffect(() => { fetchDocument(); @@ -328,6 +332,7 @@ export const DocPreviewer: React.FC = ({ From 296c1017c6f1eea3fed9262e37e04eb679476d6a Mon Sep 17 00:00:00 2001 From: huyua9 Date: Fri, 11 Sep 2026 11:30:32 +0800 Subject: [PATCH 097/568] fix(web): add Traditional Chinese child delimiter translations (#18951) Add 3 missing Traditional Chinese locale keys for child-chunk delimiter config (were falling back to English). --- web/src/locales/zh-traditional.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/web/src/locales/zh-traditional.ts b/web/src/locales/zh-traditional.ts index 361c99939d7..298e2794ab7 100644 --- a/web/src/locales/zh-traditional.ts +++ b/web/src/locales/zh-traditional.ts @@ -173,6 +173,10 @@ export default { delimiter: `文字分段標識符`, delimiterTip: '支持多字符作為分隔符,多字符用兩個反引號 \\`\\` 分隔符包裹。若配置成:\\n`##`; 系統將首先使用換行符、兩個#號以及分號先對文本進行分割,隨後再對分得的小文本塊按照「建议文本块大小」設定的大小進行拼裝。在设置文本分段標識符之前,請確保您已理解上述文本分段切片機制。', + enableChildrenDelimiter: '子文本塊用於檢索', + childrenDelimiter: '文字分段標識符', + childrenDelimiterTip: + '支持多字符作為分隔符,多字符用兩個反引號 \\`\\` 分隔符包裹。若配置成:\\n`##`; 系統將首先使用換行符、兩個#號以及分號先對文本進行分割,隨後再對分得的小文本塊按照「建議文字塊大小」設定的大小進行拼裝。在設定文字分段標識符前請確保理解上述文字分段切片機制。', html4excel: '表格轉HTML', html4excelTip: `與 General 切片方法配合使用。未開啟狀態下,表格檔案(XLSX、XLS(Excel 97-2003)會按行解析為鍵值對。開啟後,表格檔案會被解析為 HTML 表格。若原始表格超過 12 行,系統會自動按每 12 行拆分為多個 HTML 表格。欲了解更多資訊,請參閱 https://ragflow.io/docs/dataset_configuration#other-format-processing-configuration。`, autoKeywords: '自動關鍵字', From c2e770406ed0cbc10d1437563c397fc4ef6c1c9a Mon Sep 17 00:00:00 2001 From: Taranum Wasu <81034301+Taranum01@users.noreply.github.com> Date: Fri, 11 Sep 2026 09:01:02 +0530 Subject: [PATCH 098/568] fix(figure_parser): accept lang as named parameter on VisionFigureParser (#17280) (#19511) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix #17280 — VisionFigureParser.__init__ now takes explicit lang= parameter (was implicit via kwargs). --- deepdoc/parser/figure_parser.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/deepdoc/parser/figure_parser.py b/deepdoc/parser/figure_parser.py index 4806abb24aa..bbb754753ad 100644 --- a/deepdoc/parser/figure_parser.py +++ b/deepdoc/parser/figure_parser.py @@ -235,9 +235,16 @@ def worker(idx, ck): class VisionFigureParser: - def __init__(self, vision_model, figures_data, *args, **kwargs): + def __init__(self, vision_model, figures_data, *args, lang="English", **kwargs): self.vision_model = vision_model - self.language = kwargs.get("lang") or "English" + # Accept `lang` as a named parameter instead of pulling it out + # of `**kwargs`: the wrappers above pass `lang=lang` explicitly + # and previously relied on kwargs lookup, which works but is + # easy to miss when adding new call sites. A named parameter + # is clearer at the contract level. Regression for #17280. + # `**kwargs.get("lang")` is kept as a fallback so older callers + # that don't pass `lang` keep working. + self.language = _normalize_vision_language(lang) or kwargs.get("lang") or "English" self.figure_contexts = kwargs.get("figure_contexts") or [] self.context_size = max(0, int(kwargs.get("context_size", 0) or 0)) self._extract_figures_info(figures_data) From db74811549a4b27631e57baf690e26ce6dd783f0 Mon Sep 17 00:00:00 2001 From: huyua9 Date: Fri, 11 Sep 2026 11:55:12 +0800 Subject: [PATCH 099/568] fix(dataflow): preserve scalar text output shape (#18921) Normalize non-empty markdown/text/html scalar outputs as string chunks; empty stays zero chunks. --- rag/svr/task_executor.py | 32 ++++++++----------- .../svr/test_task_executor_dataflow_output.py | 29 +++++++++++++++++ 2 files changed, 43 insertions(+), 18 deletions(-) create mode 100644 test/unit_test/rag/svr/test_task_executor_dataflow_output.py diff --git a/rag/svr/task_executor.py b/rag/svr/task_executor.py index fbda9b96696..20b2790447a 100644 --- a/rag/svr/task_executor.py +++ b/rag/svr/task_executor.py @@ -793,6 +793,19 @@ def batch_encode(txts): return tk_count, vector_size +def _normalize_dataflow_output(chunks): + """Normalize pipeline output into the chunk shape used by indexing.""" + if "chunks" in chunks: + return copy.deepcopy(chunks["chunks"]), "chunks" + if "json" in chunks: + return copy.deepcopy(chunks["json"]), "json" + for output_type in ("markdown", "text", "html"): + if output_type in chunks: + payload = chunks[output_type] + return ([{"text": payload}] if payload else []), output_type + return [], "empty" + + @timed_with_recording async def run_dataflow(task: dict): from api.db.services.canvas_service import UserCanvasService @@ -837,24 +850,7 @@ async def run_dataflow(task: dict): embedding_token_consumption = chunks.get("embedding_token_consumption", 0) # The output key may exist with an empty payload; check presence, not truthiness. - if "chunks" in chunks: - chunks = copy.deepcopy(chunks["chunks"]) - output_type = "chunks" - elif "json" in chunks: - chunks = copy.deepcopy(chunks["json"]) - output_type = "json" - elif "markdown" in chunks: - chunks = [{"text": [chunks["markdown"]]}] if chunks["markdown"] else [] - output_type = "markdown" - elif "text" in chunks: - chunks = [{"text": [chunks["text"]]}] if chunks["text"] else [] - output_type = "text" - elif "html" in chunks: - chunks = [{"text": [chunks["html"]]}] if chunks["html"] else [] - output_type = "html" - else: - chunks = [] - output_type = "empty" + chunks, output_type = _normalize_dataflow_output(chunks) get_recording_context().record("pipeline_output_type", output_type) get_recording_context().record("pipeline_output_count", len(chunks)) diff --git a/test/unit_test/rag/svr/test_task_executor_dataflow_output.py b/test/unit_test/rag/svr/test_task_executor_dataflow_output.py new file mode 100644 index 00000000000..399c116b208 --- /dev/null +++ b/test/unit_test/rag/svr/test_task_executor_dataflow_output.py @@ -0,0 +1,29 @@ +import ast +from pathlib import Path + +import pytest + + +@pytest.fixture +def normalize_dataflow_output(): + repo_root = Path(__file__).resolve().parents[4] + source = (repo_root / "rag" / "svr" / "task_executor.py").read_text(encoding="utf-8") + tree = ast.parse(source) + helper = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "_normalize_dataflow_output") + namespace = {"copy": __import__("copy")} + exec(compile(ast.Module(body=[helper], type_ignores=[]), "task_executor.py", "exec"), namespace) + return namespace["_normalize_dataflow_output"] + + +@pytest.mark.parametrize("output_type", ["markdown", "text", "html"]) +def test_scalar_dataflow_output_keeps_text_as_string(normalize_dataflow_output, output_type): + chunks, normalized_type = normalize_dataflow_output({output_type: "hello"}) + + assert normalized_type == output_type + assert chunks == [{"text": "hello"}] + assert isinstance(chunks[0]["text"], str) + + +@pytest.mark.parametrize("output_type", ["markdown", "text", "html"]) +def test_empty_scalar_dataflow_output_has_no_chunks(normalize_dataflow_output, output_type): + assert normalize_dataflow_output({output_type: ""}) == ([], output_type) From b130e1814bd48df58c0ec8ea7e1d7d023c383d14 Mon Sep 17 00:00:00 2001 From: huyua9 Date: Fri, 11 Sep 2026 11:58:17 +0800 Subject: [PATCH 100/568] fix(i18n): localize Chinese delimiter preview (#18948) Sync Chinese delimiter tooltips with current parser rules; add 3 missing preview keys (were English fallback). --- web/src/locales/zh.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/web/src/locales/zh.ts b/web/src/locales/zh.ts index 95814f6357e..6e824f2ae6c 100644 --- a/web/src/locales/zh.ts +++ b/web/src/locales/zh.ts @@ -539,11 +539,14 @@ export default { topKTip: `与 Rerank 模型配合使用,用于设置传给 Rerank 模型的文本块数量。`, delimiter: `文本分段标识符`, delimiterTip: - '支持多字符作为分隔符,多字符用两个反引号 \\`\\` 分隔符包裹。若配置成:\\n`##`; 系统将首先使用换行符、两个#号以及分号先对文本进行分割,随后再对分得的小文本块按照「建议文本块大小」设定的大小进行拼装。在设置文本分段标识符前请确保理解上述文本分段切片机制。', + '分隔符字符串会被解析为分隔符列表。反引号(` `)用于界定分隔符:一对匹配的反引号会将其中的字符作为一个多字符分隔符;反引号外的每个字符都会作为独立分隔符。分隔符按长度从长到短匹配。例如:\\n`##`; 会解析为三个分隔符——换行符(\\n)、两个井号(##)和分号(;),文本遇到其中任意一个都会被切分。单字符分隔符(例如 !?; → !、?、;)无需反引号;多字符分隔符(例如 ##、END)必须用反引号包裹。', enableChildrenDelimiter: '子文本块用于检索', childrenDelimiter: '文本分段标识符', childrenDelimiterTip: - '支持多字符作为分隔符,多字符用两个反引号 \\`\\` 分隔符包裹。若配置成:\\n`##`; 系统将首先使用换行符、两个#号以及分号先对文本进行分割,随后再对分得的小文本块按照「建议文本块大小」设定的大小进行拼装。在设置文本分段标识符前请确保理解上述文本分段切片机制。', + '分隔符字符串会被解析为分隔符列表。反引号(` `)用于界定分隔符:一对匹配的反引号会将其中的字符作为一个多字符分隔符;反引号外的每个字符都会作为独立分隔符。分隔符按长度从长到短匹配。例如:\\n`##`; 会解析为三个分隔符——换行符(\\n)、两个井号(##)和分号(;),文本遇到其中任意一个都会被切分。单字符分隔符(例如 !?; → !、?、;)无需反引号;多字符分隔符(例如 ##、END)必须用反引号包裹。', + delimiterPreviewLabel: '切分位置:', + delimiterPreviewEmpty: '没有分隔符——文本将仅按大小切分。', + delimiterPreviewCount: '({{count}})', html4excel: '表格转 HTML', html4excelTip: `与 General 切片方法配合使用。未开启状态下,表格文件(XLSX、XLS(Excel 97-2003))会按行解析为键值对。开启后,表格文件会被解析为 HTML 表格。若原始表格超过 12 行,系统会自动按每 12 行拆分为多个 HTML 表格。欲了解更多详情,请参阅 https://ragflow.io/docs/dataset_configuration#other-format-processing-configuration。`, From 2e6003cfd4f3bc5c849f3ca897af4e33eab3124f Mon Sep 17 00:00:00 2001 From: xugangqiang Date: Fri, 11 Sep 2026 12:12:34 +0800 Subject: [PATCH 101/568] Unify ONNX Runtime native to 1.29.0 from infiniflow/ragflow-build (#19446) Switch Go DeepDoc's static ONNX Runtime to our own infiniflow/ragflow-build release (v1.29.0) instead of third-party. Keeps fused kernels; normalizes dir naming; added ORT version consistency check. --------- Co-authored-by: maoyifeng --- .dockerignore | 9 ++- Dockerfile_go | 20 +++++- build.sh | 85 +++++++++++++++++++------ internal/common/environments.go | 29 +++++---- internal/development.md | 13 ++++ pyproject.toml | 4 +- ragflow_deps/download_deps.py | 89 +++++++++++++++++++-------- ragflow_deps/download_go_deps.py | 66 +++++++++++++++----- ragflow_deps/test_download_go_deps.py | 45 +++++++++----- 9 files changed, 266 insertions(+), 94 deletions(-) diff --git a/.dockerignore b/.dockerignore index 1ed7cfa457e..1b4707c99e1 100644 --- a/.dockerignore +++ b/.dockerignore @@ -34,11 +34,16 @@ target/ # ── ragflow_deps build context (built as a separate image, mounted ── # ── from infiniflow/ragflow_deps:latest by the main Dockerfile) ── -# Excluding the entire directory keeps the main build context small +# Excluding the directory contents keeps the main build context small # regardless of which deps files download_deps.py currently fetches. # The deps image is built from this directory with: # cd ragflow_deps && docker build -f Dockerfile -t infiniflow/ragflow_deps . -ragflow_deps/ +# The two ORT version-pin files are re-included: build.sh's +# check_ort_version_consistency (run by Dockerfile_go's `--go` build) greps +# them. Re-including requires NOT excluding the directory itself. +ragflow_deps/* +!ragflow_deps/download_go_deps.py +!ragflow_deps/download_deps.py # ── IDE and editor config ────────────────────────────────────────────────── .idea/ diff --git a/Dockerfile_go b/Dockerfile_go index 785b050492e..6632a1907e6 100644 --- a/Dockerfile_go +++ b/Dockerfile_go @@ -159,6 +159,11 @@ RUN --mount=type=cache,id=ragflow_gomod,target=/root/.cache/gomod \ COPY internal internal COPY cmd cmd COPY build.sh ./ +# build.sh's check_ort_version_consistency (run via `./build.sh --go`) greps the +# ORT version pins from these files; without them the --go build fails with +# "could not parse the ONNX Runtime version from one of the pinned locations". +COPY ragflow_deps/download_go_deps.py ragflow_deps/download_deps.py ./ragflow_deps/ +COPY Dockerfile_go ./ # ONNX Runtime static archives: build.sh's _seed_from_system looks for the ORT # static libs under ONNXRUNTIME_STATIC_PREFIX (default ~/ragflow-native-libs/onnxruntime). @@ -169,10 +174,19 @@ COPY build.sh ./ # silently skipped and the binary fails at startup with # "no in-process DeepDoc backend serving" (dlopen(NULL)/dlsym can't find OrtGetApiBase). # ${HOME} (not hard-coded /root) keeps the path consistent with build.sh regardless of HOME. -ARG ORT_VERSION=1.23.2 +ARG ORT_VERSION=1.29.0 RUN set -eux; \ - mkdir -p "${HOME}/ragflow-native-libs/onnxruntime"; \ - cp -rn /opt/ragflow-native-libs/onnxruntime/* "${HOME}/ragflow-native-libs/onnxruntime/"; \ + mkdir -p "${HOME}/ragflow-native-libs/onnxruntime/static_lib"; \ + _src="/opt/ragflow-native-libs/onnxruntime/static_lib"; \ + _v="$(ls -d "${_src}"/onnxruntime-linux-x64-static_lib-"${ORT_VERSION}"-* 2>/dev/null | head -1)"; \ + if [ -z "${_v}" ]; then \ + _v="$(ls -d "${_src}"/onnxruntime-linux-x64-static_lib-* 2>/dev/null | head -1)"; \ + fi; \ + if [ -n "${_v}" ]; then \ + cp -r "${_v}" "${HOME}/ragflow-native-libs/onnxruntime/static_lib/"; \ + else \ + echo "Warning: no pre-baked onnxruntime static_lib in runner image; build.sh will attempt download" >&2; \ + fi; \ find "${HOME}/ragflow-native-libs/onnxruntime/static_lib" -name '*.a' | head -5 RUN git config --global safe.directory "*" && \ diff --git a/build.sh b/build.sh index ed91bcf5408..45da44de77c 100755 --- a/build.sh +++ b/build.sh @@ -150,6 +150,38 @@ check_go_deps() { command -v go >/dev/null 2>&1 || { echo -e "${RED}Error: go is required but not installed.${NC}"; exit 1; } echo "✓ Required tools are available" + check_ort_version_consistency +} + +# Fail fast when the ONNX Runtime native version is declared inconsistently. +# The in-process (Go) DeepDoc backend statically links libonnxruntime.a built +# from ONE exact ORT release; a mismatch links a wrong/missing .a and only fails +# at runtime (dlopen(NULL) can't find OrtGetApiBase). The version is pinned in +# four Go-side locations that must all agree. +check_ort_version_consistency() { + print_section "Checking ONNX Runtime version consistency" + + local env_go d1 d2 dockerfile + env_go="$(grep -m1 -E 'DeepDocORTVersion[[:space:]]*=[[:space:]]*"' "${PROJECT_ROOT}/internal/common/environments.go" | sed -E 's/.*"([^"]+)".*/\1/')" + d1="$(grep -m1 -E '^ORT_VERSION[[:space:]]*=[[:space:]]*"' "${PROJECT_ROOT}/ragflow_deps/download_go_deps.py" | sed -E 's/.*"([^"]+)".*/\1/')" + d2="$(grep -m1 -E '^ORT_VERSION[[:space:]]*=[[:space:]]*"' "${PROJECT_ROOT}/ragflow_deps/download_deps.py" | sed -E 's/.*"([^"]+)".*/\1/')" + dockerfile="$(grep -m1 -E 'ARG[[:space:]]+ORT_VERSION=' "${PROJECT_ROOT}/Dockerfile_go" | sed -E 's/.*ORT_VERSION=([0-9][^"[:space:]]*).*/\1/')" + + if [ -z "$env_go" ] || [ -z "$d1" ] || [ -z "$d2" ] || [ -z "$dockerfile" ]; then + echo -e "${RED}Error: could not parse the ONNX Runtime version from one of the pinned locations${NC}" >&2 + exit 1 + fi + + if [ "$env_go" != "$d1" ] || [ "$env_go" != "$d2" ] || [ "$env_go" != "$dockerfile" ]; then + echo -e "${RED}Error: ONNX Runtime version is inconsistent — fix before building:${NC}" >&2 + printf ' %-10s %s\n' "$env_go" "internal/common/environments.go:DeepDocORTVersion" + printf ' %-10s %s\n' "$d1" "ragflow_deps/download_go_deps.py:ORT_VERSION" + printf ' %-10s %s\n' "$d2" "ragflow_deps/download_deps.py:ORT_VERSION" + printf ' %-10s %s\n' "$dockerfile" "Dockerfile_go:ARG ORT_VERSION" + exit 1 + fi + + echo -e "${GREEN}✓ ONNX Runtime native version consistent: ${env_go}${NC}" } # Check office_oxide native library @@ -544,32 +576,34 @@ setup_cgo_env() { if [ -d "$ONNXRUNTIME_STATIC_PREFIX" ]; then # Collect every .a, but skip GPU-only providers we never build # against (would pull in CUDA/cuDNN/TensorRT which we don't ship). + # + # Select the ORT static lib that matches the Go deepdoc backend's + # required version (DeepDocORTVersion in internal/common/environments.go). + # Go and Python build/link against independent ORT versions, so the + # static_lib prefix legitimately holds more than one + # onnxruntime-linux-x64-static_lib-* dir at once (e.g. the Python-side + # 1.23.x next to the Go-side 1.29.0). We pick the dir that matches + # DeepDocORTVersion rather than failing when a second version dir is + # present. This avoids silently linking the wrong version while still + # keeping the bake self-documenting. + local ort_version + ort_version="$(grep -m1 -E 'DeepDocORTVersion[[:space:]]*=[[:space:]]*"' \ + "${PROJECT_ROOT}/internal/common/environments.go" \ + | sed -E 's/.*"([^"]+)".*/\1/')" + if [ -z "$ort_version" ]; then + echo " Error: cannot parse DeepDocORTVersion from internal/common/environments.go" >&2 + return 1 + fi local ort_a="" - local seen_version_dir="" while IFS= read -r f; do case "$(basename "$f")" in *cuda*|*tensorrt*|*coreml*|*dml*|*migraphx*) continue ;; esac - # Guard against coexisting stale version dirs: if .a files span - # more than one onnxruntime-linux-x64-static_lib-* dir, fail fast - # instead of silently linking two ORT versions (duplicate symbols - # / wrong version). Re-run `download_deps.py` to prune stale dirs - # after a version bump, or remove the old dir by hand. case "$f" in - */onnxruntime-linux-x64-static_lib-*/lib/*.a) - local vdir="${f#*/onnxruntime-linux-x64-static_lib-}" - vdir="${vdir%%/*}" - if [ -z "$seen_version_dir" ]; then - seen_version_dir="$vdir" - elif [ "$seen_version_dir" != "$vdir" ]; then - echo " Error: multiple ONNX Runtime versions found under $ONNXRUNTIME_STATIC_PREFIX" >&2 - echo " $seen_version_dir AND $vdir" >&2 - echo " Remove the stale version dir (or re-run download_deps.py to prune it)." >&2 - return 1 - fi - ;; + # Only collect .a from the dir matching the required version. + */onnxruntime-linux-x64-static_lib-"${ort_version}"*/lib/*.a) + ort_a="$ort_a $f" ;; esac - ort_a="$ort_a $f" done < <(find "$ONNXRUNTIME_STATIC_PREFIX" -type f -name '*.a' 2>/dev/null) if [ -n "$ort_a" ]; then @@ -604,7 +638,13 @@ setup_cgo_env() { # dynamic symbol table, which is what the binding's dlopen(NULL)+dlsym # lookup needs at runtime (no --export-dynamic required). else - echo " onnxruntime static_lib dir has no .a files; the in-process DeepDoc backend cannot link ORT" >&2 + local avail + avail="$(find "$ONNXRUNTIME_STATIC_PREFIX" -maxdepth 1 -type d \ + -name 'onnxruntime-linux-x64-static_lib-*' -exec basename {} \; 2>/dev/null | tr '\n' ' ')" + echo " Error: no ONNX Runtime ${ort_version} static lib under $ONNXRUNTIME_STATIC_PREFIX" >&2 + echo " available: ${avail:-}" >&2 + echo " DeepDocORTVersion=${ort_version}; bake/download the matching ORT (or update DeepDocORTVersion)." >&2 + return 1 fi else echo " onnxruntime static_lib not found ($ONNXRUNTIME_STATIC_PREFIX); the in-process DeepDoc backend cannot link ORT" >&2 @@ -809,6 +849,8 @@ OPTIONS: InfiniFlow/deepdoc model snapshot; self-skip otherwise). e.g. `$0 --test-native` --clean, -C Clean all build artifacts + --check-ort-version Verify the ONNX Runtime native version is declared + consistently across all sources (exit 1 on mismatch). --run, -r Build and run the server --strip, -s Strip debug symbols from Go binaries (-ldflags="-s -w") (disabled by default, useful for smaller production binaries) @@ -927,6 +969,9 @@ main() { --clean|-C) clean ;; + --check-ort-version) + check_ort_version_consistency + ;; --run|-r) check_cpp_deps check_go_deps diff --git a/internal/common/environments.go b/internal/common/environments.go index 3b4ed59c97d..9740817bbba 100644 --- a/internal/common/environments.go +++ b/internal/common/environments.go @@ -267,11 +267,12 @@ func HasModelFiles(dir string) bool { } // DeepDocORTVersion is the onnxruntime native release the in-process (Go) -// DeepDoc backend is built and tested against (e.g. "1.23.2"). It is ONE OF -// THREE raw version declarations that must stay equal (the other two are -// ORT_VERSION in ragflow_deps/download_go_deps.py and ragflow_deps/download_deps.py) -// — NOT a single source of truth. The download URL and extracted dir name are -// built from those ORT_VERSION constants, not from this one. The Go binding +// DeepDoc backend is built and tested against (e.g. "1.29.0"). It is ONE OF +// FOUR raw version declarations that must stay equal (the other three are +// ORT_VERSION in ragflow_deps/download_go_deps.py and ragflow_deps/download_deps.py, +// and ARG ORT_VERSION in Dockerfile_go) — NOT a single source of truth. The +// download URL and extracted dir name are built from those ORT_VERSION +// constants, not from this one. The Go binding // (github.com/infiniflow/onnxruntime_go, the org mirror of yalue/onnxruntime_go) // and the pip onnxruntime== pin must // track this MINOR version: the binding uses its own release numbering @@ -279,11 +280,15 @@ func HasModelFiles(dir string) bool { // the same minor line. ONNX Runtime is linked statically (libonnxruntime.a), // so there is no .so / SONAME at runtime. // -// To bump ORT, ALL of the following must change together (drift breaks the -// static link or the runtime OrtGetApiBase lookup): -// - DeepDocORTVersion (here, Go) AND ORT_VERSION in BOTH -// ragflow_deps/download_go_deps.py and ragflow_deps/download_deps.py; -// - the onnxruntime== pin in pyproject.toml and the onnxruntime / -// onnxruntime-gpu pins in .github/workflows/deepdoc-drift.yml; +// To bump ORT, the four Go-side native pins above must change together +// (drift breaks the static link or the runtime OrtGetApiBase lookup): +// - DeepDocORTVersion (here, Go) +// - ORT_VERSION in ragflow_deps/download_go_deps.py +// - ORT_VERSION in ragflow_deps/download_deps.py +// - ARG ORT_VERSION in Dockerfile_go +// +// Separately, keep these on the same ORT minor line but version them +// independently of the Go native lib (see pyproject.toml / development.md): +// - the onnxruntime== / onnxruntime-gpu== pins in pyproject.toml (Python side) // - the onnxruntime_go binding minor in go.mod. -const DeepDocORTVersion = "1.23.2" +const DeepDocORTVersion = "1.29.0" diff --git a/internal/development.md b/internal/development.md index 37a39164dc2..12c59c8ca9a 100644 --- a/internal/development.md +++ b/internal/development.md @@ -103,6 +103,19 @@ python3 ragflow_deps/download_go_deps.py > startup, so the remedy is always to seed the static lib above, never to build > without it. +> **Note**: The ONNX Runtime native version is pinned in several Go-side places +> that must stay in sync. Bumping it in one spot and not the others fails the +> build with `Error: ONNX Runtime version is inconsistent`: +> - `internal/common/environments.go` — `DeepDocORTVersion` +> - `Dockerfile_go` — `ARG ORT_VERSION` +> - `ragflow_deps/download_go_deps.py` and `ragflow_deps/download_deps.py` — `ORT_VERSION` +> +> `build.sh` runs this consistency check automatically before the Go build +> (through `check_go_deps`) and fails fast on any mismatch. Run it on demand +> with `./build.sh --check-ort-version`. To upgrade ORT, edit every entry above +> to the same version, then run the check. The Python pip `onnxruntime==` pin in +> `pyproject.toml` is versioned independently and is intentionally not part of +> this check. ### 1.5 Build RAGFlow diff --git a/pyproject.toml b/pyproject.toml index 6e328ff646f..84a857e6d04 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -75,8 +75,8 @@ dependencies = [ "mypy-boto3-s3==1.40.26", "Office365-REST-Python-Client==2.6.2", "ollama>=0.5.0", - "onnxruntime==1.23.2; sys_platform == 'darwin' or platform_machine != 'x86_64'", # must match internal/common.DeepDocORTVersion (native ORT minor) - "onnxruntime-gpu==1.23.2; sys_platform != 'darwin' and platform_machine == 'x86_64'", # must match internal/common.DeepDocORTVersion (native ORT minor) + "onnxruntime==1.23.2; sys_platform == 'darwin' or platform_machine != 'x86_64'", # Python-side only; versioned independently of the Go native ORT static lib (internal/common.DeepDocORTVersion) + "onnxruntime-gpu==1.23.2; sys_platform != 'darwin' and platform_machine == 'x86_64'", # Python-side only; versioned independently of the Go native ORT static lib (internal/common.DeepDocORTVersion) "opencv-python==4.10.0.84", "opencv-python-headless==4.10.0.84", "opendal>=0.45.0,<0.46.0", diff --git a/ragflow_deps/download_deps.py b/ragflow_deps/download_deps.py index adcaf1a9382..f7c7bb60529 100644 --- a/ragflow_deps/download_deps.py +++ b/ragflow_deps/download_deps.py @@ -43,12 +43,36 @@ import nltk from huggingface_hub import snapshot_download -# mirrors internal/common.DeepDocORTVersion (Go in-process backend). Single -# source for the onnxruntime native release: the download URL, .tgz name, -# extracted dir name, and SONAME below are all derived from it. The pip -# onnxruntime== pin (pyproject.toml) and the onnxruntime_go binding minor -# (go.mod) must stay on the same minor line. -ORT_VERSION = "1.23.2" +# mirrors internal/common.DeepDocORTVersion (Go in-process backend). ONE OF +# FOUR places (with that Go constant, ORT_VERSION in ragflow_deps/download_go_deps.py, +# and ARG ORT_VERSION in Dockerfile_go) that must carry the same ONNX Runtime +# native release for the statically-linked Go DeepDoc backend. This file's +# download URL and extracted dir name are derived from ORT_VERSION here, but +# there is no single source of truth — keep all four equal. build.sh +# --check-ort-version greps this file (and the other three) to fail fast on +# drift. (The Python pip onnxruntime== pin in pyproject.toml is versioned +# independently and is not part of this check.) +# +# Source of the native static archives: infiniflow/ragflow-build (our own +# ORT-only minimal build), NOT the third-party csukuangfj/onnxruntime-libs +# account. The release tag is `onnxruntime-v{ORT_VERSION}` and the asset is +# `onnxruntime-v{ORT_VERSION}-linux-x86_64.zip`. +ORT_VERSION = "1.29.0" + + +def _ort_asset_name(version): + """Release asset filename under infiniflow/ragflow-build tag onnxruntime-v{version}.""" + return f"onnxruntime-v{version}-linux-x86_64.zip" + + +def _ort_extracted_dir(version): + """Top-level directory name INSIDE the release zip (what extractall creates).""" + return f"onnxruntime-v{version}-linux-x86_64" + + +def _ort_normalized_dir(version): + """Directory name build.sh's `find ... -name '*.a'` glob expects under static_lib.""" + return f"onnxruntime-linux-x64-static_lib-{version}-glibc2_28" def get_urls(use_china_mirrors=False) -> list[str | list[str]]: @@ -91,14 +115,15 @@ def get_urls(use_china_mirrors=False) -> list[str | list[str]]: # kernels are dropped; only OrtGetApiBase is exported, via # --dynamic-list), so no libonnxruntime.so is needed at runtime — # OrtGetApiBase is resolved via dlopen(NULL) (the process-global - # symbol table, not the executable's own path). csukuangfj's - # static_lib build is - # CPU-only and glibc2_28-based, matching ORT_VERSION's C-API line - # (ABI-compatible with onnxruntime_go) and the onnxruntime the - # Python goldens were generated with. + # symbol table, not the executable's own path). Our own + # infiniflow/ragflow-build ORT-only minimal build + # (onnxruntime-v{ORT_VERSION}) is CPU-only and glibc2_28-based, + # matching ORT_VERSION's C-API line (ABI-compatible with + # onnxruntime_go) and the onnxruntime the Python goldens were + # generated with. [ - f"https://github.com/csukuangfj/onnxruntime-libs/releases/download/v{ORT_VERSION}/onnxruntime-linux-x64-static_lib-{ORT_VERSION}-glibc2_28.zip", - f"onnxruntime-linux-x64-static_lib-{ORT_VERSION}-glibc2_28.zip", + f"https://github.com/infiniflow/ragflow-build/releases/download/onnxruntime-v{ORT_VERSION}/{_ort_asset_name(ORT_VERSION)}", + _ort_asset_name(ORT_VERSION), ], ] else: @@ -140,14 +165,15 @@ def get_urls(use_china_mirrors=False) -> list[str | list[str]]: # kernels are dropped; only OrtGetApiBase is exported, via # --dynamic-list), so no libonnxruntime.so is needed at runtime — # OrtGetApiBase is resolved via dlopen(NULL) (the process-global - # symbol table, not the executable's own path). csukuangfj's - # static_lib build is - # CPU-only and glibc2_28-based, matching ORT_VERSION's C-API line - # (ABI-compatible with onnxruntime_go) and the onnxruntime the - # Python goldens were generated with. + # symbol table, not the executable's own path). Our own + # infiniflow/ragflow-build ORT-only minimal build + # (onnxruntime-v{ORT_VERSION}) is CPU-only and glibc2_28-based, + # matching ORT_VERSION's C-API line (ABI-compatible with + # onnxruntime_go) and the onnxruntime the Python goldens were + # generated with. [ - f"https://github.com/csukuangfj/onnxruntime-libs/releases/download/v{ORT_VERSION}/onnxruntime-linux-x64-static_lib-{ORT_VERSION}-glibc2_28.zip", - f"onnxruntime-linux-x64-static_lib-{ORT_VERSION}-glibc2_28.zip", + f"https://github.com/infiniflow/ragflow-build/releases/download/onnxruntime-v{ORT_VERSION}/{_ort_asset_name(ORT_VERSION)}", + _ort_asset_name(ORT_VERSION), ], ] @@ -197,7 +223,7 @@ def download_model(repository_id): ("pdfium-linux-x64-static.tgz", "pdfium-static"), ("pdf_oxide-go-ffi-linux-amd64.tar.gz", "pdf_oxide"), ("office_oxide-linux-x86_64.tar.gz", "office_oxide"), - (f"onnxruntime-linux-x64-static_lib-{ORT_VERSION}-glibc2_28.zip", os.path.join("onnxruntime", "static_lib")), + (_ort_asset_name(ORT_VERSION), os.path.join("onnxruntime", "static_lib")), ] import tarfile import zipfile @@ -209,7 +235,7 @@ def _prune_stale_onnxruntime(static_lib_dir, version): symbols / wrong version, silently).""" if not os.path.isdir(static_lib_dir): return - expected = f"onnxruntime-linux-x64-static_lib-{version}-glibc2_28" + expected = _ort_normalized_dir(version) for name in os.listdir(static_lib_dir): if not name.startswith("onnxruntime-linux-x64-static_lib-"): continue @@ -226,8 +252,8 @@ def _prune_stale_onnxruntime(static_lib_dir, version): continue target = os.path.join(native_deps_dir, subdir) - # ONNX Runtime ships a version-stamped top-level dir inside the zip - # (onnxruntime-linux-x64-static_lib--glibc2_28/). A plain + # The infiniflow/ragflow-build release zip carries a top-level dir + # named onnxruntime-v{ORT_VERSION}-linux-x86_64. A plain # "any .a present?" skip would keep a STALE version in place after a # bump: the new zip downloads, but extraction is skipped because the # old .a is still under static_lib, so the bump silently does nothing. @@ -235,7 +261,7 @@ def _prune_stale_onnxruntime(static_lib_dir, version): # already extracted. if subdir == os.path.join("onnxruntime", "static_lib"): _prune_stale_onnxruntime(target, ORT_VERSION) - version_dir = os.path.join(target, f"onnxruntime-linux-x64-static_lib-{ORT_VERSION}-glibc2_28") + version_dir = os.path.join(target, _ort_normalized_dir(ORT_VERSION)) if os.path.isdir(version_dir) and any(f.endswith(".a") for _, _, files in os.walk(version_dir) for f in files): print(f" ✓ {subdir} ({ORT_VERSION}) already extracted to {version_dir}") continue @@ -248,6 +274,19 @@ def _prune_stale_onnxruntime(static_lib_dir, version): if archive_path.endswith(".zip"): with zipfile.ZipFile(archive_path) as zf: zf.extractall(target) + # The infiniflow/ragflow-build release zip carries a top-level dir + # named onnxruntime-v{version}-linux-x86_64, but build.sh's glob and + # the stale checks above all expect + # onnxruntime-linux-x64-static_lib-{version}-glibc2_28. Rename it so + # every consumer shares one name convention (driven by ORT_VERSION). + if subdir == os.path.join("onnxruntime", "static_lib"): + extracted = os.path.join(target, _ort_extracted_dir(ORT_VERSION)) + normalized = os.path.join(target, _ort_normalized_dir(ORT_VERSION)) + if os.path.isdir(extracted) and extracted != normalized: + if os.path.exists(normalized): + shutil.rmtree(normalized) + print(f" Renaming {os.path.basename(extracted)} → {os.path.basename(normalized)}") + os.rename(extracted, normalized) else: with tarfile.open(archive_path) as tf: tf.extractall(target) diff --git a/ragflow_deps/download_go_deps.py b/ragflow_deps/download_go_deps.py index 36f83744d44..92a56f07ebe 100644 --- a/ragflow_deps/download_go_deps.py +++ b/ragflow_deps/download_go_deps.py @@ -53,13 +53,35 @@ import requests # Mirrors internal/common.DeepDocORTVersion (Go in-process backend). ONE OF -# THREE places (with that Go constant and the ORT_VERSION in -# ragflow_deps/download_deps.py) that must carry the same ONNX Runtime native -# release for the statically-linked Go DeepDoc backend. There is no single -# source of truth — keep all three equal. The pip onnxruntime== pin -# (pyproject.toml) and the onnxruntime_go binding minor (go.mod) must stay on -# the same minor line. -ORT_VERSION = "1.23.2" +# FOUR places (with that Go constant, ORT_VERSION in ragflow_deps/download_deps.py, +# and ARG ORT_VERSION in Dockerfile_go) that must carry the same ONNX Runtime +# native release for the statically-linked Go DeepDoc backend. There is no +# single source of truth — keep all four equal. build.sh --check-ort-version +# greps this file (and the other three) to fail fast on drift. (The Python pip +# onnxruntime== pin in pyproject.toml is versioned independently and is not +# part of this check.) +# +# Source of the native static archives: infiniflow/ragflow-build (our own +# ORT-only minimal build), NOT the third-party csukuangfj/onnxruntime-libs +# account. The release tag is `onnxruntime-v{ORT_VERSION}` and the asset is +# `onnxruntime-v{ORT_VERSION}-linux-x86_64.zip`. +ORT_VERSION = "1.29.0" + + +def _ort_asset_name(version): + """Release asset filename under infiniflow/ragflow-build tag onnxruntime-v{version}.""" + return f"onnxruntime-v{version}-linux-x86_64.zip" + + +def _ort_extracted_dir(version): + """Top-level directory name INSIDE the release zip (what extractall creates).""" + return f"onnxruntime-v{version}-linux-x86_64" + + +def _ort_normalized_dir(version): + """Directory name build.sh's `find ... -name '*.a'` glob expects under static_lib.""" + return f"onnxruntime-linux-x64-static_lib-{version}-glibc2_28" + # Mirrors internal/common.DeepDocModelFiles (Go in-process DeepDoc backend). # These are the ONLY weights the Go backend loads; the full InfiniFlow/deepdoc @@ -76,7 +98,7 @@ def prune_stale_onnxruntime(static_lib_dir, version): symbols / wrong version, silently).""" if not os.path.isdir(static_lib_dir): return - expected = f"onnxruntime-linux-x64-static_lib-{version}-glibc2_28" + expected = _ort_normalized_dir(version) for name in os.listdir(static_lib_dir): if not name.startswith("onnxruntime-linux-x64-static_lib-"): continue @@ -97,8 +119,8 @@ def extract_onnxruntime(static_lib_dir, archive_path, version): `static_lib_dir`. Returns True when that version is available afterwards (extracted now or already present), False when the archive is missing. - ORT ships a version-stamped top-level dir inside the zip - (onnxruntime-linux-x64-static_lib--glibc2_28/), so a present + The infiniflow/ragflow-build release zip carries a top-level dir named + onnxruntime-v{version}-linux-x86_64, so a present `static_lib_dir` is NOT evidence that THIS version is extracted: after a version bump the stale dir is pruned and the new one must be extracted. """ @@ -106,7 +128,7 @@ def extract_onnxruntime(static_lib_dir, archive_path, version): print(f" Skipping extraction: {os.path.basename(archive_path)} not found") return False prune_stale_onnxruntime(static_lib_dir, version) - version_dir = os.path.join(static_lib_dir, f"onnxruntime-linux-x64-static_lib-{version}-glibc2_28") + version_dir = os.path.join(static_lib_dir, _ort_normalized_dir(version)) if os.path.isdir(version_dir) and has_static_archives(version_dir): print(f" ✓ onnxruntime/static_lib ({version}) already extracted to {version_dir}") return True @@ -114,6 +136,18 @@ def extract_onnxruntime(static_lib_dir, archive_path, version): print(f" Extracting {os.path.basename(archive_path)} → {static_lib_dir}") with zipfile.ZipFile(archive_path) as zf: zf.extractall(static_lib_dir) + # The infiniflow/ragflow-build release zip carries a top-level dir named + # onnxruntime-v{version}-linux-x86_64, but build.sh's glob and the stale + # checks above all expect onnxruntime-linux-x64-static_lib-{version}-glibc2_28. + # Rename it so every consumer shares one name convention (driven by + # ORT_VERSION). + extracted = os.path.join(static_lib_dir, _ort_extracted_dir(version)) + normalized = os.path.join(static_lib_dir, _ort_normalized_dir(version)) + if os.path.isdir(extracted) and extracted != normalized: + if os.path.exists(normalized): + shutil.rmtree(normalized) + print(f" Renaming {os.path.basename(extracted)} → {os.path.basename(normalized)}") + os.rename(extracted, normalized) return True @@ -143,8 +177,8 @@ def get_urls(use_china_mirrors=False) -> list[str | list[str]]: ["https://gh-proxy.com/https://github.com/yfedoseev/pdf_oxide/releases/download/v0.3.73/pdf_oxide-go-ffi-linux-amd64.tar.gz", "pdf_oxide-go-ffi-linux-amd64.tar.gz"], ["https://gh-proxy.com/https://github.com/yfedoseev/office_oxide/releases/download/v0.1.9/native-linux-x86_64.tar.gz", "office_oxide-linux-x86_64.tar.gz"], [ - f"https://gh-proxy.com/https://github.com/csukuangfj/onnxruntime-libs/releases/download/v{ORT_VERSION}/onnxruntime-linux-x64-static_lib-{ORT_VERSION}-glibc2_28.zip", - f"onnxruntime-linux-x64-static_lib-{ORT_VERSION}-glibc2_28.zip", + f"https://gh-proxy.com/https://github.com/infiniflow/ragflow-build/releases/download/onnxruntime-v{ORT_VERSION}/{_ort_asset_name(ORT_VERSION)}", + _ort_asset_name(ORT_VERSION), ], ] else: @@ -172,8 +206,8 @@ def get_urls(use_china_mirrors=False) -> list[str | list[str]]: ["https://github.com/yfedoseev/pdf_oxide/releases/download/v0.3.73/pdf_oxide-go-ffi-linux-amd64.tar.gz", "pdf_oxide-go-ffi-linux-amd64.tar.gz"], ["https://github.com/yfedoseev/office_oxide/releases/download/v0.1.9/native-linux-x86_64.tar.gz", "office_oxide-linux-x86_64.tar.gz"], [ - f"https://github.com/csukuangfj/onnxruntime-libs/releases/download/v{ORT_VERSION}/onnxruntime-linux-x64-static_lib-{ORT_VERSION}-glibc2_28.zip", - f"onnxruntime-linux-x64-static_lib-{ORT_VERSION}-glibc2_28.zip", + f"https://github.com/infiniflow/ragflow-build/releases/download/onnxruntime-v{ORT_VERSION}/{_ort_asset_name(ORT_VERSION)}", + _ort_asset_name(ORT_VERSION), ], ] @@ -312,7 +346,7 @@ def download_go_models(use_china_mirrors=False): if not extract_onnxruntime( os.path.join(native_deps_dir, "onnxruntime", "static_lib"), - os.path.join(os.getcwd(), f"onnxruntime-linux-x64-static_lib-{ORT_VERSION}-glibc2_28.zip"), + os.path.join(os.getcwd(), _ort_asset_name(ORT_VERSION)), ORT_VERSION, ): # The archive was not downloaded or failed to extract, so no .a landed. diff --git a/ragflow_deps/test_download_go_deps.py b/ragflow_deps/test_download_go_deps.py index 66607972368..78c834ad1b8 100644 --- a/ragflow_deps/test_download_go_deps.py +++ b/ragflow_deps/test_download_go_deps.py @@ -4,17 +4,30 @@ # tests must guarantee the archive is really landed on disk — above all after an # ORT version bump, where the zip's version-stamped top-level dir changes but # static_lib/ still exists from the previous run. +# +# The release zip from infiniflow/ragflow-build carries a top-level dir named +# onnxruntime-v{version}-linux-x86_64; extract_onnxruntime() must rename it to +# the build.sh-expected onnxruntime-linux-x64-static_lib-{version}-glibc2_28 so +# every consumer shares one name convention. These tests pin that rename. import os import zipfile -from download_go_deps import extract_onnxruntime, has_static_archives +from download_go_deps import ( + _ort_asset_name, + _ort_extracted_dir, + _ort_normalized_dir, + extract_onnxruntime, + has_static_archives, +) def make_ort_zip(path, version): - """Build a zip shaped like the upstream ORT release: a version-stamped - top-level dir holding lib/libonnxruntime.a.""" - member = f"onnxruntime-linux-x64-static_lib-{version}-glibc2_28/lib/libonnxruntime.a" + """Build a zip shaped like the infiniflow/ragflow-build ORT release: a + top-level dir named onnxruntime-v{version}-linux-x86_64 holding + lib/libonnxruntime.a. extract_onnxruntime() must rename it to the + build.sh-expected onnxruntime-linux-x64-static_lib-{version}-glibc2_28.""" + member = f"{_ort_extracted_dir(version)}/lib/libonnxruntime.a" with zipfile.ZipFile(path, "w") as zf: zf.writestr(member, b"!\nort-payload") return path @@ -23,12 +36,14 @@ def make_ort_zip(path, version): def test_extracts_on_first_run(tmp_path): # static_lib/ does not exist yet: the plain first-run path. static_lib = tmp_path / "onnxruntime" / "static_lib" - version = "1.23.2" - archive = make_ort_zip(tmp_path / f"onnxruntime-linux-x64-static_lib-{version}-glibc2_28.zip", version) + version = "1.29.0" + archive = make_ort_zip(tmp_path / _ort_asset_name(version), version) assert extract_onnxruntime(str(static_lib), str(archive), version) is True - version_dir = static_lib / f"onnxruntime-linux-x64-static_lib-{version}-glibc2_28" + extracted = static_lib / _ort_extracted_dir(version) + assert not extracted.exists(), "release zip top-level dir must be renamed away" + version_dir = static_lib / _ort_normalized_dir(version) assert version_dir.is_dir() assert has_static_archives(str(version_dir)) @@ -40,30 +55,32 @@ def test_extracts_after_version_bump_when_static_lib_exists(tmp_path): build.sh's ORT guard rejects the build.""" static_lib = tmp_path / "onnxruntime" / "static_lib" static_lib.mkdir(parents=True) - stale = static_lib / "onnxruntime-linux-x64-static_lib-1.23.1-glibc2_28" + stale = static_lib / _ort_normalized_dir("1.28.0") (stale / "lib").mkdir(parents=True) (stale / "lib" / "libonnxruntime.a").write_bytes(b"old-ort") - version = "1.23.2" - archive = make_ort_zip(tmp_path / f"onnxruntime-linux-x64-static_lib-{version}-glibc2_28.zip", version) + version = "1.29.0" + archive = make_ort_zip(tmp_path / _ort_asset_name(version), version) assert extract_onnxruntime(str(static_lib), str(archive), version) is True assert not stale.exists(), "stale ORT version should be pruned" - version_dir = static_lib / f"onnxruntime-linux-x64-static_lib-{version}-glibc2_28" + extracted = static_lib / _ort_extracted_dir(version) + assert not extracted.exists(), "release zip top-level dir must be renamed away" + version_dir = static_lib / _ort_normalized_dir(version) assert version_dir.is_dir(), "bumped ORT version was silently not extracted" assert has_static_archives(str(version_dir)), "bumped ORT version landed no .a" def test_skips_when_archive_missing(tmp_path): static_lib = tmp_path / "onnxruntime" / "static_lib" - assert extract_onnxruntime(str(static_lib), str(tmp_path / "missing.zip"), "1.23.2") is False + assert extract_onnxruntime(str(static_lib), str(tmp_path / "missing.zip"), "1.29.0") is False def test_idempotent_when_matching_version_already_present(tmp_path): static_lib = tmp_path / "onnxruntime" / "static_lib" - version = "1.23.2" - archive = make_ort_zip(tmp_path / f"onnxruntime-linux-x64-static_lib-{version}-glibc2_28.zip", version) + version = "1.29.0" + archive = make_ort_zip(tmp_path / _ort_asset_name(version), version) assert extract_onnxruntime(str(static_lib), str(archive), version) is True before = sorted(os.listdir(static_lib)) From 4ad809634f6cff7cb032892a73a936a6be81db85 Mon Sep 17 00:00:00 2001 From: taek105 <101572128+taek105@users.noreply.github.com> Date: Fri, 11 Sep 2026 13:39:19 +0900 Subject: [PATCH 102/568] fix(document): validate immutable fields on update (#19444) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix #16831 — Go document endpoints now reject changes to ingestion-managed fields (progress, chunk_num, token_num, etc.), including zero-valued. PUT now persists name only, not full record. --- internal/handler/document.go | 12 +- internal/handler/document_test.go | 70 ++++++++- internal/service/document/document_crud.go | 46 +++--- .../document/document_dataset_update.go | 25 ++-- internal/service/document/document_test.go | 138 ++++++++++++++++-- .../service/document/document_validation.go | 62 ++++++++ 6 files changed, 310 insertions(+), 43 deletions(-) create mode 100644 internal/service/document/document_validation.go diff --git a/internal/handler/document.go b/internal/handler/document.go index cb4ad6f9f48..e58b9534fa0 100644 --- a/internal/handler/document.go +++ b/internal/handler/document.go @@ -50,7 +50,7 @@ var IMG_BASE64_PREFIX = "data:image/png;base64," // documentServiceIface defines the DocumentService methods used by DocumentHandler. type documentServiceIface interface { GetDocumentByID(ctx context.Context, id string) (*document.DocumentResponse, error) - UpdateDocument(ctx context.Context, id string, req *document.UpdateDocumentRequest) error + UpdateDocument(ctx context.Context, id string, req *document.UpdateDocumentRequest) (common.ErrorCode, error) DeleteDocument(ctx context.Context, id string) error DeleteDocuments(ctx context.Context, ids []string, deleteAll bool, datasetID, userID string) (int, error) ParseDocuments(ctx context.Context, datasetID, userID string, docIDs []string) ([]*service.ParseDocumentResponse, error) @@ -344,10 +344,12 @@ func (h *DocumentHandler) UpdateDocument(c *gin.Context) { return } - if err = h.documentService.UpdateDocument(ctx, id, &req); err != nil { - c.JSON(http.StatusInternalServerError, gin.H{ - "error": err.Error(), - }) + if errorCode, err = h.documentService.UpdateDocument(ctx, id, &req); err != nil { + if errorCode == common.CodeServerError { + common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, errorCode, nil, err.Error()) + } else { + common.ErrorWithCode(c, errorCode, err.Error()) + } return } diff --git a/internal/handler/document_test.go b/internal/handler/document_test.go index 8fa26460664..0cbcdd999aa 100644 --- a/internal/handler/document_test.go +++ b/internal/handler/document_test.go @@ -48,6 +48,8 @@ type fakeDocumentService struct { docErr error updateCalled bool updatedID string + updateCode common.ErrorCode + updateErr error deleteCalled bool deletedID string stopResult map[string]interface{} @@ -155,10 +157,10 @@ func (f *fakeDocumentService) GetDocumentByID(ctx context.Context, id string) (* } return nil, fmt.Errorf("document not found") } -func (f *fakeDocumentService) UpdateDocument(ctx context.Context, id string, req *document.UpdateDocumentRequest) error { +func (f *fakeDocumentService) UpdateDocument(ctx context.Context, id string, req *document.UpdateDocumentRequest) (common.ErrorCode, error) { f.updateCalled = true f.updatedID = id - return nil + return f.updateCode, f.updateErr } func (f *fakeDocumentService) DeleteDocument(ctx context.Context, id string) error { f.deleteCalled = true @@ -519,6 +521,70 @@ func TestUpdateDocumentHandler_Accessible(t *testing.T) { } } +func TestUpdateDocumentHandler_ValidationError(t *testing.T) { + setupDocumentPermissionDB(t, true) + + fake := &fakeDocumentService{ + doc: &document.DocumentResponse{ID: "doc-1", KbID: "kb-owner"}, + updateCode: common.CodeDataError, + updateErr: errors.New("can't change `progress`"), + } + h := &DocumentHandler{ + documentService: fake, + datasetService: dataset.NewDatasetService(), + } + + c, w := setupGinContextWithUser("PUT", "/api/v1/documents/doc-1", `{"progress":0.5}`) + c.Params = gin.Params{{Key: "id", Value: "doc-1"}} + h.UpdateDocument(c) + + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String()) + } + var resp map[string]interface{} + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp["code"] != float64(common.CodeDataError) { + t.Fatalf("expected data error, got %v", resp) + } + if resp["message"] != "can't change `progress`" { + t.Fatalf("unexpected message: %v", resp["message"]) + } +} + +func TestUpdateDocumentHandler_ServerError(t *testing.T) { + setupDocumentPermissionDB(t, true) + + fake := &fakeDocumentService{ + doc: &document.DocumentResponse{ID: "doc-1", KbID: "kb-owner"}, + updateCode: common.CodeServerError, + updateErr: errors.New("database unavailable"), + } + h := &DocumentHandler{ + documentService: fake, + datasetService: dataset.NewDatasetService(), + } + + c, w := setupGinContextWithUser("PUT", "/api/v1/documents/doc-1", `{"name":"new.pdf"}`) + c.Params = gin.Params{{Key: "id", Value: "doc-1"}} + h.UpdateDocument(c) + + if w.Code != http.StatusInternalServerError { + t.Fatalf("expected 500, got %d: %s", w.Code, w.Body.String()) + } + var resp map[string]interface{} + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatal(err) + } + if resp["code"] != float64(common.CodeServerError) { + t.Fatalf("expected server error, got %v", resp) + } + if resp["message"] != "database unavailable" { + t.Fatalf("unexpected message: %v", resp["message"]) + } +} + func setupUploadHandlerDB(t *testing.T, role string) *gorm.DB { t.Helper() diff --git a/internal/service/document/document_crud.go b/internal/service/document/document_crud.go index 17bdb9097a6..add8615436d 100644 --- a/internal/service/document/document_crud.go +++ b/internal/service/document/document_crud.go @@ -115,32 +115,42 @@ func (s *DocumentService) GetDocumentByID(ctx context.Context, id string) (*Docu } // UpdateDocument update document -func (s *DocumentService) UpdateDocument(ctx context.Context, id string, req *UpdateDocumentRequest) error { +func (s *DocumentService) UpdateDocument(ctx context.Context, id string, req *UpdateDocumentRequest) (common.ErrorCode, error) { + if req == nil { + return common.CodeDataError, errors.New("invalid request payload") + } + document, err := s.documentDAO.GetByID(ctx, dao.DB, id) if err != nil { - return err + if dao.IsNotFoundErr(err) { + return common.CodeDataError, errors.New("document not found") + } + return common.CodeServerError, err } - if req.Name != nil { - document.Name = req.Name - } - if req.Run != nil { - document.Run = req.Run + if err = validateImmutableDocumentFields(document, immutableDocumentFields{ + chunkNum: req.ChunkNum, + chunkNumRequestName: "chunk_num", + tokenNum: req.TokenNum, + tokenNumRequestName: "token_num", + progress: req.Progress, + run: req.Run, + progressMsg: req.ProgressMsg, + }); err != nil { + return common.CodeDataError, err } - if req.TokenNum != nil { - document.TokenNum = *req.TokenNum - } - if req.ChunkNum != nil { - document.ChunkNum = *req.ChunkNum + + if req.Name == nil { + return common.CodeSuccess, nil } - if req.Progress != nil { - document.Progress = *req.Progress + kb, err := s.kbDAO.GetByID(ctx, dao.DB, document.KbID) + if err != nil { + return common.CodeServerError, err } - if req.ProgressMsg != nil { - document.ProgressMsg = req.ProgressMsg + if err = s.updateDocumentNameOnly(ctx, document, kb.TenantID, *req.Name); err != nil { + return common.CodeServerError, err } - - return s.documentDAO.Update(ctx, dao.DB, document) + return common.CodeSuccess, nil } // ApplyDocCounts records a pipeline run's chunk/token/duration counts on the diff --git a/internal/service/document/document_dataset_update.go b/internal/service/document/document_dataset_update.go index 72e933e65ce..c123e74745b 100644 --- a/internal/service/document/document_dataset_update.go +++ b/internal/service/document/document_dataset_update.go @@ -265,19 +265,19 @@ func (s *DocumentService) validateDatasetDocumentUpdate(ctx context.Context, dat return code, err } } - if present["chunk_count"] && req.ChunkCount != nil && *req.ChunkCount != 0 && *req.ChunkCount != doc.ChunkNum { - return common.CodeDataError, errors.New("can't change `chunk_count`") - } - if present["token_count"] && req.TokenCount != nil && *req.TokenCount != 0 && *req.TokenCount != doc.TokenNum { - return common.CodeDataError, errors.New("can't change `token_count`") - } if present["progress"] && req.Progress != nil { if *req.Progress > 1 { return common.CodeDataError, fmt.Errorf("Field: - Message: - Value: <%s>", pythonFloatRepr(*req.Progress)) } - if *req.Progress != 0 && math.Abs(*req.Progress-doc.Progress) > 1e-9 { - return common.CodeDataError, errors.New("can't change `progress`") - } + } + if err := validateImmutableDocumentFields(doc, immutableDocumentFields{ + chunkNum: requestField(req.ChunkCount, present["chunk_count"]), + chunkNumRequestName: "chunk_count", + tokenNum: requestField(req.TokenCount, present["token_count"]), + tokenNumRequestName: "token_count", + progress: requestField(req.Progress, present["progress"]), + }); err != nil { + return common.CodeDataError, err } if present["enabled"] { @@ -332,6 +332,13 @@ func (s *DocumentService) validateDatasetDocumentUpdate(ctx context.Context, dat return common.CodeSuccess, nil } +func requestField[T any](value *T, present bool) *T { + if !present { + return nil + } + return value +} + // validateDocumentName mirrors Python's validate_document_name: length check // (101), then extension check (101), then duplicate check (102). func (s *DocumentService) validateDocumentName(ctx context.Context, doc *entity.Document, newName string) (common.ErrorCode, error) { diff --git a/internal/service/document/document_test.go b/internal/service/document/document_test.go index 0cb58c004be..d5fc1525a55 100644 --- a/internal/service/document/document_test.go +++ b/internal/service/document/document_test.go @@ -2030,23 +2030,143 @@ func TestUpdateDatasetDocumentRejectsCounterMutation(t *testing.T) { } } -func TestUpdateDatasetDocumentAllowsZeroCounterLikePythonTruthyCheck(t *testing.T) { +func TestUpdateDatasetDocumentRejectsZeroImmutableFields(t *testing.T) { + zeroCount := int64(0) + zeroProgress := 0.0 + tests := []struct { + name string + request UpdateDatasetDocumentRequest + present map[string]bool + wantErr string + }{ + {name: "chunk count", request: UpdateDatasetDocumentRequest{ChunkCount: &zeroCount}, present: map[string]bool{"chunk_count": true}, wantErr: "can't change `chunk_count`"}, + {name: "token count", request: UpdateDatasetDocumentRequest{TokenCount: &zeroCount}, present: map[string]bool{"token_count": true}, wantErr: "can't change `token_count`"}, + {name: "progress", request: UpdateDatasetDocumentRequest{Progress: &zeroProgress}, present: map[string]bool{"progress": true}, wantErr: "can't change `progress`"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + db := setupServiceTestDB(t) + pushServiceDB(t, db) + insertTestKB(t, "kb-1", "tenant-1", 1, 10, 5) + insertTestDoc(t, "doc-1", "kb-1", 10, 5) + if err := db.Model(&entity.Document{}).Where("id = ?", "doc-1").Update("progress", 0.5).Error; err != nil { + t.Fatalf("prepare document: %v", err) + } + + _, code, err := testDocumentService(t).UpdateDatasetDocument(t.Context(), "tenant-1", "kb-1", "doc-1", &tt.request, tt.present) + if err == nil { + t.Fatalf("expected %s mutation error", tt.name) + } + if code != common.CodeDataError { + t.Fatalf("code = %v, want %v", code, common.CodeDataError) + } + if err.Error() != tt.wantErr { + t.Fatalf("err = %q, want %q", err.Error(), tt.wantErr) + } + }) + } +} + +func TestUpdateDocumentRejectsImmutableFieldChanges(t *testing.T) { + tests := []struct { + name string + request UpdateDocumentRequest + wantErr string + }{ + {name: "progress", request: UpdateDocumentRequest{Progress: float64Ptr(0)}, wantErr: "can't change `progress`"}, + {name: "run", request: UpdateDocumentRequest{Run: sptr("0")}, wantErr: "can't change `run`"}, + {name: "progress message", request: UpdateDocumentRequest{ProgressMsg: sptr("reset")}, wantErr: "can't change `progress_msg`"}, + {name: "chunk count", request: UpdateDocumentRequest{ChunkNum: int64Ptr(0)}, wantErr: "can't change `chunk_num`"}, + {name: "token count", request: UpdateDocumentRequest{TokenNum: int64Ptr(0)}, wantErr: "can't change `token_num`"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + db := setupServiceTestDB(t) + pushServiceDB(t, db) + insertTestDoc(t, "doc-1", "kb-1", 10, 5) + run := "3" + progressMsg := "parsing" + if err := db.Model(&entity.Document{}).Where("id = ?", "doc-1").Updates(map[string]interface{}{ + "progress": 0.5, + "run": run, + "progress_msg": progressMsg, + }).Error; err != nil { + t.Fatalf("prepare document: %v", err) + } + + code, err := testDocumentService(t).UpdateDocument(t.Context(), "doc-1", &tt.request) + if err == nil { + t.Fatalf("expected %s mutation error", tt.name) + } + if code != common.CodeDataError { + t.Fatalf("code = %v, want %v", code, common.CodeDataError) + } + if err.Error() != tt.wantErr { + t.Fatalf("err = %q, want %q", err.Error(), tt.wantErr) + } + }) + } +} + +func TestUpdateDocumentUsesSharedRenamePath(t *testing.T) { db := setupServiceTestDB(t) pushServiceDB(t, db) insertTestKB(t, "kb-1", "tenant-1", 1, 10, 5) - insertTestDoc(t, "doc-1", "kb-1", 10, 5) + insertNamedTestDoc(t, "doc-1", "kb-1", "old.pdf", 10, 5) + insertTestFile(t, "file-1", "folder-1", "old.pdf", sptr("old.pdf")) + insertTestFile2Document(t, "f2d-1", "file-1", "doc-1") + run := "3" + progressMsg := "complete" + if err := db.Model(&entity.Document{}).Where("id = ?", "doc-1").Updates(map[string]interface{}{ + "progress": 1.0, + "run": run, + "progress_msg": progressMsg, + }).Error; err != nil { + t.Fatalf("prepare document: %v", err) + } - chunkCount := int64(0) - svc := testDocumentService(t) - ctx := t.Context() - _, code, err := svc.UpdateDatasetDocument(ctx, "tenant-1", "kb-1", "doc-1", &UpdateDatasetDocumentRequest{ - ChunkCount: &chunkCount, - }, map[string]bool{"chunk_count": true}) + newName := "new.pdf" + progress := 1.0 + chunkNum := int64(5) + tokenNum := int64(10) + req := &UpdateDocumentRequest{ + Name: &newName, + Run: &run, + TokenNum: &tokenNum, + ChunkNum: &chunkNum, + Progress: &progress, + ProgressMsg: &progressMsg, + } + code, err := testDocumentService(t).UpdateDocument(t.Context(), "doc-1", req) if err != nil { - t.Fatalf("UpdateDatasetDocument failed: code=%v err=%v", code, err) + t.Fatalf("UpdateDocument failed: code=%v err=%v", code, err) + } + + doc, err := dao.NewDocumentDAO().GetByID(t.Context(), db, "doc-1") + if err != nil { + t.Fatalf("get document: %v", err) + } + if doc.Name == nil || *doc.Name != newName { + t.Fatalf("name = %v, want %q", doc.Name, newName) + } + file, err := dao.NewFileDAO().GetByID(t.Context(), db, "file-1") + if err != nil { + t.Fatalf("get file: %v", err) + } + if file.Name != newName { + t.Fatalf("file name = %q, want %q", file.Name, newName) + } + if doc.Progress != progress || doc.Run == nil || *doc.Run != run || doc.ProgressMsg == nil || *doc.ProgressMsg != progressMsg || doc.ChunkNum != chunkNum || doc.TokenNum != tokenNum { + t.Fatalf("immutable fields changed: %#v", doc) } } +func float64Ptr(value float64) *float64 { return &value } + +func int64Ptr(value int64) *int64 { return &value } + func TestUpdateDatasetDocumentRejectsUnsupportedParserIDForVisualDoc(t *testing.T) { db := setupServiceTestDB(t) pushServiceDB(t, db) diff --git a/internal/service/document/document_validation.go b/internal/service/document/document_validation.go new file mode 100644 index 00000000000..975437da671 --- /dev/null +++ b/internal/service/document/document_validation.go @@ -0,0 +1,62 @@ +// +// 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. +// + +package document + +import ( + "errors" + "fmt" + "math" + + "ragflow/internal/entity" +) + +type immutableDocumentFields struct { + chunkNum *int64 + chunkNumRequestName string + tokenNum *int64 + tokenNumRequestName string + progress *float64 + run *string + progressMsg *string +} + +func validateImmutableDocumentFields(doc *entity.Document, fields immutableDocumentFields) error { + if fields.chunkNum != nil && *fields.chunkNum != doc.ChunkNum { + return fmt.Errorf("can't change `%s`", fields.chunkNumRequestName) + } + if fields.tokenNum != nil && *fields.tokenNum != doc.TokenNum { + return fmt.Errorf("can't change `%s`", fields.tokenNumRequestName) + } + if fields.progress != nil && !documentProgressEqual(*fields.progress, doc.Progress) { + return errors.New("can't change `progress`") + } + if fields.run != nil && !optionalStringEqual(fields.run, doc.Run) { + return errors.New("can't change `run`") + } + if fields.progressMsg != nil && !optionalStringEqual(fields.progressMsg, doc.ProgressMsg) { + return errors.New("can't change `progress_msg`") + } + return nil +} + +func documentProgressEqual(a, b float64) bool { + return math.Abs(a-b) <= 1e-9*math.Max(math.Abs(a), math.Abs(b)) +} + +func optionalStringEqual(a, b *string) bool { + return a != nil && b != nil && *a == *b +} From bcf33c6238b6cf6e4c8c1232bcd431cde0f537d1 Mon Sep 17 00:00:00 2001 From: Sbaaoui Idriss <112825897+6ba3i@users.noreply.github.com> Date: Fri, 11 Sep 2026 13:37:01 +0800 Subject: [PATCH 103/568] fix(structure-graph): discover buckets from raw rows (#19523) --- api/apps/restful_apis/chunk_api.py | 58 +++++++++++-------- .../knowledge_compiler/structure/structure.go | 5 +- internal/service/dataset_structure_graph.go | 27 ++++++--- .../service/dataset_structure_graph_test.go | 21 +++++++ 4 files changed, 76 insertions(+), 35 deletions(-) diff --git a/api/apps/restful_apis/chunk_api.py b/api/apps/restful_apis/chunk_api.py index 3865cf942bd..a1473082386 100644 --- a/api/apps/restful_apis/chunk_api.py +++ b/api/apps/restful_apis/chunk_api.py @@ -911,31 +911,39 @@ def _resolve_bucket(row: dict) -> tuple[dict, dict]: return get_result(data=_response([bucket])) # ── normal mode: per-template subgraph sampling from the raw rows ── - # Metadata-only scan of the per-doc graph blob rows (one per - # (compile_kwd, template_id)) purely to discover buckets and resolve their - # display name/kind — WITHOUT loading the (potentially huge) - # content_with_weight. Each bucket's entities/relations are then fetched - # from the raw ``knowledge_graph_kwd`` rows with subgraph sampling. - meta_fields = ["compile_kwd", "compilation_template_ids", "compilation_template_kind_kwd"] - try: - res = await thread_pool_exec( - settings.docStoreConn.search, - meta_fields, - [], - {"doc_id": [document_id], "knowledge_graph_kwd": ["graph"]}, - [], - OrderByExpr(), - 0, - 1000, - index_name, - [dataset_id], - ) - meta_rows = settings.docStoreConn.get_fields(res, meta_fields) or {} - except Exception as e: - return server_error_response(e) - - # Discover unique buckets. A template can own multiple compile_kwd blob - # rows; scoping by template_id folds them together, matching prior behavior. + # Discover buckets from the authoritative entity/relation rows. The + # structure compiler no longer emits a synthetic ``graph`` row, and a + # paged metadata-only scan avoids loading payloads or truncating large docs. + meta_fields = ["id", "compile_kwd", "compilation_template_ids", "compilation_template_kind_kwd"] + meta_rows: dict = {} + page_size = 1000 + offset = 0 + while True: + try: + res = await thread_pool_exec( + settings.docStoreConn.search, + meta_fields, + [], + {"doc_id": [document_id], "knowledge_graph_kwd": ["entity", "relation"]}, + [], + OrderByExpr(), + offset, + page_size, + index_name, + [dataset_id], + ) + page_rows = settings.docStoreConn.get_fields(res, meta_fields) or {} + except Exception as e: + return server_error_response(e) + if not page_rows: + break + meta_rows.update(page_rows) + if len(page_rows) < page_size: + break + offset += page_size + + # Discover unique buckets. A template can own multiple raw entity/relation + # rows; scoping by template_id folds them together. bucket_metas: dict[str, dict] = {} bucket_scopes: dict[str, dict] = {} for row in meta_rows.values(): diff --git a/internal/ingestion/component/knowledge_compiler/structure/structure.go b/internal/ingestion/component/knowledge_compiler/structure/structure.go index d3af89ad92f..db99d62af34 100644 --- a/internal/ingestion/component/knowledge_compiler/structure/structure.go +++ b/internal/ingestion/component/knowledge_compiler/structure/structure.go @@ -177,9 +177,8 @@ func Run(ctx context.Context, deps common.Deps, param common.Param, inputs commo // return common.Outputs{}, err // } - // Buffer every product (plus the graph) in one slice; the component merges - // them into the upstream chunk stream (matching Python, which appends - // compiled units onto the chunk list). + // Buffer the deduplicated row products in one slice; the component merges + // them into the upstream chunk stream. products := append([]common.Product{}, prods...) // products = append(products, graphProduct) diff --git a/internal/service/dataset_structure_graph.go b/internal/service/dataset_structure_graph.go index d735422cbb9..633969b1f95 100644 --- a/internal/service/dataset_structure_graph.go +++ b/internal/service/dataset_structure_graph.go @@ -779,14 +779,27 @@ func (s *DatasetArtifactService) GetDocumentGraph(ctx context.Context, in Docume return resp, nil } - // normal mode: discover buckets from per-doc graph blob rows. "id" is - // required for the same reason as dataset discovery (Infinity only projects - // listed fields; graphRowSearch keys by id). + // normal mode: discover buckets from the authoritative entity/relation + // rows. The structure compiler no longer emits a synthetic graph row; + // page metadata only so large documents cannot hide later buckets. metaFields := []string{"id", "compile_kwd", "compilation_template_ids", "compilation_template_kind_kwd"} - metaRows, _, err := graphRowSearch(ctx, in.TenantID, in.DatasetID, metaFields, - map[string]interface{}{"doc_id": []string{in.DocumentID}, "knowledge_graph_kwd": []string{"graph"}}, nil, 0, 1000, nil) - if err != nil { - return nil, err + metaRows := map[string]map[string]interface{}{} + const pageSize = 1000 + for offset := 0; ; offset += pageSize { + page, _, searchErr := graphRowSearch(ctx, in.TenantID, in.DatasetID, metaFields, + map[string]interface{}{"doc_id": []string{in.DocumentID}, "knowledge_graph_kwd": []string{"entity", "relation"}}, nil, offset, pageSize, nil) + if searchErr != nil { + return nil, searchErr + } + if len(page) == 0 { + break + } + for id, row := range page { + metaRows[id] = row + } + if len(page) < pageSize { + break + } } bucketMetas := map[string]map[string]interface{}{} diff --git a/internal/service/dataset_structure_graph_test.go b/internal/service/dataset_structure_graph_test.go index 74a767b9e26..9772e44ca44 100644 --- a/internal/service/dataset_structure_graph_test.go +++ b/internal/service/dataset_structure_graph_test.go @@ -105,3 +105,24 @@ func TestRowTemplateID_FromList(t *testing.T) { t.Errorf("rowTemplateID = %q, want tid1", got) } } + +// TestResolveGraphBucket_UsesRawStructureMetadata covers the post-#19474 +// storage shape: entity/relation rows carry the template stamp, with no +// synthetic knowledge_graph_kwd="graph" row available for discovery. +func TestResolveGraphBucket_UsesRawStructureMetadata(t *testing.T) { + row := map[string]interface{}{ + "knowledge_graph_kwd": "entity", + "compilation_template_ids": []string{"tree-1"}, + "compilation_template_kind_kwd": "tree", + "compile_kwd": "tree", + } + meta, scope := resolveGraphBucket(row, map[string]map[string]interface{}{ + "tree-1": {"template_name": "Tree", "kind": "tree"}, + }, "doc-1") + if meta["template_id"] != "tree-1" || meta["template_name"] != "Tree" { + t.Fatalf("meta = %#v, want resolved template metadata", meta) + } + if got := scope["compilation_template_ids"].([]string); len(got) != 1 || got[0] != "tree-1" { + t.Fatalf("scope = %#v, want template-scoped raw-row filter", scope) + } +} From 3a1fc91bccd4fc92810c0d3952fc6267d780a717 Mon Sep 17 00:00:00 2001 From: huyua9 Date: Fri, 11 Sep 2026 13:38:09 +0800 Subject: [PATCH 104/568] fix: forward NumberInput ref to input (#18904) --- web/src/components/originui/number-input.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/src/components/originui/number-input.tsx b/web/src/components/originui/number-input.tsx index 9d5a6789e0c..7f2d621a323 100644 --- a/web/src/components/originui/number-input.tsx +++ b/web/src/components/originui/number-input.tsx @@ -198,7 +198,6 @@ const NumberInput = forwardRef< className, )} style={style} - ref={ref} > {hideIcons || ( + ) : undefined + } + >
@@ -150,18 +115,43 @@ function ParserItem({ name, index }: ParserItemProps) { ); } +type ParserFormProps = INextOperatorForm & { + // Dataset-side embeddings (settings page, document pipeline dialog) show a + // fixed set of file types; only the canvas parser allows add/remove. + fixedFileFormats?: boolean; +}; + +type AddFileTypeMenuItemProps = { + fileType: FileType; + onSelect: (fileType: FileType) => void; +}; + +function AddFileTypeMenuItem({ fileType, onSelect }: AddFileTypeMenuItemProps) { + const { t } = useTranslation(); + const handleSelect = useCallback(() => { + onSelect(fileType); + }, [onSelect, fileType]); + + return ( + + {t(`flow.fileFormatOptions.${fileType}`)} + + ); +} + const ParserForm = ({ node, onValuesChange, hideOutputs, externalErrors, -}: INextOperatorForm) => { + fixedFileFormats, +}: ParserFormProps) => { + const { t } = useTranslation(); const defaultModelDictionary = useFetchDefaultModelDictionary(); - const formValues = useFormValues(initialParserValues, node); - const defaultValues = useMemo( - () => withDefaultParserModels(formValues, defaultModelDictionary), - [formValues, defaultModelDictionary], - ); + // Show the saved values as-is: an empty llm_id means the user cleared the + // model, and the backend falls back to the tenant default at parse time. + // Prefilling it here would make a cleared model reappear and be written back. + const defaultValues = useFormValues(initialParserValues, node); const form = useForm>({ defaultValues, @@ -172,7 +162,7 @@ const ParserForm = ({ useSyncExternalFormErrors(form, externalErrors); const name = 'setups'; - const { fields } = useFieldArray({ + const { fields, append, remove } = useFieldArray({ name, control: form.control, }); @@ -180,14 +170,58 @@ const ParserForm = ({ useWatchFormChange(node?.id, form); useFormChangeCallback(form, onValuesChange); + const remainingFileTypes = useMemo(() => { + const presentFileTypes = new Set(fields.map((x) => x.fileFormat)); + return initialParserValues.setups + .map((x) => x.fileFormat) + .filter( + (fileType): fileType is FileType => + !!fileType && !presentFileTypes.has(fileType), + ); + }, [fields]); + + const handleAddFileType = useCallback( + (fileType: FileType) => { + const setup = buildInitialParserSetup(fileType, defaultModelDictionary); + if (setup) { + append(setup); + } + }, + [append, defaultModelDictionary], + ); + + const canRemove = !fixedFileFormats && fields.length > 1; + return (
{fields.map((field, index) => { return ( - + ); })} + {!fixedFileFormats && remainingFileTypes.length > 0 && ( + + + {t('flow.addFileType')} + + + {remainingFileTypes.map((fileType) => ( + + ))} + + + )} {!hideOutputs && (
diff --git a/web/src/pages/agent/form/parser-form/pdf-form-fields.tsx b/web/src/pages/agent/form/parser-form/pdf-form-fields.tsx index 01bca52d70a..a3fbb2a0225 100644 --- a/web/src/pages/agent/form/parser-form/pdf-form-fields.tsx +++ b/web/src/pages/agent/form/parser-form/pdf-form-fields.tsx @@ -14,7 +14,6 @@ import { useEffect, useMemo } from 'react'; import { useFormContext, useWatch } from 'react-hook-form'; import { useTranslation } from 'react-i18next'; import { useOwnerTenantId } from '../../context'; -import { FileType } from '../../constant/pipeline'; import { FlattenMediaToTextFormField, LanguageFormField, @@ -26,7 +25,7 @@ import { import { CommonProps } from './interface'; import { DynamicPageRange } from './dynamic-page-range'; import { useSetInitialLanguage } from './use-set-initial-language'; -import { buildFieldNameWithPrefix, isForeignParseMethod } from './utils'; +import { buildFieldNameWithPrefix } from './utils'; const tableResultTypeOptions: SelectWithSearchFlagOptionType[] = [ { label: 'Markdown', value: '0' }, @@ -69,19 +68,6 @@ export function PdfFormFields({ prefix }: CommonProps) { useSetInitialLanguage({ prefix, languageShown }); - useEffect(() => { - const current = form.getValues(parseMethodName); - // On a file-type switch the field remounts and react-hook-form re-seeds it - // from the node's saved form data, so it can hold another file type's - // static parse method (e.g. ocr) — reset it to DeepDOC in that case too. - if (isEmpty(current) || isForeignParseMethod(FileType.PDF, current)) { - form.setValue(parseMethodName, ParseDocumentType.DeepDOC, { - shouldValidate: true, - shouldDirty: true, - }); - } - }, [form, parseMethodName]); - // Set default values for TCADP options when TCADP is selected useEffect(() => { if (tcadpOptionsShown) { diff --git a/web/src/pages/agent/form/parser-form/ppt-form-fields.tsx b/web/src/pages/agent/form/parser-form/ppt-form-fields.tsx index 22c35e8bbfe..2b8153ed2fb 100644 --- a/web/src/pages/agent/form/parser-form/ppt-form-fields.tsx +++ b/web/src/pages/agent/form/parser-form/ppt-form-fields.tsx @@ -8,10 +8,9 @@ import { isEmpty } from 'lodash'; import { useEffect, useMemo } from 'react'; import { useFormContext, useWatch } from 'react-hook-form'; import { useTranslation } from 'react-i18next'; -import { FileType } from '../../constant/pipeline'; import { ParserMethodFormField } from './common-form-fields'; import { CommonProps } from './interface'; -import { buildFieldNameWithPrefix, isForeignParseMethod } from './utils'; +import { buildFieldNameWithPrefix } from './utils'; const tableResultTypeOptions: SelectWithSearchFlagOptionType[] = [ { label: 'Markdown', value: '0' }, @@ -48,22 +47,6 @@ export function PptFormFields({ prefix }: CommonProps) { ); }, [parseMethod]); - useEffect(() => { - const current = form.getValues(parseMethodName); - // On a file-type switch the field remounts and react-hook-form re-seeds it - // from the node's saved form data, so it can hold another file type's - // static parse method (e.g. ocr) — reset it to DeepDOC in that case too. - if ( - isEmpty(current) || - isForeignParseMethod(FileType.PowerPoint, current) - ) { - form.setValue(parseMethodName, ParseDocumentType.DeepDOC, { - shouldValidate: true, - shouldDirty: true, - }); - } - }, [form, parseMethodName]); - // Set default values for TCADP options when TCADP is selected useEffect(() => { if (tcadpOptionsShown) { diff --git a/web/src/pages/agent/form/parser-form/schema.test.ts b/web/src/pages/agent/form/parser-form/schema.test.ts new file mode 100644 index 00000000000..6e5001283e1 --- /dev/null +++ b/web/src/pages/agent/form/parser-form/schema.test.ts @@ -0,0 +1,37 @@ +import { FileType, ParserFields } from '../../constant/pipeline'; +import { FormSchema } from './schema'; + +describe('parser FormSchema', () => { + it('accepts video and audio setups without a model', () => { + const result = FormSchema.safeParse({ + setups: [ + { fileFormat: FileType.Video, output_format: 'text' }, + { fileFormat: FileType.Audio, output_format: 'text' }, + ], + }); + expect(result.success).toBe(true); + }); + + it('requires at least one file type', () => { + const result = FormSchema.safeParse({ setups: [] }); + expect(result.success).toBe(false); + }); + + it('still requires fields for email', () => { + const result = FormSchema.safeParse({ + setups: [{ fileFormat: FileType.Email, output_format: 'text' }], + }); + expect(result.success).toBe(false); + + const withFields = FormSchema.safeParse({ + setups: [ + { + fileFormat: FileType.Email, + output_format: 'text', + fields: Object.values(ParserFields), + }, + ], + }); + expect(withFields.success).toBe(true); + }); +}); diff --git a/web/src/pages/agent/form/parser-form/schema.ts b/web/src/pages/agent/form/parser-form/schema.ts new file mode 100644 index 00000000000..8dc4163514a --- /dev/null +++ b/web/src/pages/agent/form/parser-form/schema.ts @@ -0,0 +1,59 @@ +import i18n from '@/locales/config'; +import { z } from 'zod'; +import { FileType } from '../../constant/pipeline'; + +export const SetupSchema = z + .object({ + fileFormat: z.string().nullish(), + // preprocess: z.array(z.string()).optional(), + output_format: z.string().optional(), + parse_method: z.string().optional(), + lang: z.string().optional(), + fields: z.array(z.string()).optional(), + vlm: z.object({ llm_id: z.string().optional() }).optional(), + flatten_media_to_text: z.boolean().optional(), + system_prompt: z.string().optional(), + table_result_type: z.string().optional(), + markdown_image_response_type: z.string().optional(), + enable_multi_column: z.boolean().optional(), + remove_toc: z.boolean().optional(), + remove_header_footer: z.boolean().optional(), + pages: z + .array( + z + .object({ + // Keep these checks on the fields themselves: an object-level + // `superRefine` is skipped whenever the base shape fails to + // parse, so one missing sibling would silently swallow the + // other field's error. + from: z.coerce + .number() + .int(i18n.t('knowledgeDetails.pageRangeFromInvalid')) + .min(1, i18n.t('knowledgeDetails.pageRangeFromInvalid')), + to: z.coerce + .number() + .int(i18n.t('knowledgeDetails.pageRangeToInvalid')) + .min(1, i18n.t('knowledgeDetails.pageRangeToInvalid')), + }) + .refine(({ from, to }) => to >= from, { + path: ['to'], + message: i18n.t('knowledgeDetails.pageRangeToInvalid'), + }), + ) + .optional(), + }) + .superRefine((values, ctx) => { + if (values.fileFormat === FileType.Email && !values.fields?.length) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['fields'], + message: 'Fields is required', + }); + } + }); + +export const FormSchema = z.object({ + setups: z.array(SetupSchema).min(1, i18n.t('flow.atLeastOneFileType')), +}); + +export type ParserFormSchemaType = z.infer; diff --git a/web/src/pages/agent/form/parser-form/spreadsheet-form-fields.tsx b/web/src/pages/agent/form/parser-form/spreadsheet-form-fields.tsx index 0e28ba2490e..934d5526e56 100644 --- a/web/src/pages/agent/form/parser-form/spreadsheet-form-fields.tsx +++ b/web/src/pages/agent/form/parser-form/spreadsheet-form-fields.tsx @@ -13,13 +13,12 @@ import { useEffect, useMemo } from 'react'; import { useFormContext, useWatch } from 'react-hook-form'; import { useTranslation } from 'react-i18next'; import { useOwnerTenantId } from '../../context'; -import { FileType } from '../../constant/pipeline'; import { FlattenMediaToTextFormField, ParserMethodFormField, } from './common-form-fields'; import { CommonProps } from './interface'; -import { buildFieldNameWithPrefix, isForeignParseMethod } from './utils'; +import { buildFieldNameWithPrefix } from './utils'; const tableResultTypeOptions: SelectWithSearchFlagOptionType[] = [ { label: 'Markdown', value: '0' }, @@ -60,22 +59,6 @@ export function SpreadsheetFormFields({ prefix }: CommonProps) { ); }, [parseMethod]); - useEffect(() => { - const current = form.getValues(parseMethodName); - // On a file-type switch the field remounts and react-hook-form re-seeds it - // from the node's saved form data, so it can hold another file type's - // static parse method (e.g. ocr) — reset it to DeepDOC in that case too. - if ( - isEmpty(current) || - isForeignParseMethod(FileType.Spreadsheet, current) - ) { - form.setValue(parseMethodName, ParseDocumentType.DeepDOC, { - shouldValidate: true, - shouldDirty: true, - }); - } - }, [form, parseMethodName]); - // Set default values for TCADP options when TCADP is selected useEffect(() => { if (tcadpOptionsShown) { diff --git a/web/src/pages/agent/form/parser-form/utils.test.ts b/web/src/pages/agent/form/parser-form/utils.test.ts index 8ee78f28aee..a2df564e93c 100644 --- a/web/src/pages/agent/form/parser-form/utils.test.ts +++ b/web/src/pages/agent/form/parser-form/utils.test.ts @@ -1,61 +1,105 @@ import { ParseDocumentType } from '@/components/layout-recognize-form-field'; -import { FileType, ImageParseMethod } from '../../constant/pipeline'; -import { getInitialParseMethod, isForeignParseMethod } from './utils'; +import { ModelTypeToField } from '@/constants/llm'; +import { + FileType, + ImageParseMethod, + initialParserValues, +} from '../../constant/pipeline'; +import { + buildInitialParserSetup, + buildInitialParserValues, + isStaticParseMethod, +} from './utils'; describe('parser-form utils', () => { - describe('getInitialParseMethod', () => { - it('returns ocr for image', () => { - expect(getInitialParseMethod(FileType.Image)).toBe(ImageParseMethod.OCR); + describe('isStaticParseMethod', () => { + it('recognizes the static parse methods', () => { + expect(isStaticParseMethod(ImageParseMethod.OCR)).toBe(true); + expect(isStaticParseMethod(ParseDocumentType.DeepDOC)).toBe(true); + expect(isStaticParseMethod(ParseDocumentType.PlainText)).toBe(true); + expect(isStaticParseMethod(ParseDocumentType.Docling)).toBe(true); + expect(isStaticParseMethod(ParseDocumentType.OpenDataLoader)).toBe(true); + expect(isStaticParseMethod(ParseDocumentType.TCADPParser)).toBe(true); }); - it('returns DeepDOC for pdf/spreadsheet/powerpoint', () => { - expect(getInitialParseMethod(FileType.PDF)).toBe( - ParseDocumentType.DeepDOC, - ); - expect(getInitialParseMethod(FileType.Spreadsheet)).toBe( - ParseDocumentType.DeepDOC, - ); - expect(getInitialParseMethod(FileType.PowerPoint)).toBe( - ParseDocumentType.DeepDOC, + it('treats LLM model ids and empty values as non-static', () => { + expect(isStaticParseMethod('gpt-4o@OpenAI')).toBe(false); + expect(isStaticParseMethod('')).toBe(false); + expect(isStaticParseMethod(undefined)).toBe(false); + expect(isStaticParseMethod(null)).toBe(false); + }); + }); + + describe('buildInitialParserSetup', () => { + it('returns a deep copy of the default setup', () => { + const setup = buildInitialParserSetup(FileType.PDF, {}); + expect(setup?.fileFormat).toBe(FileType.PDF); + // Mutating the copy must not touch the shared defaults + (setup as any).pages[0].from = 5; + expect(buildInitialParserSetup(FileType.PDF, {})?.pages?.[0].from).toBe( + 1, ); }); - it('returns empty string for file types without a parse method', () => { - expect(getInitialParseMethod(FileType.Email)).toBe(''); + it('prefills the tenant default model for video and audio', () => { + const dictionary = { + [ModelTypeToField.vision]: 'gpt-4o@OpenAI', + [ModelTypeToField.asr]: 'whisper@OpenAI', + }; + expect(buildInitialParserSetup(FileType.Video, dictionary)?.vlm).toEqual({ + llm_id: 'gpt-4o@OpenAI', + }); + expect(buildInitialParserSetup(FileType.Audio, dictionary)?.vlm).toEqual({ + llm_id: 'whisper@OpenAI', + }); }); - }); - describe('isForeignParseMethod', () => { - it('treats a static method from another file type as foreign', () => { - // The bug: switching pdf -> image left DeepDOC in parse_method - expect( - isForeignParseMethod(FileType.Image, ParseDocumentType.DeepDOC), - ).toBe(true); - expect(isForeignParseMethod(FileType.PDF, ImageParseMethod.OCR)).toBe( - true, + it('leaves other file types untouched even with defaults present', () => { + const dictionary = { + [ModelTypeToField.vision]: 'gpt-4o@OpenAI', + [ModelTypeToField.asr]: 'whisper@OpenAI', + }; + expect(buildInitialParserSetup(FileType.PDF, dictionary)?.vlm).toBe( + undefined, ); }); - it('accepts the file type’s own initial method', () => { - expect(isForeignParseMethod(FileType.Image, ImageParseMethod.OCR)).toBe( - false, - ); - expect( - isForeignParseMethod(FileType.PDF, ParseDocumentType.DeepDOC), - ).toBe(false); + it('keeps the empty model id when no tenant default exists', () => { + expect(buildInitialParserSetup(FileType.Audio, {})?.vlm).toEqual({ + llm_id: '', + }); + }); + + it('returns undefined for a file type without a default setup', () => { + expect(buildInitialParserSetup('nope' as FileType, {})).toBeUndefined(); }); + }); + + describe('buildInitialParserValues', () => { + it('prefills tenant default models across every default file type', () => { + const values = buildInitialParserValues({ + [ModelTypeToField.vision]: 'gpt-4o@OpenAI', + [ModelTypeToField.asr]: 'whisper@OpenAI', + }); - it('never treats an LLM model id as foreign', () => { - expect(isForeignParseMethod(FileType.PDF, 'gpt-4o@OpenAI')).toBe(false); - expect(isForeignParseMethod(FileType.Image, 'deepseek-v3@Moonshot')).toBe( - false, + const byFileType = new Map( + values.setups.map((setup: any) => [setup.fileFormat, setup]), ); + expect(byFileType.get(FileType.Video)?.vlm).toEqual({ + llm_id: 'gpt-4o@OpenAI', + }); + expect(byFileType.get(FileType.Audio)?.vlm).toEqual({ + llm_id: 'whisper@OpenAI', + }); + expect(byFileType.get(FileType.PDF)?.vlm).toBe(undefined); }); - it('ignores empty and non-string values', () => { - expect(isForeignParseMethod(FileType.Image, '')).toBe(false); - expect(isForeignParseMethod(FileType.Image, undefined)).toBe(false); - expect(isForeignParseMethod(FileType.Image, null)).toBe(false); + it('keeps every default file type and does not mutate the defaults', () => { + const values = buildInitialParserValues({}); + expect(values.setups).toHaveLength(initialParserValues.setups.length); + expect(initialParserValues.setups).toEqual( + buildInitialParserValues({}).setups, + ); }); }); }); diff --git a/web/src/pages/agent/form/parser-form/utils.ts b/web/src/pages/agent/form/parser-form/utils.ts index d840f757ddb..06b43117398 100644 --- a/web/src/pages/agent/form/parser-form/utils.ts +++ b/web/src/pages/agent/form/parser-form/utils.ts @@ -1,4 +1,5 @@ import { ParseDocumentType } from '@/components/layout-recognize-form-field'; +import { cloneDeep } from 'lodash'; import { FileType, FileTypeDefaultModelFieldMap, @@ -10,39 +11,9 @@ export function buildFieldNameWithPrefix(name: string, prefix: string) { return `${prefix}.${name}`; } -export function withDefaultParserModels( - formValues: Record, - defaultModelDictionary: Record, -) { - const setups = formValues?.setups; - if (!Array.isArray(setups)) { - return formValues; - } - - return { - ...formValues, - setups: setups.map((setup) => { - const field = FileTypeDefaultModelFieldMap[setup?.fileFormat as FileType]; - const modelId = field ? defaultModelDictionary[field] : ''; - if (!modelId || setup?.vlm?.llm_id) { - return setup; - } - return { ...setup, vlm: { ...setup?.vlm, llm_id: modelId } }; - }), - }; -} - -export function getInitialParseMethod(fileType: FileType): string { - const setup = initialParserValues.setups.find( - (x) => x.fileFormat === fileType, - ); - return setup?.parse_method ?? ''; -} - -// Static parse-method values across all file types. Forms saved while the -// file type was still switchable can hold another file type's static value on -// parse_method. LLM model ids from the model tree are never in this set, so a -// user-picked model is never treated as foreign. +// Static parse-method values across all file types. LLM model ids from the +// model tree are never in this set, so `isStaticParseMethod` can tell a +// built-in method apart from a user-picked model. // Note: ParseDocumentType is a const enum — list members explicitly instead of // Object.values, which is not allowed on const enums (TS2475). const KnownStaticParseMethods = new Set([ @@ -54,13 +25,46 @@ const KnownStaticParseMethods = new Set([ ImageParseMethod.OCR, ]); -export function isForeignParseMethod( +export function isStaticParseMethod(value: unknown): value is string { + return typeof value === 'string' && KnownStaticParseMethods.has(value); +} + +// Builds the default setup for a file type being added to the parser form, +// prefilling the tenant default model for types that have one (video/audio). +export function buildInitialParserSetup( fileType: FileType, - value: unknown, -): value is string { - return ( - typeof value === 'string' && - KnownStaticParseMethods.has(value) && - value !== getInitialParseMethod(fileType) + defaultModelDictionary: Record, +) { + const setup = initialParserValues.setups.find( + (x) => x.fileFormat === fileType, ); + if (!setup) { + return undefined; + } + + const nextSetup = cloneDeep(setup) as Record; + const field = FileTypeDefaultModelFieldMap[fileType]; + const modelId = field ? defaultModelDictionary[field] : ''; + if (modelId) { + nextSetup.vlm = { ...nextSetup.vlm, llm_id: modelId }; + } + return nextSetup; +} + +// Form values for a freshly added Parser node: every default file type with its +// tenant default model prefilled. Only applies to node creation — an existing +// form is shown as saved, so a cleared model stays cleared. +export function buildInitialParserValues( + defaultModelDictionary: Record, +) { + return { + ...initialParserValues, + setups: initialParserValues.setups.map( + (setup) => + buildInitialParserSetup( + setup.fileFormat as FileType, + defaultModelDictionary, + ) ?? setup, + ), + }; } diff --git a/web/src/pages/agent/form/parser-form/video-form-fields.tsx b/web/src/pages/agent/form/parser-form/video-form-fields.tsx index bd45e117296..ee536c45bea 100644 --- a/web/src/pages/agent/form/parser-form/video-form-fields.tsx +++ b/web/src/pages/agent/form/parser-form/video-form-fields.tsx @@ -20,7 +20,6 @@ export function AudioFormFields({ prefix }: OutputFormatFormFieldProps) { modelTypes={ModelTypeMap.asr_id} allowClear ownerTenantId={ownerTenantId} - required /> ); @@ -39,7 +38,6 @@ export function VideoFormFields({ prefix }: OutputFormatFormFieldProps) { modelTypes={ModelTypeMap.img2txt_id} allowClear ownerTenantId={ownerTenantId} - required /> ); diff --git a/web/src/pages/agent/hooks/use-add-node.ts b/web/src/pages/agent/hooks/use-add-node.ts index d76f1408a88..e79a2043e4d 100644 --- a/web/src/pages/agent/hooks/use-add-node.ts +++ b/web/src/pages/agent/hooks/use-add-node.ts @@ -38,7 +38,6 @@ import { initialLoopValues, initialMessageValues, initialNoteValues, - initialParserValues, initialPubMedValues, initialBGPTValues, initialQueritContentsValues, @@ -61,7 +60,7 @@ import { initialWikipediaValues, initialYahooFinanceValues, } from '../constant'; -import { withDefaultParserModels } from '../form/parser-form/utils'; +import { buildInitialParserValues } from '../form/parser-form/utils'; import useGraphStore from '../store'; import { generateNodeNamesWithIncreasingIndex, @@ -183,10 +182,7 @@ export const useInitializeOperatorParams = () => { [Operator.TavilyExtract]: initialTavilyExtractValues, [Operator.Placeholder]: {}, [Operator.File]: {}, - [Operator.Parser]: withDefaultParserModels( - initialParserValues, - defaultModelDictionary, - ), + [Operator.Parser]: buildInitialParserValues(defaultModelDictionary), [Operator.Tokenizer]: initialTokenizerValues, [Operator.TokenChunker]: initialTokenChunkerValues, [Operator.TitleChunker]: initialTitleChunkerValues, diff --git a/web/src/pages/dataset/dataset/index.tsx b/web/src/pages/dataset/dataset/index.tsx index ad85962e398..05ec190fc85 100644 --- a/web/src/pages/dataset/dataset/index.tsx +++ b/web/src/pages/dataset/dataset/index.tsx @@ -260,10 +260,6 @@ export default function Dataset() { )} {reparseDialogVisible && (
+ ); +} diff --git a/web/src/pages/dataset/dataset/parsing-status-cell.test.tsx b/web/src/pages/dataset/dataset/parsing-status-cell.test.tsx index c9285811cb8..f3ab0182b6f 100644 --- a/web/src/pages/dataset/dataset/parsing-status-cell.test.tsx +++ b/web/src/pages/dataset/dataset/parsing-status-cell.test.tsx @@ -1,5 +1,5 @@ -import { render, screen } from '@testing-library/react'; -import React from 'react'; +import { fireEvent, render, screen } from '@testing-library/react'; +import React, { StrictMode } from 'react'; jest.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }), @@ -9,11 +9,14 @@ jest.mock('./reparse-dialog', () => ({ ReparseDialog: () => null, })); +const mockRunDocumentByIds = jest.fn(); +const mockShowReparseDialog = jest.fn(); + jest.mock('./use-run-document', () => ({ useHandleRunDocumentByIds: () => ({ - handleRunDocumentByIds: jest.fn(), + handleRunDocumentByIds: mockRunDocumentByIds, visible: false, - showModal: jest.fn(), + showModal: mockShowReparseDialog, hideModal: jest.fn(), }), })); @@ -21,43 +24,57 @@ jest.mock('./use-run-document', () => ({ import { IngestionTaskStatus, RunningStatus } from './constant'; import { ParsingStatusCell } from './parsing-status-cell'; +const baseRecord = { + id: 'doc-1', + dataset_id: 'dataset-1', + name: 'doc.pdf', + type: 'document', + run: RunningStatus.UNSTART, + ingestion_status: IngestionTaskStatus.RUNNING, + progress: 0, + chunk_count: 0, + parser_config: {}, + create_date: '', + create_time: 0, + created_by: 'user-1', + nickname: '', + location: '', + pipeline_id: '', + pipeline_name: '', + process_duration: 0, + progress_msg: '', + size: 0, + source_type: 'local', + status: '1', + suffix: 'pdf', + thumbnail: '', + token_num: 0, + update_date: '', + update_time: 0, + chunk_method: 'naive', +}; + +function renderCell(overrides: Record) { + return render( + React.createElement(ParsingStatusCell, { + record: { ...baseRecord, ...overrides } as any, + showLog: jest.fn(), + showChangeParserModal: jest.fn(), + }), + { wrapper: StrictMode }, + ); +} + describe('ParsingStatusCell', () => { + beforeEach(() => { + mockRunDocumentByIds.mockClear(); + mockShowReparseDialog.mockClear(); + }); + it('shows a cancel icon while ingestion runs before the document run state updates', () => { - const { container } = render( - React.createElement(ParsingStatusCell, { - record: { - id: 'doc-1', - dataset_id: 'dataset-1', - name: 'doc.pdf', - type: 'document', - run: RunningStatus.UNSTART, - ingestion_status: IngestionTaskStatus.RUNNING, - progress: 0, - chunk_count: 0, - parser_config: {}, - create_date: '', - create_time: 0, - created_by: 'user-1', - nickname: '', - location: '', - pipeline_id: '', - pipeline_name: '', - process_duration: 0, - progress_msg: '', - size: 0, - source_type: 'local', - status: '1', - suffix: 'pdf', - thumbnail: '', - token_num: 0, - update_date: '', - update_time: 0, - chunk_method: 'naive', - }, - showLog: jest.fn(), - showChangeParserModal: jest.fn(), - }), - ); + const { container } = renderCell({ + ingestion_status: IngestionTaskStatus.RUNNING, + }); expect(container.querySelector('svg.lucide-circle-x')).toBeInTheDocument(); expect( @@ -66,41 +83,10 @@ describe('ParsingStatusCell', () => { }); it('does not expose cancelling as a document status', () => { - const { container } = render( - React.createElement(ParsingStatusCell, { - record: { - id: 'doc-1', - dataset_id: 'dataset-1', - name: 'doc.pdf', - type: 'document', - run: RunningStatus.RUNNING, - ingestion_status: IngestionTaskStatus.STOPPING, - progress: 0, - chunk_count: 0, - parser_config: {}, - create_date: '', - create_time: 0, - created_by: 'user-1', - nickname: '', - location: '', - pipeline_id: '', - pipeline_name: '', - process_duration: 0, - progress_msg: '', - size: 0, - source_type: 'local', - status: '1', - suffix: 'pdf', - thumbnail: '', - token_num: 0, - update_date: '', - update_time: 0, - chunk_method: 'naive', - }, - showLog: jest.fn(), - showChangeParserModal: jest.fn(), - }), - ); + const { container } = renderCell({ + run: RunningStatus.RUNNING, + ingestion_status: IngestionTaskStatus.STOPPING, + }); expect( screen.queryByText('knowledgeDetails.runningStatusStopping'), @@ -108,4 +94,38 @@ describe('ParsingStatusCell', () => { expect(container.querySelector('svg.lucide-circle-x')).toBeInTheDocument(); expect(container.querySelector('button[disabled]')).toBeInTheDocument(); }); + + it('runs a chunkless document once without opening the confirmation', () => { + renderCell({ ingestion_status: IngestionTaskStatus.COMPLETED }); + + fireEvent.click(screen.getByTestId('document-parse-toggle')); + + expect(mockRunDocumentByIds).toHaveBeenCalledTimes(1); + expect(mockShowReparseDialog).not.toHaveBeenCalled(); + }); + + it('opens the confirmation when existing chunks would be dropped', () => { + renderCell({ + run: RunningStatus.DONE, + ingestion_status: IngestionTaskStatus.COMPLETED, + chunk_count: 3, + }); + + fireEvent.click(screen.getByTestId('document-parse-toggle')); + + expect(mockShowReparseDialog).toHaveBeenCalledTimes(1); + expect(mockRunDocumentByIds).not.toHaveBeenCalled(); + }); + + it('opens the confirmation for a chunkless document when auto-metadata applies', () => { + renderCell({ + ingestion_status: IngestionTaskStatus.COMPLETED, + parser_config: { enable_metadata: true }, + }); + + fireEvent.click(screen.getByTestId('document-parse-toggle')); + + expect(mockShowReparseDialog).toHaveBeenCalledTimes(1); + expect(mockRunDocumentByIds).not.toHaveBeenCalled(); + }); }); diff --git a/web/src/pages/dataset/dataset/parsing-status-cell.tsx b/web/src/pages/dataset/dataset/parsing-status-cell.tsx index d3acbf0eda8..e1efa923142 100644 --- a/web/src/pages/dataset/dataset/parsing-status-cell.tsx +++ b/web/src/pages/dataset/dataset/parsing-status-cell.tsx @@ -130,7 +130,22 @@ export function ParsingStatusCell({ delete: boolean; apply_kb: boolean; }) => { - handleRunDocumentByIds(record.id, isRunning, option); + handleRunDocumentByIds(record, isRunning, option); + }; + + // The confirmation only offers real choices when there are existing chunks to + // drop or auto-metadata to re-apply. Otherwise, and always when cancelling a + // run, the action fires straight away. + const needsParseConfirm = + !isRunning && + (!isZeroChunk || Boolean(record?.parser_config?.enable_metadata)); + + const handleParseClick = () => { + if (needsParseConfirm) { + showReparseDialogModal(); + return; + } + handleOperationIconClick(); }; const showParse = useMemo(() => { @@ -181,7 +196,8 @@ export function ParsingStatusCell({ variant="ghost" size="icon-xs" disabled={isStopping} - onClick={() => showReparseDialogModal()} + onClick={handleParseClick} + data-testid="document-parse-toggle" > { - showReparseDialogModal(); - }} + onClick={handleParseClick} + data-testid="document-parse-toggle" > {operationIcon} @@ -208,10 +223,6 @@ export function ParsingStatusCell({ )} {reparseDialogVisible && (
- ), - secondTitle: ( -
- -
{row.original.name}
-
- ), - isDeleteSingleValue: true, - documentIds: [row.original.id], - }); - }} - > - {length + ' fields'} - - ); + ), + secondTitle: ( +
+ +
{row.original.name}
+
+ ), + isDeleteSingleValue: true, + documentIds: [row.original.id], + }); + }} + > + {length + ' fields'} + + ); + }, }, - }, - { - accessorKey: 'run', - header: t('Parse'), - cell: ({ row }) => { - return ( - - ); + { + accessorKey: 'run', + header: t('Parse'), + cell: ({ row }) => { + return ( + + ); + }, }, - }, - { - id: 'run-status', - header: '', - cell: ({ row }) => { - return ( - - ); + { + id: 'run-status', + header: '', + cell: ({ row }) => { + return ( + + ); + }, }, - }, - { - id: 'actions', - header: t('action'), - enableHiding: false, - cell: ({ row }) => { - const record = row.original; + { + id: 'actions', + header: t('action'), + enableHiding: false, + cell: ({ row }) => { + const record = row.original; - return ( - - ); + return ( + + ); + }, }, - }, - ]; + ], + [ + t, + navigateToChunkParsedResult, + setDocumentStatus, + datasetId, + showChangeParserModal, + showRenameModal, + showManageMetadataModal, + showLog, + setRowSelection, + ], + ); return columns; } diff --git a/web/src/pages/dataset/dataset/use-parser-model-validation.ts b/web/src/pages/dataset/dataset/use-parser-model-validation.ts new file mode 100644 index 00000000000..d06613ea218 --- /dev/null +++ b/web/src/pages/dataset/dataset/use-parser-model-validation.ts @@ -0,0 +1,46 @@ +import { useNavigatePage } from '@/hooks/logic-hooks/navigate-hooks'; +import { useIsGoBackend } from '@/utils/backend-variant'; +import { useCallback } from 'react'; +import { useParams } from 'react-router'; +import { useKnowledgeBaseContext } from '../contexts/knowledge-base-context'; +import { + FileModelGap, + findFilesMissingParserModels, + getEffectiveParserSetups, +} from './utils'; + +/** + * Validates that the models required to parse a file type (audio/video/image) + * are configured on the dataset's Parser operator. + * Only the Go backend has parser operator settings — on the Python backend + * every file passes. + */ +export function useParserModelValidation() { + const isGoBackend = useIsGoBackend(); + const { knowledgeBase, loading } = useKnowledgeBaseContext(); + const { id } = useParams(); + const { navigateToDatasetSetting } = useNavigatePage(); + + const findFilesMissingModels = useCallback( + (names: string[]): FileModelGap[] => { + // Skip while the dataset is loading: its parser_config is not readable + // yet and every media file would look unconfigured. + if (!isGoBackend || loading) { + return []; + } + return findFilesMissingParserModels( + names, + getEffectiveParserSetups(knowledgeBase), + ); + }, + [isGoBackend, loading, knowledgeBase], + ); + + const goToDatasetConfiguration = useCallback(() => { + if (id) { + navigateToDatasetSetting(id); + } + }, [id, navigateToDatasetSetting]); + + return { findFilesMissingModels, goToDatasetConfiguration }; +} diff --git a/web/src/pages/dataset/dataset/use-run-document.ts b/web/src/pages/dataset/dataset/use-run-document.ts index 8494f785657..cd48016eb87 100644 --- a/web/src/pages/dataset/dataset/use-run-document.ts +++ b/web/src/pages/dataset/dataset/use-run-document.ts @@ -1,24 +1,54 @@ +import { Modal } from '@/components/ui/modal/modal'; import { useSetModalState } from '@/hooks/common-hooks'; import { useRunDocument } from '@/hooks/use-document-request'; +import { IDocumentInfo } from '@/interfaces/database/document'; import { useState } from 'react'; +import { useTranslation } from 'react-i18next'; +import { buildMissingModelModalContent } from './parser-model-gap-content'; +import { useParserModelValidation } from './use-parser-model-validation'; export const useHandleRunDocumentByIds = (id: string) => { + const { t } = useTranslation(); const { runDocumentByIds, loading } = useRunDocument(); const [currentId, setCurrentId] = useState(''); const isLoading = loading && currentId !== '' && currentId === id; const { visible, showModal, hideModal } = useSetModalState(); + const { findFilesMissingModels, goToDatasetConfiguration } = + useParserModelValidation(); + const handleRunDocumentByIds = async ( - documentId: string, + record: IDocumentInfo, isRunning: boolean, option?: { delete: boolean; apply_kb: boolean }, ) => { if (isLoading) { return; } - setCurrentId(documentId); + // Starting a parse requires the models of the file type to be configured; + // cancelling is always allowed. + if (!isRunning) { + const gaps = findFilesMissingModels([record.name]); + if (gaps.length > 0) { + hideModal(); + Modal.error({ + title: t('knowledgeDetails.parseBlockedTitle'), + content: buildMissingModelModalContent( + t, + gaps, + 'knowledgeDetails.parseBlockedHint', + ), + okText: t('knowledgeDetails.goToConfiguration'), + cancelText: t('common.cancel'), + closable: false, + onOk: goToDatasetConfiguration, + }); + return; + } + } + setCurrentId(record.id); try { await runDocumentByIds({ - documentIds: [documentId], + documentIds: [record.id], run: isRunning ? 2 : 1, option, }); diff --git a/web/src/pages/dataset/dataset/use-upload-document.ts b/web/src/pages/dataset/dataset/use-upload-document.ts index 5b41cd7900a..81b7ef3c92a 100644 --- a/web/src/pages/dataset/dataset/use-upload-document.ts +++ b/web/src/pages/dataset/dataset/use-upload-document.ts @@ -1,13 +1,21 @@ import { UploadFormSchemaType } from '@/components/file-upload-dialog'; +import { Modal } from '@/components/ui/modal/modal'; import { useSetModalState } from '@/hooks/common-hooks'; import { useRunDocument, useUploadDocument, } from '@/hooks/use-document-request'; -import { getUnSupportedFilesCount } from '@/utils/document-util'; +import { IDocumentInfo } from '@/interfaces/database/document'; +import { FileType } from '@/pages/agent/constant/pipeline'; +import { getExtension, getUnSupportedFilesCount } from '@/utils/document-util'; import { useCallback } from 'react'; +import { useTranslation } from 'react-i18next'; +import { buildMissingModelModalContent } from './parser-model-gap-content'; +import { useParserModelValidation } from './use-parser-model-validation'; +import { getFileTypeByExtension } from './utils'; export const useHandleUploadDocument = () => { + const { t } = useTranslation(); const { visible: documentUploadVisible, hideModal: hideDocumentUploadModal, @@ -15,68 +23,126 @@ export const useHandleUploadDocument = () => { } = useSetModalState(); const { uploadDocument, loading } = useUploadDocument(); const { runDocumentByIds } = useRunDocument(); + const { findFilesMissingModels, goToDatasetConfiguration } = + useParserModelValidation(); - const onDocumentUploadOk = useCallback( - async ({ - fileList, - parseOnCreation, - tableColumnMode, - tableColumnRoles, - }: UploadFormSchemaType) => { - if (fileList.length > 0) { - // Build parser_config if column roles are configured - let parserConfig: Record | undefined; - if ( - tableColumnMode === 'manual' && - tableColumnRoles && - Object.keys(tableColumnRoles).length > 0 - ) { - parserConfig = { - table_column_mode: 'manual', - table_column_roles: tableColumnRoles, - }; - } + const proceedUpload = useCallback( + async ( + { + fileList, + parseOnCreation, + tableColumnMode, + tableColumnRoles, + }: UploadFormSchemaType, + failingFileTypes: Set, + ) => { + // Build parser_config if column roles are configured + let parserConfig: Record | undefined; + if ( + tableColumnMode === 'manual' && + tableColumnRoles && + Object.keys(tableColumnRoles).length > 0 + ) { + parserConfig = { + table_column_mode: 'manual', + table_column_roles: tableColumnRoles, + }; + } - const ret = await uploadDocument(fileList as File[], parserConfig); + const ret = await uploadDocument(fileList as File[], parserConfig); - // Check for success (code === 0) or partial success (code === 500 with some files) - const isSuccess = ret?.code === 0; - const isPartialSuccess = ret?.code === 500 && ret?.message; + // Check for success (code === 0) or partial success (code === 500 with some files) + const isSuccess = ret?.code === 0; + const isPartialSuccess = ret?.code === 500 && ret?.message; - if (!isSuccess && !isPartialSuccess) { - return; - } + if (!isSuccess && !isPartialSuccess) { + return; + } - // Trigger parsing for both full and partial success when parseOnCreation is enabled - if ( - (isSuccess || isPartialSuccess) && - parseOnCreation && - ret.data?.length > 0 - ) { + // Trigger parsing for both full and partial success when parseOnCreation + // is enabled; files whose required model is missing are uploaded but not + // auto-parsed. + if ( + (isSuccess || isPartialSuccess) && + parseOnCreation && + ret.data?.length > 0 + ) { + const runnableDocuments = (ret.data as IDocumentInfo[]).filter( + (doc) => { + const fileType = getFileTypeByExtension(getExtension(doc.name)); + return !fileType || !failingFileTypes.has(fileType); + }, + ); + if (runnableDocuments.length > 0) { runDocumentByIds({ - documentIds: ret.data.map((x: any) => x.id), + documentIds: runnableDocuments.map((x) => x.id), run: 1, }); } + } - if (isSuccess) { - hideDocumentUploadModal(); - return 0; - } - - // For partial success (code 500), check if any files were uploaded - const count = getUnSupportedFilesCount(ret?.message); - if (count !== fileList.length) { - hideDocumentUploadModal(); - return 0; - } + if (isSuccess) { + hideDocumentUploadModal(); + return 0; + } - return ret?.code; + // For partial success (code 500), check if any files were uploaded + const count = getUnSupportedFilesCount(ret?.message); + if (count !== fileList.length) { + hideDocumentUploadModal(); + return 0; } + + return ret?.code; }, [uploadDocument, runDocumentByIds, hideDocumentUploadModal], ); + const onDocumentUploadOk = useCallback( + async (values: UploadFormSchemaType) => { + const { fileList } = values; + if (fileList.length === 0) { + return; + } + + const names = fileList.map((file) => + file instanceof File ? file.name : file.file.name, + ); + const gaps = findFilesMissingModels(names); + if (gaps.length > 0) { + const failingFileTypes = new Set(gaps.map((gap) => gap.fileType)); + Modal.warning({ + title: t('knowledgeDetails.uploadMissingModelsTitle'), + content: buildMissingModelModalContent( + t, + gaps, + 'knowledgeDetails.configureInDatasetSettingHint', + ), + okText: t('knowledgeDetails.continueUpload'), + cancelText: t('knowledgeDetails.goToConfiguration'), + closable: false, + onOk: () => { + proceedUpload(values, failingFileTypes); + }, + onCancel: () => { + hideDocumentUploadModal(); + goToDatasetConfiguration(); + }, + }); + return; + } + + return proceedUpload(values, new Set()); + }, + [ + findFilesMissingModels, + goToDatasetConfiguration, + hideDocumentUploadModal, + proceedUpload, + t, + ], + ); + return { documentUploadLoading: loading, onDocumentUploadOk, diff --git a/web/src/pages/dataset/dataset/utils.test.ts b/web/src/pages/dataset/dataset/utils.test.ts index b1910a1321b..5ba5866c1c7 100644 --- a/web/src/pages/dataset/dataset/utils.test.ts +++ b/web/src/pages/dataset/dataset/utils.test.ts @@ -1,5 +1,13 @@ +import { IDataset } from '@/interfaces/database/dataset'; +import { FileType, initialParserValues } from '@/pages/agent/constant/pipeline'; import { IngestionTaskStatus, RunningStatus } from './constant'; -import { isDocumentProcessing } from './utils'; +import { + findFilesMissingParserModels, + findMissingParserModel, + getEffectiveParserSetups, + getFileTypeByExtension, + isDocumentProcessing, +} from './utils'; describe('isDocumentProcessing', () => { it('treats a scheduled ingestion task as processing before parsing starts', () => { @@ -27,3 +35,119 @@ describe('isDocumentProcessing', () => { }, ); }); + +describe('getFileTypeByExtension', () => { + it('maps media extensions to their file types', () => { + expect(getFileTypeByExtension('mp3')).toBe(FileType.Audio); + expect(getFileTypeByExtension('wav')).toBe(FileType.Audio); + expect(getFileTypeByExtension('mp4')).toBe(FileType.Video); + expect(getFileTypeByExtension('jpeg')).toBe(FileType.Image); + expect(getFileTypeByExtension('PNG')).toBe(FileType.Image); + expect(getFileTypeByExtension('pdf')).toBe(FileType.PDF); + }); + + it('returns undefined for unknown extensions', () => { + expect(getFileTypeByExtension('xyz')).toBeUndefined(); + expect(getFileTypeByExtension('')).toBeUndefined(); + }); +}); + +const DefaultSetups = initialParserValues.setups as Record[]; + +describe('findMissingParserModel', () => { + it('passes audio when the setup carries a model', () => { + const setups = [ + { fileFormat: FileType.Audio, vlm: { llm_id: 'whisper@OpenAI' } }, + ]; + expect(findMissingParserModel(FileType.Audio, setups)).toBeNull(); + }); + + it('flags audio when the setup has no model, ignoring the tenant default', () => { + expect(findMissingParserModel(FileType.Audio, DefaultSetups)).toEqual({ + fileType: FileType.Audio, + modelKind: 'asr', + }); + }); + + it('passes video when the setup carries a model', () => { + const setups = [ + { fileFormat: FileType.Video, vlm: { llm_id: 'gpt-4o@OpenAI' } }, + ]; + expect(findMissingParserModel(FileType.Video, setups)).toBeNull(); + }); + + it('flags video when the setup has no model', () => { + expect(findMissingParserModel(FileType.Video, DefaultSetups)).toEqual({ + fileType: FileType.Video, + modelKind: 'vision', + }); + }); + + it('flags image when parse_method is a static method like ocr', () => { + // The default image setup uses ocr — no vision model configured + expect(findMissingParserModel(FileType.Image, DefaultSetups)).toEqual({ + fileType: FileType.Image, + modelKind: 'vision', + }); + }); + + it('passes image when parse_method is a vision model', () => { + const setups = [ + { fileFormat: FileType.Image, parse_method: 'gpt-4o@OpenAI' }, + ]; + expect(findMissingParserModel(FileType.Image, setups)).toBeNull(); + }); + + it('ignores file types without model requirements', () => { + expect(findMissingParserModel(FileType.PDF, DefaultSetups)).toBeNull(); + expect(findMissingParserModel(undefined, DefaultSetups)).toBeNull(); + }); +}); + +describe('findFilesMissingParserModels', () => { + it('returns a gap per file that lacks its required model', () => { + const gaps = findFilesMissingParserModels( + ['song.mp3', 'notes.txt', 'photo.jpg'], + DefaultSetups, + ); + expect(gaps).toEqual([ + { name: 'song.mp3', fileType: FileType.Audio, modelKind: 'asr' }, + { name: 'photo.jpg', fileType: FileType.Image, modelKind: 'vision' }, + ]); + }); +}); + +describe('getEffectiveParserSetups', () => { + it('falls back to the default setups without a saved parser config', () => { + const setups = getEffectiveParserSetups(null); + expect(setups.map((x) => x.fileFormat)).toEqual( + initialParserValues.setups.map((x) => x.fileFormat), + ); + }); + + it('applies saved overrides keyed by file format', () => { + const knowledgeBase = { + parser_config: { + 'Parser:1': { + audio: { vlm: { llm_id: 'whisper@OpenAI' } }, + }, + }, + } as unknown as IDataset; + const setups = getEffectiveParserSetups(knowledgeBase); + const audio = setups.find((x) => x.fileFormat === FileType.Audio); + expect(audio?.vlm?.llm_id).toBe('whisper@OpenAI'); + // Untouched types keep their defaults + const image = setups.find((x) => x.fileFormat === FileType.Image); + expect(image?.parse_method).toBe('ocr'); + }); + + it('ignores non-parser operator entries', () => { + const knowledgeBase = { + parser_config: { + 'TokenChunker:1': { chunk_token_size: 128 }, + }, + } as unknown as IDataset; + const setups = getEffectiveParserSetups(knowledgeBase); + expect(setups).toHaveLength(initialParserValues.setups.length); + }); +}); diff --git a/web/src/pages/dataset/dataset/utils.ts b/web/src/pages/dataset/dataset/utils.ts index e899d88ab9a..5779f83abc9 100644 --- a/web/src/pages/dataset/dataset/utils.ts +++ b/web/src/pages/dataset/dataset/utils.ts @@ -1,5 +1,19 @@ -import { IngestionTaskStatus, RunningStatus } from './constant'; +import { Operator } from '@/constants/agent'; +import type { IDataset } from '@/interfaces/database/dataset'; import type { IDocumentInfo } from '@/interfaces/database/document'; +import { + FileType, + FileTypeSuffixMap, + initialParserValues, +} from '@/pages/agent/constant/pipeline'; +import { isStaticParseMethod } from '@/pages/agent/form/parser-form/utils'; +import { getExtension } from '@/utils/document-util'; +import { + getOperatorType, + transformParserConfigSetups, +} from '@/utils/pipeline-operator'; +import { cloneDeep } from 'lodash'; +import { IngestionTaskStatus, RunningStatus } from './constant'; export const isParserRunning = (text: RunningStatus) => { const isRunning = text === RunningStatus.RUNNING; @@ -35,3 +49,105 @@ export const isDocumentProcessing = ( document.ingestion_status === IngestionTaskStatus.STOPPING ); }; + +// --- Parser model prerequisite checks ------------------------------------- +// Audio/video/image files can only be parsed when the matching model is +// configured on the dataset's Parser operator. The tenant default is +// deliberately not consulted: parsing reads the operator setup, so a global +// default does not make the file parsable. +// These helpers power the upload warning and the parse-click validation. + +export type ParserModelGap = { + fileType: FileType; + modelKind: 'asr' | 'vision'; +}; + +export type FileModelGap = ParserModelGap & { name: string }; + +type ParserSetup = Record & { fileFormat?: string }; + +const ExtensionToFileTypeMap: Record = Object.entries( + FileTypeSuffixMap, +).reduce>((acc, [fileType, suffixes]) => { + for (const suffix of suffixes) { + acc[suffix] = fileType as FileType; + } + return acc; +}, {}); + +export function getFileTypeByExtension( + extension: string, +): FileType | undefined { + return ExtensionToFileTypeMap[extension.toLowerCase()]; +} + +/** + * Effective parser setups for a dataset: the saved Parser operator entry + * (stored as a flattened map keyed by file format) merged over the default + * setups, so untouched file types validate against their defaults. + */ +export function getEffectiveParserSetups( + knowledgeBase: Pick | null | undefined, +): ParserSetup[] { + const parserConfig = knowledgeBase?.parser_config as + | Record + | undefined; + + const parserEntry = Object.entries(parserConfig ?? {}).find( + ([operatorId]) => getOperatorType(operatorId) === Operator.Parser, + )?.[1]; + + const savedSetups = transformParserConfigSetups(parserEntry); + const savedByFileType = new Map( + savedSetups.map((setup) => [setup.fileFormat, setup]), + ); + + const defaultSetups = cloneDeep(initialParserValues.setups) as ParserSetup[]; + const merged = defaultSetups.map( + (setup) => savedByFileType.get(setup.fileFormat) ?? setup, + ); + for (const setup of savedSetups) { + if (!defaultSetups.some((x) => x.fileFormat === setup.fileFormat)) { + merged.push(setup); + } + } + return merged; +} + +export function findMissingParserModel( + fileType: FileType | undefined, + setups: ParserSetup[], +): ParserModelGap | null { + const setup = setups.find((x) => x.fileFormat === fileType); + + switch (fileType) { + case FileType.Audio: { + const configured = setup?.vlm?.llm_id; + return configured ? null : { fileType, modelKind: 'asr' }; + } + case FileType.Video: { + const configured = setup?.vlm?.llm_id; + return configured ? null : { fileType, modelKind: 'vision' }; + } + case FileType.Image: { + // The image parser's vision model is picked as parse_method; a static + // method (e.g. ocr) means no vision model is configured. + const configured = + !!setup?.parse_method && !isStaticParseMethod(setup.parse_method); + return configured ? null : { fileType, modelKind: 'vision' }; + } + default: + return null; + } +} + +export function findFilesMissingParserModels( + names: string[], + setups: ParserSetup[], +): FileModelGap[] { + return names.flatMap((name) => { + const fileType = getFileTypeByExtension(getExtension(name)); + const gap = findMissingParserModel(fileType, setups); + return gap ? [{ ...gap, name }] : []; + }); +} diff --git a/web/src/pages/dataset/setting/go/index.tsx b/web/src/pages/dataset/setting/go/index.tsx index 1ff0eb5c82d..6154beea98d 100644 --- a/web/src/pages/dataset/setting/go/index.tsx +++ b/web/src/pages/dataset/setting/go/index.tsx @@ -243,6 +243,7 @@ export default function DatasetSetting() { | Record | undefined } + fixedFileFormats /> )} From 56966c0df0450e738b5a519004cbe5df7e5f3c5e Mon Sep 17 00:00:00 2001 From: huyua9 Date: Fri, 11 Sep 2026 15:26:09 +0800 Subject: [PATCH 107/568] fix(template): align data analysis CodeExec prompt (#18958) --- .../data_analysis_beginner_assistant.json | 4 +-- .../test_data_analysis_beginner_template.py | 26 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) create mode 100644 test/unit_test/agent/test_data_analysis_beginner_template.py diff --git a/agent/templates/data_analysis_beginner_assistant.json b/agent/templates/data_analysis_beginner_assistant.json index 000abee0cad..64d958dbb8d 100644 --- a/agent/templates/data_analysis_beginner_assistant.json +++ b/agent/templates/data_analysis_beginner_assistant.json @@ -51,7 +51,7 @@ } ], "showStructuredOutput": false, - "sys_prompt": "\n You are an expert Data Analyst AI assistant, specialized in extracting insights from structured and unstructured data.\n Your core competencies include statistical analysis, data cleaning, exploratory data analysis (EDA), hypothesis testing, \n predictive modeling, and data visualization. You translate raw data into actionable business intelligence with rigorous \n methodological transparency.\n\n\n\n 1. **Understand**: Clarify the analytical objectives, data sources, and success metrics with the user.\n 2. **Data Assessment**: Evaluate data quality (completeness, consistency, outliers) and perform necessary cleaning/validation.\n 3. **Exploratory Analysis**: Decompose the dataset into logical segments; calculate descriptive statistics and identify patterns, correlations, or anomalies.\n 4. **Analytical Execution**: \n - Use `CodeExec` (Python) for all computational tasks—never rely on mental arithmetic for complex calculations.\n - Apply appropriate statistical methods (regression, clustering, time-series analysis, etc.) based on data type and business question.\n 5. **Visualization**: Generate clear, publication-ready charts and graphs using the coding environment to illustrate findings visually.\n 6. **Validation**: Verify statistical significance, check for biases, validate assumptions, and ensure reproducibility of results.\n 7. **Synthesis**: Summarize insights in business-friendly language, highlight limitations of the analysis, and provide data-driven recommendations.\n\n\n\n - Always execute data processing and calculations via code; never guess or approximate numerical results.\n - All visualizations must be generated programmaticallyand returned as renderable outputs.\n - Cite data sources and methodologies; flag any data quality issues that may affect interpretation.\n", + "sys_prompt": "\n You are an expert Data Analyst AI assistant, specialized in extracting insights from structured and unstructured data.\n Your core competencies include statistical analysis, data cleaning, exploratory data analysis (EDA), hypothesis testing, \n predictive modeling, and data visualization. You translate raw data into actionable business intelligence with rigorous \n methodological transparency.\n\n\n\n 1. **Understand**: Clarify the analytical objectives, data sources, and success metrics with the user.\n 2. **Data Assessment**: Evaluate data quality (completeness, consistency, outliers) and perform necessary cleaning/validation.\n 3. **Exploratory Analysis**: Decompose the dataset into logical segments; calculate descriptive statistics and identify patterns, correlations, or anomalies.\n 4. **Analytical Execution**: \n - Use `CodeExec` (Python) for all computational tasks—never rely on mental arithmetic for complex calculations.\n - Apply appropriate statistical methods (regression, clustering, time-series analysis, etc.) based on data type and business question.\n 5. **Visualization**: Generate clear, publication-ready charts and graphs using the coding environment to illustrate findings visually.\n 6. **Validation**: Verify statistical significance, check for biases, validate assumptions, and ensure reproducibility of results.\n 7. **Synthesis**: Summarize insights in business-friendly language, highlight limitations of the analysis, and provide data-driven recommendations.\n\n\n\n - Always execute data processing and calculations via code; never guess or approximate numerical results.\n - All visualizations must be generated programmatically and returned as renderable outputs.\n - Cite data sources and methodologies; flag any data quality issues that may affect interpretation.\n", "temperature": 0.2, "temperatureEnabled": true, "tenant_llm_id": 598, @@ -199,7 +199,7 @@ } ], "showStructuredOutput": false, - "sys_prompt": "\n You are an expert Data Analyst AI assistant, specialized in extracting insights from structured and unstructured data.\n Your core competencies include statistical analysis, data cleaning, exploratory data analysis (EDA), hypothesis testing, \n predictive modeling, and data visualization. You translate raw data into actionable business intelligence with rigorous \n methodological transparency.\n\n\n\n 1. **Understand**: Clarify the analytical objectives, data sources, and success metrics with the user.\n 2. **Data Assessment**: Evaluate data quality (completeness, consistency, outliers) and perform necessary cleaning/validation.\n 3. **Exploratory Analysis**: Decompose the dataset into logical segments; calculate descriptive statistics and identify patterns, correlations, or anomalies.\n 4. **Analytical Execution**: \n - Use `CodeExec` (Python/SQL/R) for all computational tasks—never rely on mental arithmetic for complex calculations.\n - Apply appropriate statistical methods (regression, clustering, time-series analysis, etc.) based on data type and business question.\n 5. **Visualization**: Generate clear, publication-ready charts and graphs using the coding environment to illustrate findings visually.\n 6. **Validation**: Verify statistical significance, check for biases, validate assumptions, and ensure reproducibility of results.\n 7. **Synthesis**: Summarize insights in business-friendly language, highlight limitations of the analysis, and provide data-driven recommendations.\n\n\n\n - Always execute data processing and calculations via code; never guess or approximate numerical results.\n - All visualizations must be generated programmaticallyand returned as renderable outputs.\n - Cite data sources and methodologies; flag any data quality issues that may affect interpretation.\n", + "sys_prompt": "\n You are an expert Data Analyst AI assistant, specialized in extracting insights from structured and unstructured data.\n Your core competencies include statistical analysis, data cleaning, exploratory data analysis (EDA), hypothesis testing, \n predictive modeling, and data visualization. You translate raw data into actionable business intelligence with rigorous \n methodological transparency.\n\n\n\n 1. **Understand**: Clarify the analytical objectives, data sources, and success metrics with the user.\n 2. **Data Assessment**: Evaluate data quality (completeness, consistency, outliers) and perform necessary cleaning/validation.\n 3. **Exploratory Analysis**: Decompose the dataset into logical segments; calculate descriptive statistics and identify patterns, correlations, or anomalies.\n 4. **Analytical Execution**: \n - Use `CodeExec` (Python) for all computational tasks—never rely on mental arithmetic for complex calculations.\n - Apply appropriate statistical methods (regression, clustering, time-series analysis, etc.) based on data type and business question.\n 5. **Visualization**: Generate clear, publication-ready charts and graphs using the coding environment to illustrate findings visually.\n 6. **Validation**: Verify statistical significance, check for biases, validate assumptions, and ensure reproducibility of results.\n 7. **Synthesis**: Summarize insights in business-friendly language, highlight limitations of the analysis, and provide data-driven recommendations.\n\n\n\n - Always execute data processing and calculations via code; never guess or approximate numerical results.\n - All visualizations must be generated programmatically and returned as renderable outputs.\n - Cite data sources and methodologies; flag any data quality issues that may affect interpretation.\n", "temperature": 0.2, "temperatureEnabled": true, "tenant_llm_id": 598, diff --git a/test/unit_test/agent/test_data_analysis_beginner_template.py b/test/unit_test/agent/test_data_analysis_beginner_template.py new file mode 100644 index 00000000000..d2a069ee8b4 --- /dev/null +++ b/test/unit_test/agent/test_data_analysis_beginner_template.py @@ -0,0 +1,26 @@ +import json +from pathlib import Path + + +def _data_analysis_prompts(value): + if isinstance(value, dict): + for key, child in value.items(): + if key == "sys_prompt" and isinstance(child, str) and "Data Analyst AI assistant" in child: + yield child + else: + yield from _data_analysis_prompts(child) + elif isinstance(value, list): + for child in value: + yield from _data_analysis_prompts(child) + + +def test_data_analysis_template_keeps_codeexec_prompt_copies_in_sync(): + template_path = Path(__file__).parents[3] / "agent" / "templates" / "data_analysis_beginner_assistant.json" + template = json.loads(template_path.read_text()) + prompts = list(_data_analysis_prompts(template)) + + assert len(prompts) == 2 + assert prompts[0] == prompts[1] + assert all("CodeExec` (Python)" in prompt for prompt in prompts) + assert all("Python/SQL/R" not in prompt for prompt in prompts) + assert all("programmaticallyand" not in prompt for prompt in prompts) From 2dbce829904b8e56a6e0e7298186c162440e2738 Mon Sep 17 00:00:00 2001 From: Sbaaoui Idriss <112825897+6ba3i@users.noreply.github.com> Date: Fri, 11 Sep 2026 15:50:41 +0800 Subject: [PATCH 108/568] fix(storage): retry transient S3 failures (#19526) --- rag/utils/s3_conn.py | 42 +++++-- test/unit_test/rag/utils/test_s3_conn.py | 149 +++++++++++++++++++++++ 2 files changed, 181 insertions(+), 10 deletions(-) diff --git a/rag/utils/s3_conn.py b/rag/utils/s3_conn.py index f2845940262..5af1ce9c455 100644 --- a/rag/utils/s3_conn.py +++ b/rag/utils/s3_conn.py @@ -23,6 +23,8 @@ from common.decorator import singleton from common import settings +MAX_ATTEMPTS = 3 + @singleton class RAGFlowS3: @@ -72,7 +74,7 @@ def __open__(self): if self.conn: self.__close__() except Exception: - pass + self.conn = None try: s3_params = {} @@ -100,8 +102,11 @@ def __open__(self): s3_params["config"] = Config(**config_kwargs) self.conn = [boto3.client("s3", **s3_params)] + return True except Exception: + self.conn = None logging.exception(f"Fail to connect at region {self.region_name} or endpoint {self.endpoint_url}") + return False def __close__(self): del self.conn[0] @@ -144,7 +149,7 @@ def put(self, bucket, fnm, binary, *args, **kwargs): that use ``auto`` to select their own location. """ logging.debug(f"bucket name {bucket}; filename :{fnm}:") - for _ in range(1): + for attempt in range(MAX_ATTEMPTS): try: if not self.bucket_exists(bucket): bucket_config = {"Bucket": bucket} @@ -159,9 +164,12 @@ def put(self, bucket, fnm, binary, *args, **kwargs): return r except Exception: - logging.exception(f"Fail put {bucket}/{fnm}") - self.__open__() - time.sleep(1) + logging.exception(f"Fail put {bucket}/{fnm}, attempt {attempt + 1}/{MAX_ATTEMPTS}") + if attempt == MAX_ATTEMPTS - 1: + raise + if not self.__open__(): + raise + time.sleep(2**attempt) @use_prefix_path @use_default_bucket @@ -174,16 +182,30 @@ def rm(self, bucket, fnm, *args, **kwargs): @use_prefix_path @use_default_bucket def get(self, bucket, fnm, *args, **kwargs): - for _ in range(1): + for attempt in range(MAX_ATTEMPTS): try: r = self.conn[0].get_object(Bucket=bucket, Key=fnm) object_data = r["Body"].read() return object_data + except ClientError as e: + response = e.response if isinstance(e.response, dict) else {} + error = response.get("Error", {}) + code = error.get("Code") if isinstance(error, dict) else None + if code in ("404", "NoSuchKey", "NotFound"): + return None + logging.exception(f"fail get {bucket}/{fnm}, attempt {attempt + 1}/{MAX_ATTEMPTS}") + if attempt == MAX_ATTEMPTS - 1: + raise + if not self.__open__(): + raise + time.sleep(2**attempt) except Exception: - logging.exception(f"fail get {bucket}/{fnm}") - self.__open__() - time.sleep(1) - return None + logging.exception(f"fail get {bucket}/{fnm}, attempt {attempt + 1}/{MAX_ATTEMPTS}") + if attempt == MAX_ATTEMPTS - 1: + raise + if not self.__open__(): + raise + time.sleep(2**attempt) @use_prefix_path @use_default_bucket diff --git a/test/unit_test/rag/utils/test_s3_conn.py b/test/unit_test/rag/utils/test_s3_conn.py index c77178c8eed..0171256973b 100644 --- a/test/unit_test/rag/utils/test_s3_conn.py +++ b/test/unit_test/rag/utils/test_s3_conn.py @@ -17,6 +17,9 @@ import importlib from unittest.mock import Mock +import pytest +from botocore.exceptions import ClientError + # rag.utils.s3_conn and common.settings import each other (s3_conn needs # settings.S3; settings re-imports RAGFlowS3). The cycle resolves only when # common.settings is imported first, the same order the app uses. Importing it @@ -63,3 +66,149 @@ def test_s3_health_returns_false_on_client_error(monkeypatch): client.head_bucket.side_effect = ConnectionError("unavailable") assert storage.health() is False + + +def _client_error(code): + return ClientError({"Error": {"Code": code}}, "GetObject") + + +def test_s3_put_succeeds_after_transient_failure(monkeypatch): + storage, client, _ = _new_storage(monkeypatch, {"bucket": "ragflow"}) + client.upload_fileobj.side_effect = [ConnectionError("temporary"), None] + reconnect = Mock(return_value=True) + monkeypatch.setattr(storage, "__open__", reconnect) + sleep = Mock() + monkeypatch.setattr(s3_conn.time, "sleep", sleep) + + assert storage.put("kb", "file.txt", b"data") is None + assert client.upload_fileobj.call_count == 2 + reconnect.assert_called_once_with() + sleep.assert_called_once_with(1) + + +def test_s3_put_succeeds_on_first_attempt(monkeypatch): + storage, client, _ = _new_storage(monkeypatch, {"bucket": "ragflow"}) + + assert storage.put("kb", "file.txt", b"data") is client.upload_fileobj.return_value + client.upload_fileobj.assert_called_once() + + +def test_s3_put_succeeds_after_two_transient_failures(monkeypatch): + storage, client, _ = _new_storage(monkeypatch, {"bucket": "ragflow"}) + client.upload_fileobj.side_effect = [ConnectionError("one"), ConnectionError("two"), None] + reconnect = Mock(return_value=True) + monkeypatch.setattr(storage, "__open__", reconnect) + sleep = Mock() + monkeypatch.setattr(s3_conn.time, "sleep", sleep) + + assert storage.put("kb", "file.txt", b"data") is None + assert client.upload_fileobj.call_count == 3 + assert reconnect.call_count == 2 + assert sleep.call_args_list == [((1,), {}), ((2,), {})] + + +def test_s3_put_exhaustion_reraises_and_uses_expected_retries(monkeypatch): + storage, client, _ = _new_storage(monkeypatch, {"bucket": "ragflow"}) + failure = ConnectionError("temporary") + client.upload_fileobj.side_effect = failure + reconnect = Mock(return_value=True) + monkeypatch.setattr(storage, "__open__", reconnect) + sleep = Mock() + monkeypatch.setattr(s3_conn.time, "sleep", sleep) + + with pytest.raises(ConnectionError) as raised: + storage.put("kb", "file.txt", b"data") + + assert raised.value is failure + assert client.upload_fileobj.call_count == 3 + assert reconnect.call_count == 2 + assert sleep.call_args_list == [((1,), {}), ((2,), {})] + + +def test_s3_put_reconnect_failure_preserves_operation_error(monkeypatch): + storage, client, _ = _new_storage(monkeypatch, {"bucket": "ragflow"}) + failure = ConnectionError("upload failed") + client.upload_fileobj.side_effect = failure + reconnect = Mock(return_value=False) + monkeypatch.setattr(storage, "__open__", reconnect) + sleep = Mock() + monkeypatch.setattr(s3_conn.time, "sleep", sleep) + + with pytest.raises(ConnectionError) as raised: + storage.put("kb", "file.txt", b"data") + + assert raised.value is failure + assert client.upload_fileobj.call_count == 1 + sleep.assert_not_called() + + +def test_s3_get_succeeds_after_transient_failure(monkeypatch): + storage, client, _ = _new_storage(monkeypatch, {"bucket": "ragflow"}) + client.get_object.side_effect = [ConnectionError("temporary"), {"Body": Mock(read=Mock(return_value=b"data"))}] + reconnect = Mock(return_value=True) + monkeypatch.setattr(storage, "__open__", reconnect) + sleep = Mock() + monkeypatch.setattr(s3_conn.time, "sleep", sleep) + + assert storage.get("kb", "file.txt") == b"data" + assert client.get_object.call_count == 2 + reconnect.assert_called_once_with() + sleep.assert_called_once_with(1) + + +def test_s3_get_succeeds_on_first_attempt(monkeypatch): + storage, client, _ = _new_storage(monkeypatch, {"bucket": "ragflow"}) + client.get_object.return_value = {"Body": Mock(read=Mock(return_value=b"data"))} + + assert storage.get("kb", "file.txt") == b"data" + client.get_object.assert_called_once() + + +@pytest.mark.parametrize("code", ["404", "NoSuchKey", "NotFound"]) +def test_s3_get_missing_object_codes_return_none_without_retry(monkeypatch, code): + storage, client, _ = _new_storage(monkeypatch, {"bucket": "ragflow"}) + client.get_object.side_effect = _client_error(code) + reconnect = Mock(return_value=True) + monkeypatch.setattr(storage, "__open__", reconnect) + sleep = Mock() + monkeypatch.setattr(s3_conn.time, "sleep", sleep) + + assert storage.get("kb", "missing.txt") is None + client.get_object.assert_called_once_with(Bucket="ragflow", Key="missing.txt") + reconnect.assert_not_called() + sleep.assert_not_called() + + +def test_s3_get_non_not_found_client_error_exhausts_retries(monkeypatch): + storage, client, _ = _new_storage(monkeypatch, {"bucket": "ragflow"}) + failure = _client_error("AccessDenied") + client.get_object.side_effect = failure + reconnect = Mock(return_value=True) + monkeypatch.setattr(storage, "__open__", reconnect) + sleep = Mock() + monkeypatch.setattr(s3_conn.time, "sleep", sleep) + + with pytest.raises(ClientError) as raised: + storage.get("kb", "file.txt") + + assert raised.value is failure + assert client.get_object.call_count == 3 + assert reconnect.call_count == 2 + assert sleep.call_args_list == [((1,), {}), ((2,), {})] + + +def test_s3_get_reconnect_failure_preserves_operation_error(monkeypatch): + storage, client, _ = _new_storage(monkeypatch, {"bucket": "ragflow"}) + failure = ConnectionError("download failed") + client.get_object.side_effect = failure + reconnect = Mock(return_value=False) + monkeypatch.setattr(storage, "__open__", reconnect) + sleep = Mock() + monkeypatch.setattr(s3_conn.time, "sleep", sleep) + + with pytest.raises(ConnectionError) as raised: + storage.get("kb", "file.txt") + + assert raised.value is failure + assert client.get_object.call_count == 1 + sleep.assert_not_called() From ce34ec42f5e700241a6f8066700640ef934a7d9c Mon Sep 17 00:00:00 2001 From: qinling0210 <88864212+qinling0210@users.noreply.github.com> Date: Fri, 11 Sep 2026 15:58:42 +0800 Subject: [PATCH 109/568] Port agentic RAG PRs to GO (#19527) ### Summary Port https://github.com/infiniflow/ragflow/pull/19424/ https://github.com/infiniflow/ragflow/pull/19459/ Address comments from https://github.com/infiniflow/ragflow/pull/19500 --- cmd/ragflow_server.go | 10 +- internal/agent/chat/message_fit.go | 118 ++++++-- internal/agent/chat/message_fit_test.go | 108 ++++++++ internal/agent/tool/agentic_search.go | 8 +- internal/agent/tool/agentic_search_test.go | 2 +- internal/agent/tool/dataset_navigation.go | 58 +++- .../agent/tool/dataset_navigation_test.go | 113 +++++++- internal/entity/models/aliyun.go | 42 ++- internal/entity/models/aliyun_test.go | 197 ++++++++++++++ internal/entity/models/chat_tools.go | 5 +- internal/entity/models/chat_tools_test.go | 44 ++- internal/entity/models/llm.go | 29 +- internal/entity/models/llm_test.go | 80 ++++++ .../ingestion/component/chunker/title_cap.go | 8 +- internal/rag/advanced_rag/agentic_rag.go | 162 ++++++++++- .../rag/advanced_rag/agentic_rag_graph.go | 52 ++-- .../advanced_rag/agentic_rag_graph_test.go | 105 +++++++- internal/rag/advanced_rag/agentic_rag_test.go | 182 ++++++++++++- .../advanced_rag/harness/action_session.go | 172 ++++++------ .../harness/action_session_test.go | 103 ++++++- .../rag/advanced_rag/harness/arithmetic.go | 13 +- .../advanced_rag/harness/arithmetic_test.go | 24 ++ .../rag/advanced_rag/harness/doc_fetch.go | 49 +++- .../advanced_rag/harness/doc_fetch_test.go | 127 +++++++++ internal/rag/advanced_rag/harness/kbinfos.go | 140 ++++++++-- .../rag/advanced_rag/harness/kbinfos_test.go | 154 ++++++++++- internal/rag/advanced_rag/harness/memory.go | 28 +- .../rag/advanced_rag/harness/memory_test.go | 32 +++ .../orchestrator/sufficient_context.go | 90 +++++-- .../orchestrator/sufficient_context_test.go | 165 +++++++++++- .../harness/tool_compiled_expansion.go | 123 ++++++--- .../harness/tool_compiled_expansion_test.go | 119 +++++++++ .../rag/advanced_rag/harness/tool_executor.go | 103 ++++--- .../harness/tool_executor_test.go | 117 +++++++- .../advanced_rag/harness/tool_exploration.go | 37 ++- .../harness/tool_exploration_test.go | 84 ++++++ .../advanced_rag/harness/tool_navigation.go | 108 +++++++- .../harness/tool_navigation_test.go | 252 +++++++++++++++++- .../rag/advanced_rag/harness/tool_search.go | 161 ++++++----- .../advanced_rag/harness/tool_search_test.go | 159 +++++++++-- .../harness/tool_text_processing.go | 115 ++++++-- internal/rag/prompts/action_run.md | 33 +++ internal/rag/prompts/generator.go | 119 ++++++--- internal/rag/prompts/generator_test.go | 100 +++++++ internal/service/chat_pipeline.go | 23 +- internal/service/chat_pipeline_test.go | 40 +++ internal/service/model_service.go | 134 ++++++++-- internal/service/model_service_test.go | 177 ++++++++++++ internal/service/nav/chunk_agg_router.go | 21 +- internal/service/nav/chunk_agg_router_test.go | 30 ++- internal/service/nlp/datasetnav.go | 85 ++++-- internal/service/nlp/datasetnav_test.go | 156 +++++++++-- internal/tokenizer/failfast_test.go | 25 +- internal/tokenizer/tokenizer.go | 41 +-- rag/advanced_rag/harness/memory.py | 11 +- .../orchestrator/sufficient_context.py | 47 +++- rag/prompts/generator.py | 94 ++++--- 57 files changed, 4264 insertions(+), 670 deletions(-) create mode 100644 internal/rag/advanced_rag/harness/doc_fetch_test.go create mode 100644 internal/rag/advanced_rag/harness/tool_exploration_test.go diff --git a/cmd/ragflow_server.go b/cmd/ragflow_server.go index 314a07da3d3..bdee1038356 100644 --- a/cmd/ragflow_server.go +++ b/cmd/ragflow_server.go @@ -650,8 +650,9 @@ func runIngestor(ctx context.Context, cancel context.CancelFunc, args *serverArg } defer tokenizer.Close() - // Fail fast if the cl100k_base BPE table is missing: without it - // NumTokensFromString silently returns 0, corrupting every token budget. + // Fail fast if the cl100k_base BPE table is missing. NumTokensFromString / + // TrimContentToTokenLimit now panic rather than degrading silently, so this + // trades a mid-request panic for a clear startup failure. if err := tokenizer.InitCL100KEncoder(); err != nil { common.Fatal("Failed to initialize cl100k_base tokenizer", zap.Error(err)) } @@ -800,8 +801,9 @@ func runAPI(ctx context.Context, args *serverArgs) error { } defer tokenizer.Close() - // Fail fast if the cl100k_base BPE table is missing: without it - // NumTokensFromString silently returns 0, corrupting every token budget. + // Fail fast if the cl100k_base BPE table is missing. NumTokensFromString / + // TrimContentToTokenLimit now panic rather than degrading silently, so this + // trades a mid-request panic for a clear startup failure. if err := tokenizer.InitCL100KEncoder(); err != nil { common.Fatal("Failed to initialize cl100k_base tokenizer", zap.Error(err)) } diff --git a/internal/agent/chat/message_fit.go b/internal/agent/chat/message_fit.go index 24c132340aa..b7dcbf21cd0 100644 --- a/internal/agent/chat/message_fit.go +++ b/internal/agent/chat/message_fit.go @@ -51,8 +51,10 @@ func ContextFitBudget(maxLength int) int { } // validateFittedMessages checks that the fitted message list is non-empty -// and the last message is a non-empty user turn (content or multi-modal -// parts). Returns an error string on failure, empty string on success. +// and the last message is a user turn that still carries something usable — +// non-empty text, or a real media payload. Returns an error string on failure, +// empty string on success. +// // Python requires len >= 2 because the system prompt is always injected // upstream; Go allows len >= 1 because the system message may be embedded // inside msgs (from buildMessagesWithImages) or absent entirely. @@ -64,36 +66,70 @@ func validateFittedMessages(msgFit []schema.Message) string { if last.Role != schema.User { return "**ERROR**: LLM last message is not a user turn after prompt fitting; check model content_length context setting" } - if strings.TrimSpace(last.Content) == "" && len(last.UserInputMultiContent) == 0 { + if strings.TrimSpace(last.Content) == "" && !hasUsableContent(last.UserInputMultiContent) { return "**ERROR**: LLM user message is empty after prompt fitting; check model content_length context setting" } return "" } +// hasUsableContent reports whether the multi-modal parts still give the model +// something to work with: non-empty text, or a media payload with a url or +// inline data. Parts merely EXISTING is not enough — a text-only turn whose +// text the fitting trimmed away leaves a non-empty slice holding an empty text +// part, and sending that turn would ask the model to answer nothing (Python's +// validate_fitted_messages rejects an empty user content the same way). +func hasUsableContent(parts []schema.MessageInputPart) bool { + for _, p := range parts { + if p.Type == schema.ChatMessagePartTypeText { + if strings.TrimSpace(p.Text) != "" { + return true + } + continue + } + for _, c := range payloadCommons(p) { + hasURL := c.URL != nil && strings.TrimSpace(*c.URL) != "" + hasData := c.Base64Data != nil && strings.TrimSpace(*c.Base64Data) != "" + if hasURL || hasData { + return true + } + } + } + return false +} + +// payloadCommons returns the media payloads a part carries, if any. +func payloadCommons(p schema.MessageInputPart) []*schema.MessagePartCommon { + out := make([]*schema.MessagePartCommon, 0, 4) + if p.Image != nil { + out = append(out, &p.Image.MessagePartCommon) + } + if p.Audio != nil { + out = append(out, &p.Audio.MessagePartCommon) + } + if p.Video != nil { + out = append(out, &p.Video.MessagePartCommon) + } + if p.File != nil { + out = append(out, &p.File.MessagePartCommon) + } + return out +} + // FitMessages applies message_fit_in semantics to the given messages and // validates that the result ends with a non-empty user turn. Returns the // fitted messages and an error string (empty on success). // Mirrors Python's LLM.fit_messages in PR #16413. func FitMessages(systemPrompt string, msgs []schema.Message, maxLength int) ([]schema.Message, string) { // Deep-copy msgs (mirrors Python's deepcopy) to avoid mutating caller's slice. + // Copy the WHOLE message first: the fitted history must keep every field the + // model layer relies on (tool calls, tool ids, reasoning, extras, ...), which + // a Role/Content/parts literal would silently drop. Then deep-copy only the + // reference-backed fields fitting rewrites. copied := make([]schema.Message, len(msgs)) for i, m := range msgs { - cloned := slices.Clone(m.UserInputMultiContent) - for j, p := range cloned { - if p.Image != nil { - imgCopy := *p.Image - if p.Image.URL != nil { - u := *p.Image.URL - imgCopy.URL = &u - } - cloned[j].Image = &imgCopy - } - } - copied[i] = schema.Message{ - Role: m.Role, - Content: m.Content, - UserInputMultiContent: cloned, - } + cloned := m + cloned.UserInputMultiContent = deepCopyInputParts(m.UserInputMultiContent) + copied[i] = cloned } // Convert to messagefit.Message. Track where each entry's text lives @@ -176,3 +212,47 @@ func FitMessages(systemPrompt string, msgs []schema.Message, maxLength int) ([]s } return result, validateFittedMessages(result) } + +// deepCopyInputParts clones the multi-modal parts — the slice, the media +// payload structs and their url/base64 pointers — so fitting can rewrite a +// part's text or drop parts without touching the caller's message. +func deepCopyInputParts(parts []schema.MessageInputPart) []schema.MessageInputPart { + out := slices.Clone(parts) + for j, p := range out { + if p.Image != nil { + img := *p.Image + img.MessagePartCommon = clonePartCommon(img.MessagePartCommon) + out[j].Image = &img + } + if p.Audio != nil { + audio := *p.Audio + audio.MessagePartCommon = clonePartCommon(audio.MessagePartCommon) + out[j].Audio = &audio + } + if p.Video != nil { + video := *p.Video + video.MessagePartCommon = clonePartCommon(video.MessagePartCommon) + out[j].Video = &video + } + if p.File != nil { + file := *p.File + file.MessagePartCommon = clonePartCommon(file.MessagePartCommon) + out[j].File = &file + } + } + return out +} + +// clonePartCommon copies a payload's pointer-backed fields so the fitted message +// never aliases the caller's payload. +func clonePartCommon(c schema.MessagePartCommon) schema.MessagePartCommon { + if c.URL != nil { + u := *c.URL + c.URL = &u + } + if c.Base64Data != nil { + d := *c.Base64Data + c.Base64Data = &d + } + return c +} diff --git a/internal/agent/chat/message_fit_test.go b/internal/agent/chat/message_fit_test.go index 3820fedb146..6374368db9f 100644 --- a/internal/agent/chat/message_fit_test.go +++ b/internal/agent/chat/message_fit_test.go @@ -209,3 +209,111 @@ func TestFitMessages_ImageOnlyLastTurnOverBudget(t *testing.T) { t.Fatalf("image-only turn lost or modified after over-budget fitting: %+v", last) } } + +// TestFitMessages_RejectsTextOnlyTurnTrimmedToEmpty pins the validation rule: a +// multi-modal turn whose only part is text that the fitting trimmed away has +// nothing left to send, so the non-empty parts slice must not pass it as a valid +// user turn (Python's validate_fitted_messages rejects empty user content too). +func TestFitMessages_RejectsTextOnlyTurnTrimmedToEmpty(t *testing.T) { + // The system share absorbs the whole (small) budget, so the user turn is + // trimmed to nothing. A zero budget would be clamped to 8192 by the fitter. + msgs := []schema.Message{ + {Role: schema.System, Content: strings.Repeat("sys ", 100)}, + {Role: schema.User, UserInputMultiContent: []schema.MessageInputPart{ + {Type: schema.ChatMessagePartTypeText, Text: strings.Repeat("question ", 400)}, + }}, + } + fitted, fitErr := FitMessages("", msgs, 60) + if fitErr == "" { + t.Fatalf("an empty user turn was accepted: %+v", fitted) + } + if !strings.Contains(fitErr, "user message is empty") { + t.Errorf("fit error = %q, want the empty-user-message error", fitErr) + } +} + +// TestFitMessages_KeepsTurnWithImageWhenTextTrimsToEmpty is the counterpart: the +// text part is trimmed away but the turn still carries an image payload, which +// IS usable — so it stays a valid user turn and the image is preserved. +func TestFitMessages_KeepsTurnWithImageWhenTextTrimsToEmpty(t *testing.T) { + imgURL := "data:image/png;base64,AAAA" + msgs := []schema.Message{ + {Role: schema.System, Content: strings.Repeat("sys ", 100)}, + {Role: schema.User, UserInputMultiContent: []schema.MessageInputPart{ + {Type: schema.ChatMessagePartTypeText, Text: strings.Repeat("question ", 400)}, + {Type: schema.ChatMessagePartTypeImageURL, Image: &schema.MessageInputImage{ + MessagePartCommon: schema.MessagePartCommon{URL: &imgURL}, + }}, + }}, + } + fitted, fitErr := FitMessages("", msgs, 60) + if fitErr != "" { + t.Fatalf("turn with an image payload was rejected: %s", fitErr) + } + last := fitted[len(fitted)-1] + if len(last.UserInputMultiContent) != 2 || last.UserInputMultiContent[1].Type != schema.ChatMessagePartTypeImageURL { + t.Fatalf("image part lost: %+v", last.UserInputMultiContent) + } + if got := strings.TrimSpace(last.UserInputMultiContent[0].Text); got != "" { + t.Errorf("text part = %q, want it trimmed away by the zero budget", got) + } +} + +// TestFitMessages_PreservesAllMessageFields pins the deep copy: fitting rewrites +// only the text it touches, so the returned messages must still carry every +// other schema.Message field (tool calls, tool ids, reasoning, generated parts, +// extras, name) — and the caller's payload must not be aliased. +func TestFitMessages_PreservesAllMessageFields(t *testing.T) { + imgURL := "data:image/png;base64,AAAA" + msgs := []schema.Message{ + {Role: schema.System, Content: "sys"}, + { + Role: schema.Assistant, + Content: "calling a tool", + ReasoningContent: "because", + AssistantGenMultiContent: []schema.MessageOutputPart{ + {Type: schema.ChatMessagePartTypeText, Text: "generated"}, + }, + ToolCalls: []schema.ToolCall{{ + ID: "call-1", Type: "function", + Function: schema.FunctionCall{Name: "rag", Arguments: "{}"}, + }}, + Extra: map[string]any{"k": "v"}, + }, + {Role: schema.Tool, Content: "tool result", ToolCallID: "call-1", ToolName: "rag"}, + {Role: schema.User, Name: "u", UserInputMultiContent: []schema.MessageInputPart{ + {Type: schema.ChatMessagePartTypeText, Text: "question"}, + {Type: schema.ChatMessagePartTypeImageURL, Image: &schema.MessageInputImage{ + MessagePartCommon: schema.MessagePartCommon{URL: &imgURL}, + }}, + }}, + } + fitted, fitErr := FitMessages("", msgs, 100000) + if fitErr != "" { + t.Fatalf("unexpected fit error: %s", fitErr) + } + if len(fitted) != 4 { + t.Fatalf("got %d messages, want 4", len(fitted)) + } + + assistant := fitted[1] + if assistant.ReasoningContent != "because" || len(assistant.AssistantGenMultiContent) != 1 || + len(assistant.ToolCalls) != 1 || assistant.ToolCalls[0].ID != "call-1" || + assistant.ToolCalls[0].Function.Name != "rag" || assistant.Extra["k"] != "v" { + t.Errorf("assistant message lost fields after fitting: %+v", assistant) + } + if tool := fitted[2]; tool.ToolCallID != "call-1" || tool.ToolName != "rag" { + t.Errorf("tool message lost fields after fitting: %+v", tool) + } + user := fitted[3] + if user.Name != "u" || len(user.UserInputMultiContent) != 2 { + t.Errorf("user message lost fields after fitting: %+v", user) + } + img := user.UserInputMultiContent[1].Image + if img == nil || img.URL == nil || *img.URL != imgURL { + t.Fatalf("image payload lost after fitting: %+v", img) + } + if img.URL == &imgURL { + t.Error("image url was not deep-copied: the fitted message aliases the caller's payload") + } +} diff --git a/internal/agent/tool/agentic_search.go b/internal/agent/tool/agentic_search.go index 98ab03eea3a..4586662397c 100644 --- a/internal/agent/tool/agentic_search.go +++ b/internal/agent/tool/agentic_search.go @@ -285,7 +285,11 @@ func narrowContent(content string, kwds []string) (string, bool) { return "..." + highlightKeywords(b.String(), kwds) + "...", true } -// highlightKeywords wraps keyword occurrences in . +// highlightKeywords stars keyword occurrences, mirroring Python +// _highlight_keywords' `*term*` marker (text_processing.py:412) — NOT an XML +// tag: search.py narrows through the same helper, so a starred span is what the +// Python canvas hands the model. (The tags elsewhere in this port are the +// engine's highlight markup: rag/utils/*_conn.py, akshare.go.) func highlightKeywords(text string, kwds []string) string { if len(kwds) == 0 { return text @@ -310,7 +314,7 @@ func highlightKeywords(text string, kwds []string) string { } pattern += ")" re := regexp.MustCompile(`(?i)` + pattern) - return re.ReplaceAllString(text, "${1}") + return re.ReplaceAllString(text, "*${1}*") } func md5Hex(s string) string { diff --git a/internal/agent/tool/agentic_search_test.go b/internal/agent/tool/agentic_search_test.go index c0c49baf91c..c8354a93ca8 100644 --- a/internal/agent/tool/agentic_search_test.go +++ b/internal/agent/tool/agentic_search_test.go @@ -33,7 +33,7 @@ func TestNarrowContent_KeepsKeywordSentence(t *testing.T) { if !strings.Contains(nc, "key insight") { t.Errorf("narrowed content missing keyword sentence: %q", nc) } - if !strings.Contains(nc, "rocket") { + if !strings.Contains(nc, "*rocket*") { t.Errorf("narrowed content missing highlight: %q", nc) } } diff --git a/internal/agent/tool/dataset_navigation.go b/internal/agent/tool/dataset_navigation.go index 191d27fc725..d302679c595 100644 --- a/internal/agent/tool/dataset_navigation.go +++ b/internal/agent/tool/dataset_navigation.go @@ -39,8 +39,10 @@ type datasetNavigationArgs struct { Topic string `json:"topic"` Keywords string `json:"keywords,omitempty"` DatasetIDs []string `json:"dataset_ids,omitempty"` - DocScope string `json:"doc_scope,omitempty"` - MaxDocs int `json:"max_docs,omitempty"` + // DocScope restricts the routed documents, mirroring Python's + // dataset_navigation_by_tree(doc_scope: list[str] | None = None). + DocScope []string `json:"doc_scope,omitempty"` + MaxDocs int `json:"max_docs,omitempty"` } // datasetNavigationResult is the JSON shape returned to the model. @@ -90,6 +92,10 @@ func (d *DatasetNavigationByTree) Info(_ context.Context) (*schema.ToolInfo, err Type: schema.String, Desc: "Optional additional keywords to disambiguate the topic.", }, + "doc_scope": { + Type: schema.Array, + Desc: "Optional doc ids to restrict the navigation to.", + }, }), }, nil } @@ -133,10 +139,30 @@ func (d *DatasetNavigationByTree) InvokableRun(ctx context.Context, argumentsInJ // Route RELEVANT docs by querying the nav tree with the topic (semantic KNN). // The topic is the routing signal — we must not return arbitrary doc ids. query := strings.TrimSpace(args.Topic + " " + args.Keywords) + + // Honor the supplied doc scope. Python's dataset_navigation_by_tree threads + // tools.scoped_doc_ids(doc_scope) into BOTH its tree walk and its + // content-recall fallback; the canvas context carries no session scope, so + // only the caller-supplied scope applies here. It is enforced in collect() + // rather than only at the Search call, because the cluster-walk fallback's + // ListClusters/ListChildren take no scope argument. + docScope := compactStrings(args.DocScope) + scopeSet := make(map[string]struct{}, len(docScope)) + for _, id := range docScope { + scopeSet[id] = struct{}{} + } + inScope := func(id string) bool { + if len(scopeSet) == 0 { + return true + } + _, ok := scopeSet[id] + return ok + } + seen := map[string]struct{}{} var docs []string collect := func(id string) { - if id == "" { + if id == "" || !inScope(id) { return } if _, ok := seen[id]; ok { @@ -149,12 +175,11 @@ func (d *DatasetNavigationByTree) InvokableRun(ctx context.Context, argumentsInJ docs = append(docs, id) } - // Primary: semantic search over each dataset's nav tree. + // Primary: semantic search over each dataset's nav tree. The scope is + // forwarded so the service also trims each cluster's returned coverage to it + // (a cluster that merely OVERLAPS the scope must not surface extra docs). for _, datasetID := range datasetIDs { - // No doc scope: Python's dataset_navigation_by_tree applies - // tools.scoped_doc_ids(None), but this canvas tool's context carries no - // session document scope, so the read stays dataset-wide. - hits, err := ns.Search(ctx, tenantID, datasetID, query, nil, nil, maxDocs) + hits, err := ns.Search(ctx, tenantID, datasetID, query, nil, docScope, maxDocs) if err != nil { continue } @@ -170,7 +195,9 @@ func (d *DatasetNavigationByTree) InvokableRun(ctx context.Context, argumentsInJ } // Fallback: if semantic routing found nothing (e.g. no embedder), walk the - // root clusters so the tool still returns a useful (if coarse) doc set. + // root clusters so the tool still returns a useful (if coarse) doc set. The + // scope still applies — collect() filters these leaves, standing in for + // Python's _content_recall_docs(tools, query, doc_scope). if len(docs) == 0 { for _, datasetID := range datasetIDs { clusters, _, err := ns.ListClusters(ctx, tenantID, datasetID, 0, 100) @@ -205,9 +232,22 @@ func (d *DatasetNavigationByTree) InvokableRun(ctx context.Context, argumentsInJ } func (d *DatasetNavigationByTree) mergeDefaults(args datasetNavigationArgs) datasetNavigationArgs { + // Blank request values count as NOT SUPPLIED, and they must be compacted + // before the default is considered: a request like {"doc_scope":[" "]} has a + // non-zero length, so it used to suppress d.defaults.DocScope and then + // compact away at the use site — leaving an empty scope, which inScope() and + // ns.Search read as "unscoped". The configured restriction was therefore + // silently disabled by a value that carries no document id, letting the tool + // return documents the default scope excludes. Python's + // RAGTools.scoped_doc_ids treats a falsy request scope the same way this now + // does: fall back to the configured scope (agentic_rag.py:352-358). + args.DocScope = compactStrings(args.DocScope) if len(args.DatasetIDs) == 0 && len(d.defaults.DatasetIDs) != 0 { args.DatasetIDs = append([]string(nil), d.defaults.DatasetIDs...) } + if len(args.DocScope) == 0 && len(d.defaults.DocScope) != 0 { + args.DocScope = compactStrings(d.defaults.DocScope) + } if args.MaxDocs <= 0 { args.MaxDocs = d.defaults.MaxDocs } diff --git a/internal/agent/tool/dataset_navigation_test.go b/internal/agent/tool/dataset_navigation_test.go index 75d7ad8821f..929378ab986 100644 --- a/internal/agent/tool/dataset_navigation_test.go +++ b/internal/agent/tool/dataset_navigation_test.go @@ -2,6 +2,7 @@ package tool import ( "context" + "encoding/json" "sync" "testing" @@ -14,7 +15,8 @@ import ( // queries by topic rather than walking arbitrary clusters. type navRoutingFake struct { mu sync.Mutex - searched []string // topics passed to Search + searched []string // topics passed to Search + scopes [][]string // doc scopes passed to Search hits []nav.NavHit clusters []nav.NavNode children map[string][]nav.NavNode @@ -24,9 +26,10 @@ func (f *navRoutingFake) UpsertDoc(context.Context, nav.UpsertDocInput) error { func (f *navRoutingFake) RemoveDoc(context.Context, string, string, string) error { return nil } -func (f *navRoutingFake) Search(_ context.Context, _, _ string, query string, _ []float32, _ []string, _ int) ([]nav.NavHit, error) { +func (f *navRoutingFake) Search(_ context.Context, _, _ string, query string, _ []float32, docScope []string, _ int) ([]nav.NavHit, error) { f.mu.Lock() f.searched = append(f.searched, query) + f.scopes = append(f.scopes, append([]string(nil), docScope...)) f.mu.Unlock() return f.hits, nil } @@ -45,6 +48,14 @@ func (f *navRoutingFake) searchedTopics() []string { return append([]string(nil), f.searched...) } +func (f *navRoutingFake) searchedScopes() [][]string { + f.mu.Lock() + defer f.mu.Unlock() + out := make([][]string, len(f.scopes)) + copy(out, f.scopes) + return out +} + // TestDatasetNavigation_UsesTopicRouting asserts the router queries the nav tree // with the topic (semantic search), rather than blindly walking clusters and // returning arbitrary doc ids. @@ -123,6 +134,104 @@ func TestCanvasDatasetIDs_DedupEmpty(t *testing.T) { } } +func navTestContext(t *testing.T) context.Context { + t.Helper() + state := runtime.NewCanvasState("run-1", "task-1") + state.Sys["tenant_id"] = "tenant-1" + return runtime.WithState(t.Context(), state) +} + +func decodeNavDocs(t *testing.T, out string) []string { + t.Helper() + var res struct { + Docs []string `json:"docs"` + } + if err := json.Unmarshal([]byte(out), &res); err != nil { + t.Fatalf("unmarshal result %q: %v", out, err) + } + return res.Docs +} + +// TestDatasetNavigation_HonorsDocScope pins that a supplied doc_scope reaches the +// nav service AND filters the routed result: Python's dataset_navigation_by_tree +// threads tools.scoped_doc_ids(doc_scope), so an out-of-scope document must never +// come back from a scoped request. +func TestDatasetNavigation_HonorsDocScope(t *testing.T) { + fake := &navRoutingFake{hits: []nav.NavHit{ + {Type: nav.TypeNavDoc, DocID: "d1", Name: "in scope"}, + {Type: nav.TypeNavDoc, DocID: "out", Name: "out of scope"}, + }} + prev := nav.GetNavService() + nav.SetNavService(fake) + defer func() { nav.SetNavService(prev) }() + + tool := NewDatasetNavigationByTree() + out, err := tool.InvokableRun(navTestContext(t), `{"topic":"X","dataset_ids":["kb1"],"doc_scope":["d1"]}`) + if err != nil { + t.Fatalf("InvokableRun: %v", err) + } + scopes := fake.searchedScopes() + if len(scopes) != 1 || len(scopes[0]) != 1 || scopes[0][0] != "d1" { + t.Fatalf("doc scope not forwarded to Search: %v", scopes) + } + if docs := decodeNavDocs(t, out); len(docs) != 1 || docs[0] != "d1" { + t.Errorf("docs = %v, want only the in-scope d1", docs) + } +} + +// TestDatasetNavigation_DocScopeFiltersClusterFallback pins the fallback half: +// when semantic routing finds nothing, the cluster walk must still not surface +// out-of-scope documents (ListClusters/ListChildren take no scope, so the tool +// filters the leaves itself — standing in for Python's _content_recall_docs). +func TestDatasetNavigation_DocScopeFiltersClusterFallback(t *testing.T) { + fake := &navRoutingFake{ + clusters: []nav.NavNode{{Name: "c1"}}, + children: map[string][]nav.NavNode{ + "c1": {{DocID: "d1"}, {DocID: "out"}}, + }, + } + prev := nav.GetNavService() + nav.SetNavService(fake) + defer func() { nav.SetNavService(prev) }() + + tool := NewDatasetNavigationByTree() + out, err := tool.InvokableRun(navTestContext(t), `{"topic":"X","dataset_ids":["kb1"],"doc_scope":["d1"]}`) + if err != nil { + t.Fatalf("InvokableRun: %v", err) + } + if docs := decodeNavDocs(t, out); len(docs) != 1 || docs[0] != "d1" { + t.Errorf("fallback docs = %v, want only the in-scope d1", docs) + } +} + +// TestDatasetNavigation_BlankRequestScopeFallsBackToDefaults pins that a blank +// request value cannot DISABLE the configured default scope: [" "] has a +// non-zero length, so it suppressed the default and then compacted to an empty +// scope, which inScope()/ns.Search read as "unscoped" — the tool returned +// documents the default scope excludes. +func TestDatasetNavigation_BlankRequestScopeFallsBackToDefaults(t *testing.T) { + fake := &navRoutingFake{hits: []nav.NavHit{ + {Type: nav.TypeNavDoc, DocID: "d1", Name: "in scope"}, + {Type: nav.TypeNavDoc, DocID: "out", Name: "out of scope"}, + }} + prev := nav.GetNavService() + nav.SetNavService(fake) + defer func() { nav.SetNavService(prev) }() + + tool := NewDatasetNavigationByTreeWithDefaults(datasetNavigationArgs{DocScope: []string{"d1"}}) + out, err := tool.InvokableRun(navTestContext(t), `{"topic":"X","dataset_ids":["kb1"],"doc_scope":[" "]}`) + if err != nil { + t.Fatalf("InvokableRun: %v", err) + } + scopes := fake.searchedScopes() + if len(scopes) != 1 || len(scopes[0]) != 1 || scopes[0][0] != "d1" { + t.Fatalf("doc scope forwarded to Search = %v, want the configured default [d1]", scopes) + } + if docs := decodeNavDocs(t, out); len(docs) != 1 || docs[0] != "d1" { + t.Errorf("docs = %v, want only the in-scope d1 (a blank request value must not disable the default scope)", docs) + } +} + func containsStr(s, sub string) bool { return len(s) > 0 && len(sub) > 0 && (s == sub || containsSub(s, sub)) } diff --git a/internal/entity/models/aliyun.go b/internal/entity/models/aliyun.go index 471ba55468a..388dc3170d7 100644 --- a/internal/entity/models/aliyun.go +++ b/internal/entity/models/aliyun.go @@ -341,7 +341,10 @@ type aliyunNativeEmbedResponse struct { RequestID string `json:"request_id"` Output struct { Embeddings []struct { - TextIndex int `json:"text_index"` + // TextIndex is a pointer so an absent/null key is distinguishable + // from index 0: Python does embds[e["text_index"]] and raises + // KeyError when the key is missing (wrapped into EmbeddingError). + TextIndex *int `json:"text_index"` Embedding []float64 `json:"embedding"` } `json:"embeddings"` } `json:"output"` @@ -355,6 +358,16 @@ type aliyunNativeEmbedResponse struct { // Python QWenEmbed). Inputs are sent in batches of 4 like Python; the response's // text_index is relative to the batch, so it is offset back to the caller's // slice before being returned. +// +// The response is reassembled exactly like Python QWenEmbed.encode: each batch's +// chunk is sized by the NUMBER OF RETURNED EMBEDDINGS and every vector is +// PLACED at its batch-relative text_index (never appended in response order), +// because consumers such as NavEmbedder read the slice positionally and discard +// EmbeddingData.Index. As in Python, a duplicate text_index overwrites the +// earlier vector, a gap leaves an empty vector in that slot, and a text_index +// outside the returned chunk raises — a NEGATIVE text_index counts from the end +// of the chunk (embds[-1] is the last slot), exactly like a Python list +// assignment. func (a *AliyunModel) embedNative(ctx context.Context, root, modelName string, request EmbedRequest, apiConfig *APIConfig, modelUsage *common.ModelUsage) ([]EmbeddingData, error) { textType := "document" if request.Query { @@ -407,15 +420,32 @@ func (a *AliyunModel) embedNative(ctx context.Context, root, modelName string, r if parsed.Code != "" { return nil, fmt.Errorf("aliyun native embeddings API error: %s: %s", parsed.Code, parsed.Message) } + // Mirror Python QWenEmbed.encode: + // embds = [[] for _ in range(len(resp["output"]["embeddings"]))] + // for e in resp["output"]["embeddings"]: + // embds[e["text_index"]] = e["embedding"] + // res.extend(embds) + // including Python list-assignment indexing: a negative text_index + // counts from the END of the chunk (embds[-1] is the last slot), and out + // of range in either direction raises. + embds := make([]EmbeddingData, len(parsed.Output.Embeddings)) for _, item := range parsed.Output.Embeddings { - if item.TextIndex < 0 || item.TextIndex >= len(batch) { - return nil, fmt.Errorf("aliyun native embeddings response index %d out of range for batch of %d", item.TextIndex, len(batch)) + if item.TextIndex == nil { + return nil, fmt.Errorf("aliyun native embeddings response item missing text_index") + } + idx := *item.TextIndex + if idx < 0 { + idx += len(embds) } - embeddings = append(embeddings, EmbeddingData{ + if idx < 0 || idx >= len(embds) { + return nil, fmt.Errorf("aliyun native embeddings response index %d out of range for %d embeddings", *item.TextIndex, len(embds)) + } + embds[idx] = EmbeddingData{ Embedding: item.Embedding, - Index: start + item.TextIndex, - }) + Index: len(embeddings) + idx, + } } + embeddings = append(embeddings, embds...) recordResponseUsage(modelUsage, parsed.RequestID, &TokenUsage{TotalTokens: parsed.Usage.TotalTokens}, "embedding") } return embeddings, nil diff --git a/internal/entity/models/aliyun_test.go b/internal/entity/models/aliyun_test.go index 6a962220cdb..41b3e308d34 100644 --- a/internal/entity/models/aliyun_test.go +++ b/internal/entity/models/aliyun_test.go @@ -738,3 +738,200 @@ func TestAliyunEmbedNativeSendsTextTypeAndBatches(t *testing.T) { t.Errorf("query text_type = %v, want query", bodies[len(bodies)-1]["parameters"]) } } + +// TestAliyunEmbedNativePlacesVectorsByTextIndex pins that an out-of-order +// response is reordered onto the caller's inputs: nav_embedder/dataset-utils +// read the result positionally and discard Index, so placing by text_index is +// what keeps each vector bound to the right text. +func TestAliyunEmbedNativePlacesVectorsByTextIndex(t *testing.T) { + withSSRFBypass(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + // Deliberately reversed: text_index 3,2,1,0 with distinct vectors. + _, _ = w.Write([]byte(`{"output":{"embeddings":[` + + `{"text_index":3,"embedding":[3]},` + + `{"text_index":2,"embedding":[2]},` + + `{"text_index":1,"embedding":[1]},` + + `{"text_index":0,"embedding":[0]}` + + `]},"usage":{"total_tokens":1}}`)) + })) + defer srv.Close() + + m := NewAliyunModel(map[string]string{"default": srv.URL}, URLSuffix{Embedding: "embeddings"}) + apiKey := "test-key" + got, err := m.embedNative(t.Context(), srv.URL, "text-embedding-v4", + EmbedRequest{Texts: []string{"a", "b", "c", "d"}}, &APIConfig{ApiKey: &apiKey}, nil) + if err != nil { + t.Fatalf("embedNative: %v", err) + } + if len(got) != 4 { + t.Fatalf("len = %d, want 4", len(got)) + } + for i, e := range got { + if e.Index != i || len(e.Embedding) != 1 || e.Embedding[0] != float64(i) { + t.Errorf("got[%d] = {index:%d vec:%v}, want {index:%d vec:[%d]}", i, e.Index, e.Embedding, i, i) + } + } +} + +// TestAliyunEmbedNativeDuplicateIndexLastWins pins Python QWenEmbed.encode's +// "embds[e['text_index']] = e['embedding']": a repeated text_index overwrites +// the earlier vector and the slot left unfilled stays empty — no error. +func TestAliyunEmbedNativeDuplicateIndexLastWins(t *testing.T) { + withSSRFBypass(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"output":{"embeddings":[` + + `{"text_index":0,"embedding":[0]},` + + `{"text_index":1,"embedding":[1]},` + + `{"text_index":1,"embedding":[9]}` + + `]},"usage":{"total_tokens":1}}`)) + })) + defer srv.Close() + + m := NewAliyunModel(map[string]string{"default": srv.URL}, URLSuffix{Embedding: "embeddings"}) + apiKey := "test-key" + got, err := m.embedNative(t.Context(), srv.URL, "text-embedding-v4", + EmbedRequest{Texts: []string{"a", "b", "c"}}, &APIConfig{ApiKey: &apiKey}, nil) + if err != nil { + t.Fatalf("embedNative: %v", err) + } + if len(got) != 3 { + t.Fatalf("len = %d, want 3 (one chunk entry per returned embedding)", len(got)) + } + if len(got[0].Embedding) != 1 || got[0].Embedding[0] != 0 { + t.Errorf("got[0] = %v, want [0]", got[0].Embedding) + } + if len(got[1].Embedding) != 1 || got[1].Embedding[0] != 9 { + t.Errorf("got[1] = %v, want the LAST duplicate [9]", got[1].Embedding) + } + if len(got[2].Embedding) != 0 { + t.Errorf("got[2] = %v, want the unfilled slot to stay empty", got[2].Embedding) + } +} + +// TestAliyunEmbedNativeShortResponseStaysShort pins that Go mirrors Python's +// len(resp.embeddings)-sized chunks: a response covering only part of the batch +// is NOT rejected, it just yields a shorter result (Python's res.extend). +func TestAliyunEmbedNativeShortResponseStaysShort(t *testing.T) { + withSSRFBypass(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"output":{"embeddings":[` + + `{"text_index":0,"embedding":[0]},` + + `{"text_index":1,"embedding":[1]}` + + `]},"usage":{"total_tokens":1}}`)) + })) + defer srv.Close() + + m := NewAliyunModel(map[string]string{"default": srv.URL}, URLSuffix{Embedding: "embeddings"}) + apiKey := "test-key" + got, err := m.embedNative(t.Context(), srv.URL, "text-embedding-v4", + EmbedRequest{Texts: []string{"a", "b", "c", "d"}}, &APIConfig{ApiKey: &apiKey}, nil) + if err != nil { + t.Fatalf("embedNative: %v", err) + } + if len(got) != 2 { + t.Fatalf("len = %d, want 2 (response count, Python res.extend)", len(got)) + } + if got[0].Embedding[0] != 0 || got[1].Embedding[0] != 1 { + t.Errorf("got = %v, want [[0],[1]]", got) + } +} + +// TestAliyunEmbedNativeRejectsOutOfRangeIndex pins Python's IndexError: a +// text_index past the returned chunk is an error. +func TestAliyunEmbedNativeRejectsOutOfRangeIndex(t *testing.T) { + withSSRFBypass(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"output":{"embeddings":[` + + `{"text_index":5,"embedding":[5]}` + + `]},"usage":{"total_tokens":1}}`)) + })) + defer srv.Close() + + m := NewAliyunModel(map[string]string{"default": srv.URL}, URLSuffix{Embedding: "embeddings"}) + apiKey := "test-key" + _, err := m.embedNative(t.Context(), srv.URL, "text-embedding-v4", + EmbedRequest{Texts: []string{"a", "b"}}, &APIConfig{ApiKey: &apiKey}, nil) + if err == nil || !strings.Contains(err.Error(), "out of range") { + t.Fatalf("err = %v, want out-of-range error", err) + } +} + +// TestAliyunEmbedNativeRejectsMissingTextIndexKey pins Python's KeyError on +// e["text_index"]: an item without the key is an error, not a silent index 0. +func TestAliyunEmbedNativeRejectsMissingTextIndexKey(t *testing.T) { + withSSRFBypass(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"output":{"embeddings":[` + + `{"embedding":[1]}` + + `]},"usage":{"total_tokens":1}}`)) + })) + defer srv.Close() + + m := NewAliyunModel(map[string]string{"default": srv.URL}, URLSuffix{Embedding: "embeddings"}) + apiKey := "test-key" + _, err := m.embedNative(t.Context(), srv.URL, "text-embedding-v4", + EmbedRequest{Texts: []string{"a"}}, &APIConfig{ApiKey: &apiKey}, nil) + if err == nil || !strings.Contains(err.Error(), "text_index") { + t.Fatalf("err = %v, want missing-text_index error", err) + } +} + +// TestAliyunEmbedNativeNegativeIndexCountsFromEnd pins Python list-assignment +// semantics: a negative text_index indexes from the END of the chunk, so +// embds[-1] overwrites the last slot. +func TestAliyunEmbedNativeNegativeIndexCountsFromEnd(t *testing.T) { + withSSRFBypass(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"output":{"embeddings":[` + + `{"text_index":-1,"embedding":[7]},` + + `{"text_index":0,"embedding":[0]},` + + `{"text_index":1,"embedding":[1]}` + + `]},"usage":{"total_tokens":1}}`)) + })) + defer srv.Close() + + m := NewAliyunModel(map[string]string{"default": srv.URL}, URLSuffix{Embedding: "embeddings"}) + apiKey := "test-key" + got, err := m.embedNative(t.Context(), srv.URL, "text-embedding-v4", + EmbedRequest{Texts: []string{"a", "b", "c"}}, &APIConfig{ApiKey: &apiKey}, nil) + if err != nil { + t.Fatalf("embedNative: %v", err) + } + if len(got) != 3 { + t.Fatalf("len = %d, want 3", len(got)) + } + // embds[-1] = [7] lands in the last slot: [[0],[1],[7]]. + want := []float64{0, 1, 7} + for i, w := range want { + if len(got[i].Embedding) != 1 || got[i].Embedding[0] != w { + t.Errorf("got[%d] = %v, want [%v]", i, got[i].Embedding, w) + } + } +} + +// TestAliyunEmbedNativeRejectsTooNegativeIndex pins that an index below +// -len(chunk) raises, exactly like Python's IndexError. +func TestAliyunEmbedNativeRejectsTooNegativeIndex(t *testing.T) { + withSSRFBypass(t) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"output":{"embeddings":[` + + `{"text_index":-5,"embedding":[5]}` + + `]},"usage":{"total_tokens":1}}`)) + })) + defer srv.Close() + + m := NewAliyunModel(map[string]string{"default": srv.URL}, URLSuffix{Embedding: "embeddings"}) + apiKey := "test-key" + _, err := m.embedNative(t.Context(), srv.URL, "text-embedding-v4", + EmbedRequest{Texts: []string{"a", "b"}}, &APIConfig{ApiKey: &apiKey}, nil) + if err == nil || !strings.Contains(err.Error(), "out of range") { + t.Fatalf("err = %v, want out-of-range error", err) + } +} diff --git a/internal/entity/models/chat_tools.go b/internal/entity/models/chat_tools.go index 4149787827c..c3ea0b1ddc4 100644 --- a/internal/entity/models/chat_tools.go +++ b/internal/entity/models/chat_tools.go @@ -162,7 +162,10 @@ func runToolLoop(ctx context.Context, cm *ChatModel, history []Message, toolsLis var toolAnswer string history, toolAnswer, hit = appendToolResults(history, resp.ToolCalls, cm.ToolConfig.ToolCallSession, terminalSet(cm)) if hit { - addRoundUsage(resp) + // This round's usage was already folded in by addRoundUsage above + // (it accumulates into aggUsage and forwards a per-round delta to the + // run-usage sink, which ADDS): calling it again here would count the + // round twice in both totalTokens and the recorded run usage. return toolAnswer, totalTokens, nil } // history now carries this round's tool results; continue to the next round. diff --git a/internal/entity/models/chat_tools_test.go b/internal/entity/models/chat_tools_test.go index 4cb98e8ffbd..beaeb57efe0 100644 --- a/internal/entity/models/chat_tools_test.go +++ b/internal/entity/models/chat_tools_test.go @@ -16,7 +16,12 @@ package models -import "testing" +import ( + "context" + "testing" + + "ragflow/internal/tokenizer" +) // stubSession returns a canned result per tool name. type stubSession struct { @@ -170,3 +175,40 @@ func TestSendTerminalEmptyAnswerIsSilent(t *testing.T) { t.Fatalf("streamed %v, want nothing for an empty terminal answer", got) } } + +// TestChatWithToolsCountsTerminalRoundUsageOnce pins that a terminal-tool round +// contributes its tokens exactly once, in both the returned total and the +// run-usage sink (whose Add accumulates): runToolLoop folds the round in before +// the short-circuit decides. +func TestChatWithToolsCountsTerminalRoundUsageOnce(t *testing.T) { + const ( + answer = "[SUMMARY]" + total = 15 + ) + driver := &captureToolDriver{resp: &ChatResponse{ + ToolCalls: []map[string]interface{}{toolCallMsg("call-1", "summarize_document", `{"doc_id":"abc"}`)}, + Usage: &TokenUsage{PromptTokens: 10, CompletionTokens: 5, TotalTokens: total}, + }} + modelName, apiKey := "m", "k" + cm := NewChatModel(driver, &modelName, &APIConfig{ApiKey: &apiKey}) + cm.ToolConfig = &ToolConfig{ + Tools: `[{"type":"function","function":{"name":"summarize_document"}}]`, + ToolCallSession: &stubSession{results: map[string]string{"summarize_document": answer}}, + TerminalTools: map[string]struct{}{"summarize_document": {}}, + } + + ctx := tokenizer.WithRunUsage(context.Background()) + got, tokens, err := cm.ChatWithTools(ctx, "", []Message{{Role: "user", Content: "q"}}, &ChatConfig{}) + if err != nil { + t.Fatalf("ChatWithTools: %v", err) + } + if got != answer { + t.Fatalf("answer = %q, want the terminal result %q", got, answer) + } + if tokens != total { + t.Errorf("totalTokens = %d, want %d (the terminal round must be counted once)", tokens, total) + } + if _, _, runTotal, calls := tokenizer.GetRunUsage(ctx).Snapshot(); runTotal != total || calls != 1 { + t.Errorf("run usage total=%d calls=%d, want total=%d calls=1", runTotal, calls, total) + } +} diff --git a/internal/entity/models/llm.go b/internal/entity/models/llm.go index 16e3e50e33d..7ec073e960c 100644 --- a/internal/entity/models/llm.go +++ b/internal/entity/models/llm.go @@ -262,8 +262,6 @@ func (m *EinoChatModel) chatConfigForGenerate() (*ChatConfig, error) { choice = "required" break } - //if m.toolChoice != nil { - // choice = *m.toolChoice } cfg.ToolChoice = &choice for _, tool := range m.tools { @@ -275,9 +273,36 @@ func (m *EinoChatModel) chatConfigForGenerate() (*ChatConfig, error) { break } } + // An explicit WithToolChoice overrides both defaults above; the setter + // documents that the choice reaches the driver through this config. A + // keyword choice leaves ToolChoiceValue as an untyped nil: the driver only + // falls back to the plain string when the field is nil (base_model.go:565), + // and a typed-nil map would be sent as `"tool_choice": null`. + if m.toolChoice != nil && *m.toolChoice != "" { + cfg.ToolChoice = m.toolChoice + cfg.ToolChoiceValue = nil + if body := toolChoiceBody(*m.toolChoice); body != nil { + cfg.ToolChoiceValue = body + } + } return cfg, nil } +// toolChoiceBody returns the OpenAI tool_choice OBJECT form for a choice naming +// a specific tool, and nil for the keyword forms ("auto"/"none"/"required"), +// which travel as the plain ToolChoice string (base_model.go:561-568 prefers +// this value whenever it is set). +func toolChoiceBody(choice string) map[string]any { + switch choice { + case "auto", "none", "required": + return nil + } + return map[string]any{ + "type": "function", + "function": map[string]any{"name": choice}, + } +} + func openAIToolsFromEino(infos []*schema.ToolInfo) ([]map[string]any, error) { tools := make([]map[string]any, 0, len(infos)) for _, info := range infos { diff --git a/internal/entity/models/llm_test.go b/internal/entity/models/llm_test.go index a3a150b33bc..7200cb32c26 100644 --- a/internal/entity/models/llm_test.go +++ b/internal/entity/models/llm_test.go @@ -5,6 +5,7 @@ import ( "errors" "io" "ragflow/internal/common" + "reflect" "testing" "github.com/cloudwego/eino/schema" @@ -50,6 +51,85 @@ func TestEinoChatModelAllowsFinalAnswerAfterToolResult(t *testing.T) { } } +// TestEinoChatModelAppliesExplicitToolChoice pins that WithToolChoice actually +// reaches the driver's configuration (its doc promises exactly that): a keyword +// choice travels as the plain string with no object value, a named tool travels +// in the OpenAI object form, and either overrides the execute_code default. +func TestEinoChatModelAppliesExplicitToolChoice(t *testing.T) { + cases := []struct { + name string + tools []*schema.ToolInfo + choice string + wantChoice string + wantValue map[string]any // nil for the keyword forms + }{ + { + name: "keyword none overrides the execute_code default", + tools: []*schema.ToolInfo{{Name: "execute_code"}}, + choice: "none", + wantChoice: "none", + }, + { + name: "explicit required without execute_code", + tools: []*schema.ToolInfo{{Name: "rag"}}, + choice: "required", + wantChoice: "required", + }, + { + name: "named tool uses the object form", + tools: []*schema.ToolInfo{{Name: "rag"}, {Name: "summarize_document"}}, + choice: "summarize_document", + wantChoice: "summarize_document", + wantValue: map[string]any{ + "type": "function", + "function": map[string]any{"name": "summarize_document"}, + }, + }, + { + name: "no explicit choice keeps the execute_code default", + tools: []*schema.ToolInfo{{Name: "execute_code"}}, + wantChoice: "required", + wantValue: map[string]any{ + "type": "function", + "function": map[string]any{"name": "execute_code"}, + }, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + modelName := "chat" + model := NewEinoChatModel(NewChatModel(&captureToolDriver{}, &modelName, &APIConfig{}), nil) + bound, err := model.WithTools(tc.tools) + if err != nil { + t.Fatalf("WithTools: %v", err) + } + wrapper := bound.(*EinoChatModel) + if tc.choice != "" { + wrapper = wrapper.WithToolChoice(tc.choice) + } + cfg, err := wrapper.chatConfigForGenerate() + if err != nil { + t.Fatalf("chatConfigForGenerate: %v", err) + } + if cfg.ToolChoice == nil { + t.Fatalf("ToolChoice = nil, want %q", tc.wantChoice) + } + if *cfg.ToolChoice != tc.wantChoice { + t.Fatalf("ToolChoice = %q, want %q", *cfg.ToolChoice, tc.wantChoice) + } + if tc.wantValue == nil { + if cfg.ToolChoiceValue != nil { + t.Errorf("ToolChoiceValue = %#v, want nil for a keyword choice", cfg.ToolChoiceValue) + } + return + } + if got, ok := cfg.ToolChoiceValue.(map[string]any); !ok || !reflect.DeepEqual(got, tc.wantValue) { + t.Errorf("ToolChoiceValue = %#v, want %#v", cfg.ToolChoiceValue, tc.wantValue) + } + }) + } +} + func TestEinoChatModelStreamFiltersDoneSentinel(t *testing.T) { modelName := "chat" driver := &streamSentinelDriver{captureToolDriver: &captureToolDriver{}} diff --git a/internal/ingestion/component/chunker/title_cap.go b/internal/ingestion/component/chunker/title_cap.go index a3da43b66bb..b049c661608 100644 --- a/internal/ingestion/component/chunker/title_cap.go +++ b/internal/ingestion/component/chunker/title_cap.go @@ -42,9 +42,11 @@ var ( trimToTokenLimit = realTrimToTokenLimit ) -// titleTokenCount counts tokens for text. numTokensFromString returns 0 when -// the encoder is unavailable; in that case fall back to the rune count so the -// cap is still enforced (mirrors Python #18455's character-count fallback). +// titleTokenCount counts tokens for text. tokenizer.NumTokensFromString now +// PANICS when the encoder is unavailable (mirroring Python's raise), so a 0 here +// can only come from the counter itself (empty input, or the stubbed counter the +// tests install); fall back to the rune count so the cap is still enforced +// (mirrors Python #18455's character-count fallback). func titleTokenCount(text string) int { if text == "" { return 0 diff --git a/internal/rag/advanced_rag/agentic_rag.go b/internal/rag/advanced_rag/agentic_rag.go index 35c8673f31d..3e8cb71b2b5 100644 --- a/internal/rag/advanced_rag/agentic_rag.go +++ b/internal/rag/advanced_rag/agentic_rag.go @@ -854,7 +854,7 @@ type RAGCache struct { mu sync.Mutex entries map[string]ragCacheEntry lastVerdict string - // ConsecutiveUnanswerable mirrors Python RAGTools._consecutive_unanswerable + // consecutiveUnanswerable mirrors Python RAGTools._consecutive_unanswerable // (agentic_rag.py:818): how many consecutive rag() calls ended without a // satisfying verdict. After two in a row, RAGTools.rag appends a // "[Research status] … STOP calling rag again" note to the answer so the @@ -862,7 +862,36 @@ type RAGCache struct { // (rebuilt per turn), so it counts consecutive insufficient rounds within a // single request; it is not persisted across turns unless a caller injects a // long-lived *RAGCache via RAGTools.Cache. - ConsecutiveUnanswerable int + // + // Private and guarded by mu: a turn's concurrent rag() calls share ONE + // *RAGCache (Rag builds/stores it on deps.Cache before the outer react + // loop), so an unsynchronized counter would race. + consecutiveUnanswerable int +} + +// NoteUnanswerable records one research round's verdict on the shared cache. +func (c *RAGCache) NoteUnanswerable(verdict string) { + if c == nil { + return + } + c.mu.Lock() + defer c.mu.Unlock() + if verdict == VerdictSufficient { + c.consecutiveUnanswerable = 0 + } else { + c.consecutiveUnanswerable++ + } +} + +// ConsecutiveUnanswerable reports how many consecutive rag() rounds ended +// without a satisfying verdict. +func (c *RAGCache) ConsecutiveUnanswerable() int { + if c == nil { + return 0 + } + c.mu.Lock() + defer c.mu.Unlock() + return c.consecutiveUnanswerable } type ragCacheEntry struct { @@ -930,7 +959,7 @@ func researchStatusTrailer(cache *RAGCache, resp *RunResponse) string { if resp.Verdict != VerdictInsufficient || resp.SCAFeedback == "" || resp.Answer == "" { return "" } - if cache != nil && cache.ConsecutiveUnanswerable >= 2 { + if cache != nil && cache.ConsecutiveUnanswerable() >= 2 { return " STOP calling rag again: the same gaps remain." } return " If these gaps are material, call rag again with a question focused on them." @@ -1655,6 +1684,9 @@ func runOuterReact(ctx context.Context, deps RAGTools, req harness.RunRequest, l composeFinalAnswer(ctx, deps, req, p.kb, p.resp, logger) return p.resp } + // The fold returned the LOWEST-INDEX terminal rag call's answer: keep that + // call's evidence so the answer's [ID:n] markers line up with the chunks. + session.selectEvidence(answer) p.resp.Answer = answer p.resp.Chunks = p.kb.Chunks p.resp.DocAggs = p.kb.DocAggs @@ -1718,6 +1750,9 @@ func runOuterReactStream(ctx context.Context, deps RAGTools, req harness.RunRequ if p.resp.Answer == "" && !mux.terminalFired { p.resp.Answer = strings.TrimSpace(mux.outerText.String()) } + // Keep only the evidence of the call that owns the answer (selectEvidence + // no-ops when the answer came from the outer model instead of a rag call). + session.selectEvidence(p.resp.Answer) p.resp.Chunks = p.kb.Chunks p.resp.DocAggs = p.kb.DocAggs p.resp.EmptyResult = len(p.kb.Chunks) == 0 @@ -1737,38 +1772,67 @@ type outerReactSession struct { // mux is set only on the streaming path; it merges the inner run's output // into the caller's sink. mux *outerStreamMux + // mu guards the per-call result merge (publish) and the recorded per-call + // outcomes (calls): appendToolResults invokes this session's tool calls + // concurrently. + mu sync.Mutex + // calls records each rag call's answer + evidence pool in completion order so + // selectEvidence can match the terminal fold's winning answer back to its own + // pool. Guarded by mu. + calls []ragCallResult } // ToolCall routes the two outer tools to their Go implementations. +// +// A round's tool calls arrive CONCURRENTLY — models.appendToolResults runs one +// goroutine per call — exactly as Python gathers them (asyncio.gather over the +// round's tool_calls, chat_model.py:670/:2555). Each rag call therefore runs on +// its own request/evidence/response and publishes the outcome under mu; sharing +// the session's would let two calls mix questions, evidence and answers. func (s *outerReactSession) ToolCall(name string, arguments map[string]interface{}) (string, error) { switch name { case "rag": + // Work on a COPY of the request: this call must not rewrite the + // session's question/images, which a concurrent call is reading. + req := s.req if q, ok := arguments["question"].(string); ok && q != "" { - s.req.Question = q + req.Question = q } // Python's inner _compose_answer_from_evidence is text-only: the outer // model already saw the images via multimodal history, and the rephrased // question carries no images. Drop the original images so the inner // compose model (ComposeAnswerWith via composeFinalAnswer) does not // receive them — matching Python's inner compose. - s.req.Images = nil + req.Images = nil + + // Per-call evidence, response and the projections that point at them: + // Python gives every rag() invocation its own graph state and shares only + // the tools object (agentic_rag.py:877 run_agentic_rag(self, messages)). + kb := &harness.Kbinfos{} + resp := &RunResponse{Mode: s.spec, Kbinfos: kb} + sd := s.sd + sd.KB = kb + inner := s.deps + inner.KB = kb + if s.mux != nil { // Streaming: s.deps already routes the inner research log and the // composed answer into the caller's sink, so return "" — the // terminal short-circuit stops the loop and sendTerminal stays // silent, so the answer is not streamed twice. s.mux.markTerminal() - RunAgenticRAG(s.ctx, s.deps, s.req, s.sd, s.kb, s.resp, s.logger, s.spec) - composeFinalAnswer(s.ctx, s.deps, s.req, s.kb, s.resp, s.logger) + RunAgenticRAG(s.ctx, inner, req, sd, kb, resp, s.logger, s.spec) + composeFinalAnswer(s.ctx, inner, req, kb, resp, s.logger) + s.publish(resp, kb) return "", nil } // Non-streaming: disable the sink so the answer is not emitted twice, - // and hand it back for the terminal short-circuit to return as final. - inner := s.deps + // and hand this call's own answer back for the terminal short-circuit. inner.AnswerSink = nil - RunAgenticRAG(s.ctx, inner, s.req, s.sd, s.kb, s.resp, s.logger, s.spec) - composeFinalAnswer(s.ctx, inner, s.req, s.kb, s.resp, s.logger) - return s.resp.Answer, nil + RunAgenticRAG(s.ctx, inner, req, sd, kb, resp, s.logger, s.spec) + composeFinalAnswer(s.ctx, inner, req, kb, resp, s.logger) + s.publish(resp, kb) + return resp.Answer, nil case "summarize_document": docID, _ := arguments["doc_id"].(string) if docID == "" { @@ -1783,6 +1847,80 @@ func (s *outerReactSession) ToolCall(name string, arguments map[string]interface return fmt.Sprintf("unknown tool %q", name), nil } +// publish merges one rag call's outcome into the session state. The inner run +// used to write that state directly, before each call got its own; the merge +// reproduces what a single call contributed, and for concurrent calls it keeps +// the FIRST non-empty answer/verdict (appendToolResults folds the first terminal +// hit in call order) while the evidence is unioned, so the caller still sees the +// chunks the answer was composed from. +func (s *outerReactSession) publish(call *RunResponse, kb *harness.Kbinfos) { + s.mu.Lock() + defer s.mu.Unlock() + // Remember this call's own answer + evidence so selectEvidence can restore + // the pool the winning answer was composed from. + s.calls = append(s.calls, ragCallResult{answer: call.Answer, kb: kb}) + if s.resp.Answer == "" { + s.resp.Answer = call.Answer + } + if s.resp.Verdict == "" { + s.resp.Verdict = call.Verdict + } + if s.resp.SCAFeedback == "" { + s.resp.SCAFeedback = call.SCAFeedback + } + if s.resp.CollectedAnswer == "" { + s.resp.CollectedAnswer = call.CollectedAnswer + } + if len(s.resp.Slots) == 0 { + s.resp.Slots = call.Slots + } + s.resp.Partial = s.resp.Partial || call.Partial + s.kb.Chunks = append(s.kb.Chunks, kb.Chunks...) + s.kb.DocAggs = append(s.kb.DocAggs, kb.DocAggs...) + s.kb.Memory = append(s.kb.Memory, kb.Memory...) + if s.kb.PreSummary == "" { + s.kb.PreSummary = kb.PreSummary + } +} + +// ragCallResult is one rag call's outcome: the answer it composed and the +// evidence pool that produced it. +type ragCallResult struct { + answer string + kb *harness.Kbinfos +} + +// selectEvidence leaves only the evidence of the rag call whose answer the +// terminal fold returned. The fold picks the LOWEST-INDEX terminal call while +// publish sees completion order, so the union alone can leave that answer's +// [ID:n] markers pointing into another call's chunks — the answer and the +// reference list would disagree. No-op when no recorded call matches (the +// terminal tool was summarize_document, or the answer did not come from a rag +// call), in which case the union stands. +// +// Matching is by exact answer text, so two calls that produce byte-identical +// answers are indistinguishable and the FIRST recorded (first to finish) one +// wins. That collision is accepted: plumbing the tool-call index through +// ToolCallSession is not worth it for a case that cannot happen with distinct +// questions. +func (s *outerReactSession) selectEvidence(answer string) { + if answer == "" { + return + } + s.mu.Lock() + defer s.mu.Unlock() + for _, r := range s.calls { + if r.answer != answer { + continue + } + s.kb.Chunks = append([]map[string]any(nil), r.kb.Chunks...) + s.kb.DocAggs = append([]map[string]any(nil), r.kb.DocAggs...) + s.kb.Memory = append([]map[string]any(nil), r.kb.Memory...) + s.kb.PreSummary = r.kb.PreSummary + return + } +} + // runDirect is the low/naive path: one hybrid search, no tool loop. // // It is the ONE Go implementation of Python orchestrator/direct.py::direct_search diff --git a/internal/rag/advanced_rag/agentic_rag_graph.go b/internal/rag/advanced_rag/agentic_rag_graph.go index 5f117ae66a7..fa6ae929ae6 100644 --- a/internal/rag/advanced_rag/agentic_rag_graph.go +++ b/internal/rag/advanced_rag/agentic_rag_graph.go @@ -50,6 +50,7 @@ import ( "sync" "time" "unicode" + "unicode/utf8" "github.com/cespare/xxhash/v2" "github.com/cloudwego/eino/compose" @@ -811,7 +812,9 @@ func fanoutLooksLikeQuery(line string, loose bool) bool { return false } } - if len(s) > fanoutMaxChars { + // Python len() counts characters, not bytes; a byte-based cap would reject a + // legitimate CJK fan-out well below the 160-character limit. + if utf8.RuneCountInString(s) > fanoutMaxChars { return false } words := len(strings.Fields(s)) @@ -821,6 +824,17 @@ func fanoutLooksLikeQuery(line string, loose bool) bool { return words <= fanoutMaxWords } +// fanoutLineBreak reports whether r is a Python str.splitlines() line boundary. +// Splitting on "\n" alone misses a lone "\r" and the other Unicode line breaks a +// model could emit, so the loose path would fuse several fan-out lines into one. +func fanoutLineBreak(r rune) bool { + switch r { + case '\n', '\r', '\v', '\f', 0x1c, 0x1d, 0x1e, 0x85, 0x2028, 0x2029: + return true + } + return false +} + // parseFanouts mirrors Python _parse_fanouts: extract fan-outs from a // model reply, validating every entry's shape. func parseFanouts(text string) []string { @@ -837,11 +851,15 @@ func parseFanouts(text string) []string { // look like a search query are kept — answer sentences and source // lists are dropped. loose = true - for _, ln := range strings.Split(text, "\n") { - ln = strings.TrimSpace(strings.TrimLeft(ln, "-•0123456789. ")) - if ln != "" { - raw = append(raw, ln) + // Python `text.splitlines()`: split on every line boundary, not just "\n". + for _, ln := range strings.FieldsFunc(text, fanoutLineBreak) { + if strings.TrimSpace(ln) == "" { + continue } + // Python `ln.strip("-•0123456789. ").strip()` strips the bullet / + // numbering cutset from BOTH ends, then trims whitespace, so a + // trailing period/digit never leaks into the retrieval query. + raw = append(raw, strings.TrimSpace(strings.Trim(ln, "-•0123456789. "))) } } kept := make([]string, 0, len(raw)) @@ -1408,7 +1426,6 @@ func scaNode(ctx context.Context, deps RAGTools, st *AgenticState, logger *log.L // when the SCA produced no structured gaps. func unresolvedClueGaps(st *AgenticState) []orchestrator.MissingPiece { var gaps []orchestrator.MissingPiece - seen := map[string]bool{} for _, us := range st.UnresolvedSlots { clues, ok := us["question_clues"].([]string) if !ok { @@ -1419,10 +1436,9 @@ func unresolvedClueGaps(st *AgenticState) []orchestrator.MissingPiece { break } qc = strings.TrimSpace(qc) - if qc == "" || seen[qc] { + if qc == "" { continue } - seen[qc] = true gaps = append(gaps, orchestrator.MissingPiece{What: qc, SearchHint: qc}) } } @@ -1977,6 +1993,13 @@ func routeSCA(st *AgenticState, enableSCA bool, scaMaxRounds int) agenticNode { if st.NoProgress { return nodeFormalizeAnswer } + // Evidence pool saturated at the SCA view cap: any further chunk lands + // beyond what the SCA can read, so another search round cannot flip the + // sufficiency verdict. Short-circuit straight to finalize. + if st.KB != nil && len(st.KB.Chunks) >= SCAViewCap { + _LOG.Printf("[SCA] evidence pool FULL (%d chunks >= SCA view cap %d); early-stopping to finalize_answer.", len(st.KB.Chunks), SCAViewCap) + return nodeFormalizeAnswer + } if !enableSCA { // medium: single research pass — the SCA verdict is informational only. return nodeFormalizeAnswer @@ -2224,7 +2247,7 @@ func RunSlotResearchPass(ctx context.Context, deps harness.SessionDeps, question } // Shared across sessions so duplicate retrievals are served from cache. - sharedToolCache := map[string]harness.ToolOutcome{} + sharedToolCache := harness.NewToolCache() var sharedSearchQueries []string sem := make(chan struct{}, slotSessionConcurrency) @@ -3032,15 +3055,10 @@ func NewAgenticLoop() AgenticLoop { // accumulates across the outer react loop's multiple rag() calls within a single // turn — which is exactly why Rag() must build deps.Cache before branching into // the outer loop (otherwise the "STOP calling rag again" guard would never fire). +// Those calls run concurrently, so the update itself is RAGCache.NoteUnanswerable +// (locked); this wrapper only keeps the call site's name. func recordConsecutiveUnanswerable(cache *RAGCache, verdict string) { - if cache == nil { - return - } - if verdict == VerdictSufficient { - cache.ConsecutiveUnanswerable = 0 - } else { - cache.ConsecutiveUnanswerable++ - } + cache.NoteUnanswerable(verdict) } // graphRecursionLimit mirrors Python run_agentic_rag — the graph aborts diff --git a/internal/rag/advanced_rag/agentic_rag_graph_test.go b/internal/rag/advanced_rag/agentic_rag_graph_test.go index 1646037bd2c..c07ac3e8a44 100644 --- a/internal/rag/advanced_rag/agentic_rag_graph_test.go +++ b/internal/rag/advanced_rag/agentic_rag_graph_test.go @@ -167,6 +167,27 @@ func TestRouteSCADisabledSCAClosesOut(t *testing.T) { } } +// TestRouteSCAFullPoolShortCircuits pins the PR: a pool at/over the SCA view cap +// cannot flip the verdict, so routeSCA finalizes instead of researching — even +// when the verdict is insufficient and headroom remains. +func TestRouteSCAFullPoolShortCircuits(t *testing.T) { + st := &AgenticState{ + Verdict: VerdictInsufficient, + MaxLoops: 3, + SearchRounds: 0, + KB: &harness.Kbinfos{Chunks: make([]map[string]any, SCAViewCap)}, + } + st.Deadline = time.Now().Add(120 * time.Second) + if n := routeSCA(st, true, 3); n != nodeFormalizeAnswer { + t.Fatalf("full pool: expected formalize, got %v", n) + } + // One chunk below the cap still takes the normal research path. + st.KB.Chunks = make([]map[string]any, SCAViewCap-1) + if n := routeSCA(st, true, 3); n != nodeQueryRewrite { + t.Fatalf("below cap: expected rewrite, got %v", n) + } +} + func TestRouteSCAInsufficientStartsRewrite(t *testing.T) { // Sufficient verdict closes out. st := &AgenticState{Verdict: VerdictSufficient, MaxLoops: 3} @@ -273,10 +294,12 @@ func TestExpandFanoutsFallbackOnBadJSON(t *testing.T) { mdl := &scriptedModel{} mdl.push("I cannot break this down.") got := ExpandFanouts(context.Background(), RAGTools{Model: mdl}, "single question") - // Bad JSON: the loop falls back to line-splitting the model's reply, which - // yields the reply itself (single line), not the raw question. - if len(got) != 1 || got[0] != "I cannot break this down." { - t.Fatalf("expected line-split fallback, got %v", got) + // Bad JSON: the model answered in prose, so the loop line-splits the reply + // (yielding the reply itself, not the raw question). The loose path strips the + // Python `strip("-•0123456789. ")` cutset from both ends, so the trailing + // period is dropped exactly as `_parse_fanouts` would. + if len(got) != 1 || got[0] != "I cannot break this down" { + t.Fatalf("expected line-split fallback without the trailing period, got %v", got) } } @@ -336,6 +359,51 @@ func TestFanoutLooksLikeQueryBounds(t *testing.T) { } } +// TestFanoutLooksLikeQueryCountsRunes pins Python len(): the 160-char cap counts +// code points, so a CJK fan-out at the limit must survive even though it exceeds +// 160 BYTES, and one over the limit must still be rejected. +func TestFanoutLooksLikeQueryCountsRunes(t *testing.T) { + atLimit := strings.Repeat("中", fanoutMaxChars) // 160 chars / 480 bytes + if !fanoutLooksLikeQuery(atLimit, false) { + t.Errorf("a %d-character fan-out must pass: the cap counts characters, not bytes", fanoutMaxChars) + } + if fanoutLooksLikeQuery(atLimit+"中", false) { + t.Errorf("a %d-character fan-out must be rejected", fanoutMaxChars+1) + } +} + +// TestParseFanoutsLooseStripsBothEnds pins Python `ln.strip("-•0123456789. ")`: +// the bullet/numbering cutset is stripped from BOTH ends, so a trailing period is +// not carried into the retrieval query (the leading "1." already was not). +func TestParseFanoutsLooseStripsBothEnds(t *testing.T) { + got := parseFanouts("1. who opened the library.\n- when did it open?") + want := []string{"who opened the library", "when did it open?"} + if len(got) != len(want) { + t.Fatalf("parseFanouts = %q, want %q", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("parseFanouts[%d] = %q, want %q", i, got[i], want[i]) + } + } +} + +// TestParseFanoutsSplitsOnAllLineBreaks pins Python `text.splitlines()`: a +// carry-return separated reply yields one fan-out per line, not a single fused +// blob (splitting on "\n" alone would keep the lone "\r" inline). +func TestParseFanoutsSplitsOnAllLineBreaks(t *testing.T) { + got := parseFanouts("who opened it\rwhen did it open?") + want := []string{"who opened it", "when did it open?"} + if len(got) != len(want) { + t.Fatalf("parseFanouts = %q, want %q", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("parseFanouts[%d] = %q, want %q", i, got[i], want[i]) + } + } +} + // TestRenderSlotDraftMatchesPythonFormat pins Python _render_slot_draft // (agentic_rag_graph.py:1278-1326) exactly: the collected answer leads with its // evidence metadata, a resolved slot carries strength + terminal + evidence ids + @@ -610,7 +678,13 @@ type channelRetriever struct { } func (r *channelRetriever) Retrieve(_ context.Context, req harness.RetrieveRequest) ([]map[string]any, error) { - r.weights = append(r.weights, req.KeywordsSimilarityWeight) + // Each leg names its weight explicitly; nil (the control was not supplied) + // is recorded as -1 so the assertions below catch a leg that drops it. + weight := -1.0 + if req.KeywordsSimilarityWeight != nil { + weight = *req.KeywordsSimilarityWeight + } + r.weights = append(r.weights, weight) r.topN = append(r.topN, req.TopN) r.queries = append(r.queries, req.Query) return nil, nil @@ -1232,15 +1306,18 @@ func TestQueryRewriteFoldsUnresolvedCluesWhenNoGaps(t *testing.T) { func TestUnresolvedClueGapsCapsAtTwoClues(t *testing.T) { st := &AgenticState{UnresolvedSlots: []map[string]any{ {"question_clues": []string{"a", "b", "c"}}, - {"question_clues": []string{"a", "d"}}, // duplicate "a" is dropped + {"question_clues": []string{"a", "d"}}, // Python appends without dedupe }} gaps := unresolvedClueGaps(st) - if len(gaps) != 3 { - t.Fatalf("gaps = %d, want 3 (2 from the first slot + 1 new from the second)", len(gaps)) + if len(gaps) != 4 { + t.Fatalf("gaps = %d, want 4 (first two clues of each slot, duplicates kept)", len(gaps)) } if gaps[0].What != "a" || gaps[0].SearchHint != "a" { t.Errorf("gaps[0] = %+v, want what=hint=\"a\"", gaps[0]) } + if gaps[2].What != "a" || gaps[3].What != "d" { + t.Errorf("gaps = %+v, want the second slot's clues a,d appended verbatim", gaps) + } } // TestBuildSCAClaimsFallsBackToEvidenceOnlyClaim pins Python :1072-1073: with no @@ -2490,25 +2567,25 @@ func TestRecordConsecutiveUnanswerableAcrossOuterRagCalls(t *testing.T) { // First outer rag() call — unsatisfying verdict bumps the counter to 1. recordConsecutiveUnanswerable(cache, VerdictInsufficient) - if cache.ConsecutiveUnanswerable != 1 { + if cache.ConsecutiveUnanswerable() != 1 { t.Fatalf("after 1st outer rag() call: ConsecutiveUnanswerable = %d, want 1", - cache.ConsecutiveUnanswerable) + cache.ConsecutiveUnanswerable()) } // Second outer rag() call — still unsatisfying: counter must reach 2 so the // STOP guard can fire (the state the pre-fix code could never reach on the // outer path, because deps.Cache was nil and the increment was skipped). recordConsecutiveUnanswerable(cache, VerdictInsufficient) - if cache.ConsecutiveUnanswerable != 2 { + if cache.ConsecutiveUnanswerable() != 2 { t.Fatalf("after 2nd outer rag() call: ConsecutiveUnanswerable = %d, want 2", - cache.ConsecutiveUnanswerable) + cache.ConsecutiveUnanswerable()) } // A satisfying verdict resets the streak, matching Python rag (:921-924). recordConsecutiveUnanswerable(cache, VerdictSufficient) - if cache.ConsecutiveUnanswerable != 0 { + if cache.ConsecutiveUnanswerable() != 0 { t.Fatalf("after a SUFFICIENT verdict: ConsecutiveUnanswerable = %d, want 0", - cache.ConsecutiveUnanswerable) + cache.ConsecutiveUnanswerable()) } } diff --git a/internal/rag/advanced_rag/agentic_rag_test.go b/internal/rag/advanced_rag/agentic_rag_test.go index 9fcfb409f5c..8fb771d8ae8 100644 --- a/internal/rag/advanced_rag/agentic_rag_test.go +++ b/internal/rag/advanced_rag/agentic_rag_test.go @@ -19,7 +19,11 @@ package advanced_rag import ( "context" "errors" + "fmt" + "io" + "log" "strings" + "sync" "testing" "github.com/cloudwego/eino/schema" @@ -284,7 +288,7 @@ func TestResolveEffectiveQuestionHandlesEmpty(t *testing.T) { // rag() calls. func TestResearchStatusTrailerStopsAfterTwoUnanswerable(t *testing.T) { cache := NewRAGCache() - cache.ConsecutiveUnanswerable = 2 + cache.consecutiveUnanswerable = 2 resp := &RunResponse{ Verdict: VerdictInsufficient, SCAFeedback: "evidence is not yet sufficient", @@ -305,7 +309,7 @@ func TestResearchStatusTrailerStopsAfterTwoUnanswerable(t *testing.T) { // re-ask rather than tell the agent to stop. func TestResearchStatusTrailerInvitesFocusedReaskBelowTwo(t *testing.T) { cache := NewRAGCache() - cache.ConsecutiveUnanswerable = 1 + cache.consecutiveUnanswerable = 1 resp := &RunResponse{ Verdict: VerdictInsufficient, SCAFeedback: "evidence is not yet sufficient", @@ -329,7 +333,7 @@ func TestResearchStatusTrailerInvitesFocusedReaskBelowTwo(t *testing.T) { // missing SCA feedback all yield "". func TestResearchStatusTrailerSkipsSufficientOrEmpty(t *testing.T) { cache := NewRAGCache() - cache.ConsecutiveUnanswerable = 2 + cache.consecutiveUnanswerable = 2 cases := []struct { name string @@ -501,3 +505,175 @@ func TestFitEvidenceTrimsOversizedEvidence(t *testing.T) { t.Fatal("evidence must not be trimmed to nothing") } } + +// TestOuterReactSessionPublishMergesPerCallResults pins the locked merge: a +// round's rag calls run concurrently, so each publishes its own evidence and +// answer and none may be lost. Run with -race. +func TestOuterReactSessionPublishMergesPerCallResults(t *testing.T) { + session := &outerReactSession{kb: &harness.Kbinfos{}, resp: &RunResponse{}} + const calls = 4 + + var wg sync.WaitGroup + for i := 0; i < calls; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + session.publish( + &RunResponse{Answer: fmt.Sprintf("answer-%d", i), Verdict: fmt.Sprintf("verdict-%d", i)}, + &harness.Kbinfos{ + Chunks: []map[string]any{{"chunk_id": fmt.Sprintf("c%d", i)}}, + DocAggs: []map[string]any{{"doc_id": fmt.Sprintf("d%d", i)}}, + Memory: []map[string]any{{"id": fmt.Sprintf("m%d", i)}}, + }) + }(i) + } + wg.Wait() + + if len(session.kb.Chunks) != calls || len(session.kb.DocAggs) != calls || len(session.kb.Memory) != calls { + t.Fatalf("merged evidence = %d chunks / %d doc_aggs / %d memory, want %d each", + len(session.kb.Chunks), len(session.kb.DocAggs), len(session.kb.Memory), calls) + } + seen := map[string]bool{} + for _, c := range session.kb.Chunks { + id, _ := c["chunk_id"].(string) + seen[id] = true + } + for i := 0; i < calls; i++ { + if !seen[fmt.Sprintf("c%d", i)] { + t.Errorf("merged chunks lost c%d: %v", i, seen) + } + } + if !strings.HasPrefix(session.resp.Answer, "answer-") { + t.Errorf("answer = %q, want one call's answer", session.resp.Answer) + } + if !strings.HasPrefix(session.resp.Verdict, "verdict-") { + t.Errorf("verdict = %q, want one call's verdict", session.resp.Verdict) + } +} + +// TestOuterReactSessionToolCallKeepsSharedRequestIntact pins the per-call +// isolation: models.appendToolResults runs a round's rag calls concurrently +// (chat_tools.go), so a call must apply its rewritten question and its cleared +// images to a COPY — never to the request a concurrent call is reading. +// Run with -race. +func TestOuterReactSessionToolCallKeepsSharedRequestIntact(t *testing.T) { + spec := harness.GetMode("naive") + session := &outerReactSession{ + ctx: context.Background(), + spec: spec, + kb: &harness.Kbinfos{}, + resp: &RunResponse{Mode: spec}, + logger: log.New(io.Discard, "", 0), + req: harness.RunRequest{ + Question: "original question", + Images: []string{"data:image/png;base64,AAAA"}, + }, + } + + var wg sync.WaitGroup + for _, q := range []string{"first question", "second question"} { + wg.Add(1) + go func(q string) { + defer wg.Done() + if _, err := session.ToolCall("rag", map[string]interface{}{"question": q}); err != nil { + t.Errorf("ToolCall(%q): %v", q, err) + } + }(q) + } + wg.Wait() + + if session.req.Question != "original question" { + t.Errorf("shared request question = %q, want it untouched (each call works on a copy)", session.req.Question) + } + if len(session.req.Images) != 1 { + t.Errorf("shared request images = %v, want them untouched", session.req.Images) + } +} + +// ragTestChunkIDs lists a chunk pool's ids in order. +func ragTestChunkIDs(chunks []map[string]any) []string { + out := make([]string, 0, len(chunks)) + for _, c := range chunks { + id, _ := c["chunk_id"].(string) + out = append(out, id) + } + return out +} + +// TestRAGCacheConsecutiveUnanswerableIsSerialized pins that the counter lives +// behind the cache's lock: a round's concurrent rag() calls bump the SAME shared +// cache, so an unsynchronized increment would race and lose updates. +// Run with -race. +func TestRAGCacheConsecutiveUnanswerableIsSerialized(t *testing.T) { + cache := NewRAGCache() + const calls = 8 + + var wg sync.WaitGroup + for i := 0; i < calls; i++ { + wg.Add(1) + go func() { + defer wg.Done() + cache.NoteUnanswerable(VerdictInsufficient) + }() + } + wg.Wait() + + if got := cache.ConsecutiveUnanswerable(); got != calls { + t.Errorf("ConsecutiveUnanswerable = %d, want %d (increments must not be lost)", got, calls) + } + cache.NoteUnanswerable(VerdictSufficient) + if got := cache.ConsecutiveUnanswerable(); got != 0 { + t.Errorf("after a SUFFICIENT verdict = %d, want 0", got) + } + if got := (*RAGCache)(nil).ConsecutiveUnanswerable(); got != 0 { + t.Errorf("nil cache = %d, want 0", got) + } + (*RAGCache)(nil).NoteUnanswerable(VerdictInsufficient) // must not panic +} + +// TestOuterReactSessionSelectsWinningCallEvidence pins the citation fix: the +// terminal fold returns the LOWEST-INDEX terminal rag call's answer while +// publish() records completion order, so the session must hand back THAT call's +// evidence — otherwise the answer's [ID:n] markers address another call's chunks. +func TestOuterReactSessionSelectsWinningCallEvidence(t *testing.T) { + session := &outerReactSession{kb: &harness.Kbinfos{}, resp: &RunResponse{}} + winner := &harness.Kbinfos{ + Chunks: []map[string]any{{"chunk_id": "w0"}, {"chunk_id": "w1"}}, + DocAggs: []map[string]any{{"doc_id": "dw"}}, + Memory: []map[string]any{{"id": "mw"}}, + PreSummary: "winner summary", + } + loser := &harness.Kbinfos{Chunks: []map[string]any{{"chunk_id": "l0"}}} + + // The losing call finishes FIRST, i.e. completion order ≠ index order. + session.publish(&RunResponse{Answer: "answer-loser"}, loser) + session.publish(&RunResponse{Answer: "answer-winner"}, winner) + + if got := ragTestChunkIDs(session.kb.Chunks); len(got) != 3 || got[0] != "l0" { + t.Fatalf("unselected union = %v, want the loser's chunk first (that is the misalignment)", got) + } + + session.selectEvidence("answer-winner") + + if got := ragTestChunkIDs(session.kb.Chunks); len(got) != 2 || got[0] != "w0" || got[1] != "w1" { + t.Errorf("chunks after selection = %v, want the winner's [w0 w1] in its own order", got) + } + if len(session.kb.DocAggs) != 1 || len(session.kb.Memory) != 1 || session.kb.PreSummary != "winner summary" { + t.Errorf("winner's evidence fields not restored: %+v", session.kb) + } +} + +// TestOuterReactSessionSelectEvidenceKeepsUnionWithoutAMatch keeps the fallback: +// an answer no rag call produced (the terminal tool was summarize_document, or +// the outer model answered itself) leaves the union in place. +func TestOuterReactSessionSelectEvidenceKeepsUnionWithoutAMatch(t *testing.T) { + session := &outerReactSession{kb: &harness.Kbinfos{}, resp: &RunResponse{}} + session.publish(&RunResponse{Answer: "answer-a"}, &harness.Kbinfos{Chunks: []map[string]any{{"chunk_id": "a0"}}}) + + session.selectEvidence("a summarize_document result") + session.selectEvidence("") + + if got := ragTestChunkIDs(session.kb.Chunks); len(got) != 1 || got[0] != "a0" { + t.Errorf("chunks = %v, want the union kept when no call matches", got) + } +} diff --git a/internal/rag/advanced_rag/harness/action_session.go b/internal/rag/advanced_rag/harness/action_session.go index 75260cd5176..dfac24ed503 100644 --- a/internal/rag/advanced_rag/harness/action_session.go +++ b/internal/rag/advanced_rag/harness/action_session.go @@ -925,10 +925,11 @@ var ( Type: "function", Function: ToolFunction{ Name: "retrieve", - Description: ("Keyword-first search of the fixed document corpus. Pass natural-" + - "language queries; returns SHORT snippets of the most relevant " + - "passages (exact-term matched where possible). Use multiple queries " + - "to cover different aspects. Supports 1-3 queries per call."), + Description: `WHEN TO CALL: Use when you know or suspect exact surface terms or keywords in the corpus (names, titles, codes, phrases). Best as the first recall pass; send 1-3 queries covering different facets.` + + `DO NOT CALL: When you already hold a doc_id and need to read it (use list_chunks); when the answer shares no surface words with any query (use search_chunks); for counting or enumerating a whole document.` + + `ARGUMENTS: query — array of 1-3 strings (natural-language queries). Note: doc_scope exists inside the executor but is NOT a declared parameter; do not pass it.` + + `OUTPUT: Short exact-term-matched snippets, each carrying its doc_id and chunk id. Status ok means new evidence entered the pool; redundant means everything was already there.` + + `IF IT FAILS: miss (empty payload) means this query matched nothing — rephrase or switch to search_chunks; do not conclude the corpus lacks the fact. redundant means stop re-searching and emit a state patch.`, Parameters: arrayParam("", 1, 3), }, } @@ -937,10 +938,11 @@ var ( Type: "function", Function: ToolFunction{ Name: "list_chunks", - Description: ("Deep-read the FULL text of one document by doc_id (returned in " + - "retrieve snippets). Use for enumeration / count / arithmetic answers " + - "when snippets are insufficient. Returns all chunks of the document " + - "in reading order. One doc_id per call."), + Description: `WHEN TO CALL: You need the FULL text of one document (enumeration, counts, arithmetic over many passages) and you already have its doc_id from a prior tool result.` + + `DO NOT CALL: When you only need a single passage (use search_chunks or retrieve first); when you have no doc_id yet (locate it via navigate_tree or search_chunks first).` + + `ARGUMENTS: doc_id — string, the document id seen in a retrieve / search_chunks / navigate result. ONLY doc_id is accepted; there is no chunk_ids argument, and the tool returns the whole document (capped at 30 chunks).` + + `OUTPUT: All chunks of the document in reading order. ok = new evidence; redundant = already in pool.` + + `IF IT FAILS: An unknown or blank doc_id yields an empty result (query-level miss, not a dataset fact) — pick a different doc_id or locate one first. Do not treat this as a reason to disable the tool.`, Parameters: map[string]any{ "type": "object", "properties": map[string]any{ @@ -958,18 +960,11 @@ var ( Type: "function", Function: ToolFunction{ Name: "search_chunks", - Description: ("SEMANTIC retrieval (hybrid vector+BM25) with COMPILED-STRUCTURE " + - "EXPANSION. Use as the PRIMARY recall tool when exact-term " + - "``retrieve`` returns nothing useful, or when the dataset is large and " + - "you are unsure which document holds the answer — the answer passage " + - "may share NO surface words with the query. " + - "Compiled expansion: automatically appends related chunks from the " + - "dataset's compiled structure (page index, tree/heading hierarchy, " + - "knowledge graph, wiki pages when present) so a semantic hit carries " + - "its structural neighbours (parent/child headings, sibling pages). " + - "If the dataset has NO compiled structure (incl. no wiki), expansion " + - "is a no-op — no error, just semantic hits. " + - "Returns snippet chunks ranked by relevance. 1-2 queries per call."), + Description: `WHEN TO CALL: Primary semantic recall. Use when exact retrieve returns nothing useful, when the corpus is large and you are unsure which document holds the answer, or when the answer passage shares no surface words with your query. Send 1-2 queries.` + + `DO NOT CALL: When you already have a doc_id and want to read that document (use list_chunks); when a single exact passage would be found faster by grep-style retrieve.` + + `ARGUMENTS: query — array of 1-2 strings. Compiled-structure expansion is automatic and a no-op on datasets without compiled structure, so no extra argument is needed.` + + `OUTPUT: Relevance-ranked snippet chunks, possibly with structural neighbours (parent/child headings, sibling pages) appended. ok = new evidence; redundant = already seen.` + + `IF IT FAILS: miss means this query matched nothing — change the angle or fall back to retrieve or navigate_tree. Re-issuing a near-duplicate query is skipped as redundant, so vary the query instead of paraphrasing it.`, Parameters: arrayParam("", 1, 2), }, } @@ -978,11 +973,11 @@ var ( Type: "function", Function: ToolFunction{ Name: "web_search", - Description: ("Search the open WEB. Use ONLY when the needed fact is world " + - "knowledge / recent event / not covered by the fixed corpus — e.g. " + - "a current event, a person's alive-now status, or a statistic newer " + - "than the corpus. If the fact plausibly lives in the documents, " + - "prefer corpus tools (retrieve/search_chunks) first. 1-2 queries per call."), + Description: `WHEN TO CALL: The needed fact is world knowledge, a recent event, or newer than the corpus (a current event, a person's alive-now status, a fresh statistic). This tool only appears when a web provider is configured.` + + `DO NOT CALL: When the fact plausibly lives in the fixed corpus — prefer retrieve or search_chunks first. For corpus-only questions this tool is unavailable.` + + `ARGUMENTS: query — array of 1-2 strings.` + + `OUTPUT: Web results shaped like corpus chunks, merged into the same evidence pool.` + + `IF IT FAILS: error (no provider) — it will not appear at all this session; if it does appear and fails, switch to corpus tools permanently and do not retry it.`, Parameters: arrayParam("", 1, 2), }, } @@ -997,23 +992,11 @@ var ( Type: "function", Function: ToolFunction{ Name: "navigate_tree", - Description: ("LOCATE the RIGHT DOCUMENT among MANY before deep-reading. Use it " + - "BEFORE search_chunks when the dataset is large and you have no " + - "doc_id yet — it routes by TOPIC/CLUSTERING similarity over the " + - "compiled document-navigation tree (not exact surface words), so it " + - "finds the document even when your query words differ from its text. " + - "Returns candidate doc_ids + a first-chunk summary of each. " + - "This is the FIRST hop of a navigation chain: " + - "navigate_tree(query) -> doc_id -> navigate_structure(doc_id, ...) " + - "-> list_chunks(doc_id, chunk_ids). " + - "Use when: the question names a topic/entity/alias but you do not " + - "know which document discusses it; search_chunks returned scattered " + - "hits across many docs and you must pick the source. " + - "Do NOT use if you already hold a doc_id (go straight to " + - "navigate_structure) or if the answer is likely a single exact " + - "passage (prefer retrieve/search_chunks). " + - "If the dataset has no compiled document navigation tree, it returns " + - "empty — fall back to search_chunks."), + Description: `WHEN TO CALL: The question names a topic, entity, or alias but you do NOT know which document discusses it, especially on a large corpus. Routes by topic or cluster similarity over the compiled navigation tree.` + + `DO NOT CALL: When you already hold a doc_id (go straight to navigate_structure); when the answer is likely a single exact passage (use retrieve or search_chunks).` + + `ARGUMENTS: query — string, the topic / entity / alias whose document(s) to locate. Note: keywords is read by the executor but is NOT a declared parameter; do not pass it.` + + `OUTPUT: Candidate doc_ids plus a first-chunk summary of each; these become your known-docs set for the next step.` + + `IF IT FAILS: empty (no_structure) means the dataset has no compiled navigation tree — immediately switch to search_chunks. A second such empty disables this tool for the rest of the session, so do not retry it.`, Parameters: map[string]any{ "type": "object", "properties": map[string]any{ @@ -1031,18 +1014,11 @@ var ( Type: "function", Function: ToolFunction{ Name: "navigate_structure", - Description: ("PINPOINT A PASSAGE inside ONE document using its compiled structure " + - "(heading/catalog tree, concept mindmap, or entity graph) — the " + - "in-document counterpart of navigate_tree. " + - "Use AFTER you know the doc_id (from navigate_tree / search_chunks / " + - "retrieve) and need to find where the answer lives WITHOUT reading " + - "every chunk. Returns the structure outline annotated with matching " + - "chunk_ids (reading-order aware). Then call list_chunks(doc_id, " + - "chunk_ids) to read exactly those. " + - "kind: 'catalog' (default) for page-index/heading/timeline trees, " + - "'mindmap' for concept maps, 'graph' for entity-relation graphs. " + - "If the document has NO compiled structure, an empty is " + - "returned — fall back to list_chunks to read the full document."), + Description: `WHEN TO CALL: You know the doc_id and need to PINPOINT where the answer lives inside that one document, without reading every chunk. The in-document counterpart of navigate_tree.` + + `DO NOT CALL: When you have no doc_id yet; when the document has no compiled structure (use list_chunks to read the full document).` + + `ARGUMENTS: doc_id — string, required. query — string, what to locate within the document. kind — enum catalog / mindmap / graph, default catalog (compiled-structure kind).` + + `OUTPUT: The structure outline annotated with matching chunk_ids, reading-order aware. ok = useful hits; poor (chunk_ptrs = 0) means it drilled to nothing usable.` + + `IF IT FAILS: empty (no_structure) — try another doc_id or kind, or fall back to list_chunks / search_chunks. poor — read the full document via list_chunks(doc_id). A second empty disables the tool for the session.`, Parameters: map[string]any{ "type": "object", "properties": map[string]any{ @@ -1059,19 +1035,11 @@ var ( Type: "function", Function: ToolFunction{ Name: "calculate", - Description: ("COMPUTE a numeric answer by generating and safely running code. " + - "MANDATORY whenever the question asks you to DERIVE a number by " + - "combining facts you found (sum/difference/percentage/ratio/sort/" + - "compare/difference in length/age, price, area, growth, etc.) — do " + - "NOT do arithmetic mentally. Language-neutral: the question and " + - "facts may be in ANY language (English, Chinese, ...); pass the " + - "numbers verbatim as written in the evidence regardless of language. " + - "Steps: (1) collect every needed number first (retrieve / " + - "search_chunks / navigate_* / list_chunks); (2) call calculate with " + - "the question + ALL those numbers; (3) report the computed result " + - "verbatim. If a needed number is missing, search for it first — do " + - "not estimate. If the answer IS one of the stated numbers (no " + - "combination needed), answer directly without this tool."), + Description: `WHEN TO CALL: The question asks you to DERIVE a number by combining facts you found (sum / difference / percentage / ratio / sort / compare / length / age / price / area / growth). NEVER do arithmetic mentally.` + + `DO NOT CALL: When the answer IS one of the stated numbers (no combination needed) — answer directly. When a needed number is still missing — retrieve it first; do not estimate.` + + `ARGUMENTS: question — string, the user question verbatim. facts — array of strings, the numbers or facts found in evidence, verbatim (keep the original language; pass them exactly as written).` + + `OUTPUT: an object with expression and result — report the computed result verbatim.` + + `IF IT FAILS: poor (no numeric answer derivable) — retrieve more numbers, or answer directly if the answer is already stated. Never fabricate a computation.`, Parameters: map[string]any{ "type": "object", "properties": map[string]any{ @@ -1177,6 +1145,10 @@ type Toolset struct { // DisabledTools holds tools proven unavailable this session (no compiled // structure of their kind). DisabledTools map[string]bool + // mu guards DisabledTools: one Toolset is shared by a session's concurrent + // rag calls (models.appendToolResults runs a round's tool calls in parallel), + // so the map must not be written and read unsynchronized. + mu sync.Mutex // Exec runs the tools. Exec ToolExecutor } @@ -1209,7 +1181,7 @@ func (t *Toolset) ActiveToolSpecs() []ToolSpec { if name == "web_search" && !t.HasWebSearch { continue } - if t.DisabledTools[name] { + if t.IsDisabled(name) { continue } if s, ok := ToolMap[name]; ok { @@ -1226,6 +1198,8 @@ func (t *Toolset) DisableTool(name string) { if _, ok := ToolMap[name]; !ok { return } + t.mu.Lock() + defer t.mu.Unlock() if t.DisabledTools == nil { t.DisabledTools = map[string]bool{} } @@ -1234,6 +1208,8 @@ func (t *Toolset) DisableTool(name string) { // IsDisabled reports whether name has been disabled this session. func (t *Toolset) IsDisabled(name string) bool { + t.mu.Lock() + defer t.mu.Unlock() return t.DisabledTools[name] } @@ -1665,8 +1641,10 @@ type SessionState struct { // ToolChars is the running total of tool-payload chars emitted so far // (O(1) accounting; Python tracks the same counter as _tool_chars). ToolChars int - // ToolCache avoids re-executing an identical (name, args) call. - ToolCache map[string]ToolOutcome + // ToolCache avoids re-executing an identical (name, args) call. It is the + // per-round cache shared with the round's other sessions, so it is a guarded + // *ToolCache rather than a bare map. + ToolCache *ToolCache // SearchQueries accumulates retrieval queries for near-dup detection. SearchQueries []string // SkippedDup counts near-duplicate retrievals suppressed so far. @@ -1821,7 +1799,7 @@ func (s *SessionState) toolNode(ctx context.Context) error { } used := s.ToolChars if s.ToolCache == nil { - s.ToolCache = map[string]ToolOutcome{} + s.ToolCache = NewToolCache() } seenQueries := append([]string(nil), s.SearchQueries...) skipped := 0 @@ -1867,14 +1845,16 @@ func (s *SessionState) toolNode(ctx context.Context) error { continue } - // Same-session cache: avoid re-running an identical (name, args) call. + // Same-round cache: avoid re-running an identical (name, args) call. // The cache only avoids RE-EXECUTING; a response is still returned for // every declared call, because the assistant message declared it. + // The cache is shared by a round's concurrent sessions, hence the guarded + // Get/Put. cacheKey := callCacheKey(c) - oc, cached := s.ToolCache[cacheKey] + oc, cached := s.ToolCache.Get(cacheKey) if !cached { oc = ExecuteTool(ctx, s.Tools, c.Name, c.Args) - s.ToolCache[cacheKey] = oc + s.ToolCache.Put(cacheKey, oc) } if q != "" { seenQueries = append(seenQueries, q) @@ -2387,6 +2367,46 @@ func callCacheKey(c ToolCall) string { return c.Name + "|" + string(raw) } +// ToolCache is the per-round tool-outcome cache. One instance is shared by a +// round's CONCURRENT sessions: Python builds a single dict per round +// (agentic_rag_graph.py:1407) and hands it to every session (:2030), and only +// asyncio's cooperative scheduling keeps that safe. Go's sessions are goroutines +// and concurrent map access is a FATAL error there, so the map is guarded. +type ToolCache struct { + mu sync.Mutex + m map[string]ToolOutcome +} + +// NewToolCache returns an empty, concurrency-safe tool cache. +func NewToolCache() *ToolCache { return &ToolCache{m: map[string]ToolOutcome{}} } + +// Get returns the cached outcome for key. A nil cache never holds anything, so a +// session constructed without one simply re-executes (the pre-existing behavior). +func (c *ToolCache) Get(key string) (ToolOutcome, bool) { + if c == nil { + return ToolOutcome{}, false + } + c.mu.Lock() + defer c.mu.Unlock() + oc, ok := c.m[key] + return oc, ok +} + +// Put stores the outcome for key. Two identical calls that lose the race both +// compute and both store — Python's dict behaves the same way under asyncio (the +// cache avoids re-executing DELIBERATE repeats, not simultaneous ones). +func (c *ToolCache) Put(key string, oc ToolOutcome) { + if c == nil { + return + } + c.mu.Lock() + defer c.mu.Unlock() + if c.m == nil { + c.m = map[string]ToolOutcome{} + } + c.m[key] = oc +} + // stripUnpairedToolCalls removes assistant tool_calls that never received a // tool response — a malformed history makes providers reject the next request // ("tool call result does not follow tool call"). @@ -3040,7 +3060,7 @@ type SessionDeps struct { // Returns an empty Result (no states) when no model is configured or the // session fails — mirroring Python, which logs and returns // Result(messages=[], new_states=[]) rather than propagating. -func RunActionSession(ctx context.Context, deps SessionDeps, direction string, parent State, deadlineLeft float64, baseSummary string, sharedToolCache map[string]ToolOutcome, sharedSearchQueries []string) Result { +func RunActionSession(ctx context.Context, deps SessionDeps, direction string, parent State, deadlineLeft float64, baseSummary string, sharedToolCache *ToolCache, sharedSearchQueries []string) Result { system := loadPrompt(deps.Prompts, "action_run") seedUser := fmt.Sprintf("Direction: %s\n\nState:\n%s", direction, parent.RenderSlots()) @@ -3091,7 +3111,7 @@ func RunActionSession(ctx context.Context, deps SessionDeps, direction string, p Direction: direction, } if st.ToolCache == nil { - st.ToolCache = map[string]ToolOutcome{} + st.ToolCache = NewToolCache() } // The graph loop is bounded by the turn budget and the deadline; the context diff --git a/internal/rag/advanced_rag/harness/action_session_test.go b/internal/rag/advanced_rag/harness/action_session_test.go index f30a707a028..8658f5cb4d8 100644 --- a/internal/rag/advanced_rag/harness/action_session_test.go +++ b/internal/rag/advanced_rag/harness/action_session_test.go @@ -8,6 +8,7 @@ import ( "strings" "sync" "testing" + "unicode/utf8" "github.com/cloudwego/eino/compose" "github.com/cloudwego/eino/schema" @@ -95,7 +96,7 @@ func TestToolNodeContinuesLadderInCode(t *testing.T) { DeadlineLeft: 60, Direction: "who created Culdcept", NavRuleID: llmRung, - ToolCache: map[string]ToolOutcome{}, + ToolCache: NewToolCache(), PendingCalls: []ToolCall{ {ID: "call-1", Name: "navigate_structure"}, }, @@ -152,7 +153,7 @@ func TestToolNodeLeavesLadderAloneWithNoPendingRule(t *testing.T) { DeadlineLeft: 60, Direction: "who created Culdcept", NavRuleID: "", // ladder finished - ToolCache: map[string]ToolOutcome{}, + ToolCache: NewToolCache(), PendingCalls: []ToolCall{ {ID: "call-1", Name: "retrieve"}, }, @@ -1089,3 +1090,101 @@ func TestRenderPromptUsesLoader(t *testing.T) { // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- + +// --------------------------------------------------------------------------- +// Tool spec / schema contract (moved here from action_session_schema_test.go) +// --------------------------------------------------------------------------- + +// playbookAnchors are the 5-section contract every tool description must carry +// (mirrors PLAYBOOK_ANCHORS in the Python action-session schema test). +var playbookAnchors = []string{"WHEN TO CALL", "DO NOT CALL", "ARGUMENTS", "OUTPUT", "IF IT FAILS"} + +// executorSupportedParams lists the params the executor actually consumes per +// tool (mirrors _EXECUTOR_SUPPORTED). The schema MUST NOT declare any param +// outside this set — otherwise the model is told to fill an argument the runtime +// silently ignores (the list_chunks(chunk_ids) ghost bug). Note: doc_scope / +// keywords are supported by the executor but intentionally NOT declared in the +// schema (keep the description honest with the implementation). +var executorSupportedParams = map[string]map[string]bool{ + "retrieve": {"query": true, "doc_scope": true}, + "search_chunks": {"query": true}, + "list_chunks": {"doc_id": true}, + "navigate_tree": {"query": true, "keywords": true}, + "navigate_structure": {"doc_id": true, "query": true, "kind": true}, + "calculate": {"question": true, "facts": true}, + "web_search": {"query": true}, +} + +// TestToolSpecsHavePlaybookSections pins the PR: each of the 7 tools documents +// the 5-section contract, within the token budget (cap 1200 chars). +func TestToolSpecsHavePlaybookSections(t *testing.T) { + for _, name := range allTools { + desc := ToolMap[name].Function.Description + for _, anchor := range playbookAnchors { + if !strings.Contains(desc, anchor) { + t.Errorf("%s description missing anchor %q", name, anchor) + } + } + if n := utf8.RuneCountInString(desc); n > 1200 { + t.Errorf("%s description too long: %d chars (cap 1200)", name, n) + } + } +} + +// TestActiveToolSpecsToolSurface pins mode -> exposed tool count: low=0, +// medium/high=7, ultra=8, web-hidden=6. +func TestActiveToolSpecsToolSurface(t *testing.T) { + cases := []struct { + mode string + web bool + want int + }{ + {"low", true, 0}, + {"medium", true, 7}, + {"high", true, 7}, + {"ultra", true, 8}, + {"medium", false, 6}, + } + for _, c := range cases { + ts := &Toolset{ThinkingMode: c.mode, HasWebSearch: c.web} + if got := len(ts.ActiveToolSpecs()); got != c.want { + t.Errorf("mode=%s web=%t: tools = %d, want %d", c.mode, c.web, got, c.want) + } + } +} + +// TestSchemaParamsMatchExecutor pins that no schema declares a param the +// executor cannot consume (no ghost args). +func TestSchemaParamsMatchExecutor(t *testing.T) { + for _, name := range allTools { + props, _ := ToolMap[name].Function.Parameters["properties"].(map[string]any) + supported := executorSupportedParams[name] + for param := range props { + if param == "decision" { + continue + } + if !supported[param] { + t.Errorf("%s declares unsupported param %q", name, param) + } + } + } +} + +// TestActionRunPromptHasPlaybook pins that action_run.md exposes the TOOL +// PLAYBOOK and only references real tools. +func TestActionRunPromptHasPlaybook(t *testing.T) { + prompt := loadPrompt(nil, "action_run") + if !strings.Contains(prompt, "TOOL PLAYBOOK") { + t.Error("action_run prompt missing TOOL PLAYBOOK") + } + for _, tool := range []string{"navigate_structure", "calculate", "graph_explore"} { + if !strings.Contains(prompt, tool) { + t.Errorf("action_run prompt missing tool %q", tool) + } + } + for _, name := range append(append([]string{}, allTools...), GraphExploreTool) { + if _, ok := ToolMap[name]; !ok { + t.Errorf("%q referenced by the playbook is not in ToolMap", name) + } + } +} diff --git a/internal/rag/advanced_rag/harness/arithmetic.go b/internal/rag/advanced_rag/harness/arithmetic.go index 8939c7d082b..d77cf02f93e 100644 --- a/internal/rag/advanced_rag/harness/arithmetic.go +++ b/internal/rag/advanced_rag/harness/arithmetic.go @@ -1380,11 +1380,14 @@ func dateDiff(a, b any) (int64, error) { if err != nil { return 0, err } - days := db.Sub(da).Hours() / 24 - if days < 0 { - days = -days - } - return int64(days), nil + // Both dates are midnight UTC, so a second-based difference is exact and + // avoids time.Duration's ~292-year int64 nanosecond ceiling, which SATURATES + // (every longer span came back as 106751 days). + seconds := db.Unix() - da.Unix() + if seconds < 0 { + seconds = -seconds + } + return seconds / 86400, nil } func parseISODate(s string) (time.Time, error) { diff --git a/internal/rag/advanced_rag/harness/arithmetic_test.go b/internal/rag/advanced_rag/harness/arithmetic_test.go index 81a98bc30e8..0bc9bca35b1 100644 --- a/internal/rag/advanced_rag/harness/arithmetic_test.go +++ b/internal/rag/advanced_rag/harness/arithmetic_test.go @@ -563,3 +563,27 @@ func TestComputeFromFactsFitsToContextBudget(t *testing.T) { t.Errorf("value = %q, want 44", cf.Value) } } + +// TestDateDiffCountsCalendarDays pins that date_diff counts calendar days rather +// than a time.Duration: the latter saturates at its ~292-year int64 nanosecond +// ceiling, so every longer span came back as 106751 days. +func TestDateDiffCountsCalendarDays(t *testing.T) { + cases := []struct { + a, b string + want int64 + }{ + {"1941-07-28", "1959-07-17", 6563}, // the prompt's own example + {"1607-05-14", "2020-01-01", 150712}, // 412 years: past the Duration ceiling + {"2020-01-01", "1607-05-14", 150712}, // order-independent (abs) + {"1607-05-14", "1607-05-14", 0}, + } + for _, tc := range cases { + got, err := dateDiff(tc.a, tc.b) + if err != nil { + t.Fatalf("dateDiff(%q, %q): %v", tc.a, tc.b, err) + } + if got != tc.want { + t.Errorf("dateDiff(%q, %q) = %d, want %d", tc.a, tc.b, got, tc.want) + } + } +} diff --git a/internal/rag/advanced_rag/harness/doc_fetch.go b/internal/rag/advanced_rag/harness/doc_fetch.go index 7d4878f7dd8..10dbb206d7b 100644 --- a/internal/rag/advanced_rag/harness/doc_fetch.go +++ b/internal/rag/advanced_rag/harness/doc_fetch.go @@ -130,20 +130,49 @@ func summarizeDocument(ctx context.Context, deps SearchDeps, docID string, maxTo } // Python :942-948 — the document becomes part of the evidence set, so its - // [ID]s stay citable; only the blocks added here are returned. - startIdx := 0 - if deps.KB != nil { - startIdx = len(deps.KB.Chunks) - deps.KB.Merge(chunks, aggs) - } else { + // [ID]s stay citable; only the blocks of the chunks read here are returned. + // + // The blocks are picked by the SOURCE CHUNK, not by the pre-merge chunk + // count: KBPrompt skips a chunk with no content and stops when the token + // budget is exhausted, so block N is not chunk N — a slice taken at the + // pre-merge count can drop readable blocks, or point past the end and return + // nil for a document that was read fine (Python's `blocks[start_idx:]` has the + // same flaw; Go hits it more often because Merge deduplicates a document + // chunk that is already pooled, so the pre-merge count can even equal the + // post-merge count). Merge reports the pool position of every chunk this + // fetch contributed — deduplicated ones included — which makes the mapping + // exact; iterating it keeps the document's reading order. + if deps.KB == nil { deps.KB = &Kbinfos{} - deps.KB.Merge(chunks, aggs) } - blocks := prompts.KBPrompt(deps.KB.Chunks, budget) - if startIdx >= len(blocks) { + added := deps.KB.Merge(chunks, aggs) + blocks, sources := prompts.KBPromptWithSourceIndices(deps.KB.Chunks, budget) + blockAt := make(map[int]string, len(sources)) + for i, src := range sources { + if _, seen := blockAt[src]; !seen { + blockAt[src] = blocks[i] + } + } + // One block per POOL POSITION. `added` is positional per OCCURRENCE: a chunk + // the reader served twice (offset paging over an unstable order) or a chunk + // already pooled is reported at the same position again, so appending per + // occurrence would hand the model the same block — and its tokens — twice. + fresh := make([]string, 0, len(added)) + seenPositions := make(map[int]struct{}, len(added)) + for _, pos := range added { + if _, seen := seenPositions[pos]; seen { + continue + } + seenPositions[pos] = struct{}{} + if block, ok := blockAt[pos]; ok { + fresh = append(fresh, block) + } + } + // Nothing of this document survived the budget: the pool is already at the + // model window, so there is no block to hand back. + if len(fresh) == 0 { return nil } - fresh := blocks[startIdx:] // Python :952-959 — without do_refer the model is told not to cite, so the // rules must not be handed to it. diff --git a/internal/rag/advanced_rag/harness/doc_fetch_test.go b/internal/rag/advanced_rag/harness/doc_fetch_test.go new file mode 100644 index 00000000000..9382ee68134 --- /dev/null +++ b/internal/rag/advanced_rag/harness/doc_fetch_test.go @@ -0,0 +1,127 @@ +// +// 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. +// + +package harness + +import ( + "context" + "strings" + "testing" +) + +// docChunkStub serves one document's chunks in reading order, paged. +type docChunkStub struct { + chunks []map[string]any +} + +func (d *docChunkStub) DocChunks(_ context.Context, req DocChunksRequest) ([]map[string]any, error) { + if req.Offset >= len(d.chunks) { + return nil, nil + } + end := req.Offset + req.Limit + if end > len(d.chunks) { + end = len(d.chunks) + } + return d.chunks[req.Offset:end], nil +} + +func docFetchDeps(pool, docChunks []map[string]any) SearchDeps { + return SearchDeps{ + KbIDs: []string{"kb-1"}, + TenantID: "tenant-1", + KB: &Kbinfos{Chunks: pool}, + DocChunks: &docChunkStub{chunks: docChunks}, + } +} + +// TestSummarizeDocumentReturnsBlocksForAlreadyPooledChunks covers the case the +// pre-merge chunk count gets wrong on its own: Merge deduplicates a chunk that is +// already pooled, so the pool does not grow and a slice taken at the pre-merge +// count starts past the end of the rendered blocks — the tool then reported that +// a document it had just read had no readable chunks. +func TestSummarizeDocumentReturnsBlocksForAlreadyPooledChunks(t *testing.T) { + pool := []map[string]any{{"chunk_id": "c1", "content": "Pooled body."}} + docChunks := []map[string]any{{"chunk_id": "c1", "content": "Pooled body."}} + + got := summarizeDocument(context.Background(), docFetchDeps(pool, docChunks), "doc-1", 100000) + + if len(got) != 1 { + t.Fatalf("blocks = %d (%v), want the document's block even though it was already pooled", len(got), got) + } + if !strings.Contains(got[0], "Pooled body.") { + t.Errorf("block = %q, want the document's content", got[0]) + } +} + +// TestSummarizeDocumentSelectsBlocksBySourceChunk covers a skipped chunk: KBPrompt +// renders no block for a chunk without content, so every later block is one +// position earlier than its chunk. Slicing by the chunk count dropped the first +// document block. +func TestSummarizeDocumentSelectsBlocksBySourceChunk(t *testing.T) { + pool := []map[string]any{ + {"chunk_id": "empty", "content": ""}, // renders no block + } + docChunks := []map[string]any{ + {"chunk_id": "c1", "content": "First document body."}, + {"chunk_id": "c2", "content": "Second document body."}, + } + + got := summarizeDocument(context.Background(), docFetchDeps(pool, docChunks), "doc-1", 100000) + + if len(got) != 2 { + t.Fatalf("blocks = %d (%v), want both document chunks", len(got), got) + } + if !strings.Contains(got[0], "First document body.") || !strings.Contains(got[1], "Second document body.") { + t.Errorf("blocks = %v, want the document's chunks in reading order", got) + } +} + +// TestSummarizeDocumentReturnsNothingWhenNoChunkRenders keeps the guard: when the +// fetched chunks contribute no renderable block there is nothing to hand back, +// and in particular no unrelated pooled block. +func TestSummarizeDocumentReturnsNothingWhenNoChunkRenders(t *testing.T) { + pool := []map[string]any{{"chunk_id": "p0", "content": "Pooled evidence."}} + docChunks := []map[string]any{{"chunk_id": "c1", "content": " "}} + + got := summarizeDocument(context.Background(), docFetchDeps(pool, docChunks), "doc-1", 100000) + + if len(got) != 0 { + t.Fatalf("blocks = %v, want nothing for a document with no renderable chunk", got) + } +} + +// TestSummarizeDocumentDeduplicatesRepeatedSourcePositions covers the paging +// hazard: offset paging over an unstable order can serve the same chunk on two +// pages, and Merge reports a position per OCCURRENCE, not per distinct chunk. The +// block of that one pooled chunk was therefore appended twice — paying its tokens +// into the prompt twice, on top of a budget that was already spent. +func TestSummarizeDocumentDeduplicatesRepeatedSourcePositions(t *testing.T) { + pool := []map[string]any{{"chunk_id": "p0", "content": "Pooled evidence."}} + docChunks := []map[string]any{ + {"chunk_id": "c1", "content": "Document body."}, + {"chunk_id": "c1", "content": "Document body."}, // same chunk served twice + {"chunk_id": "c2", "content": "Second body."}, + } + + got := summarizeDocument(context.Background(), docFetchDeps(pool, docChunks), "doc-1", 100000) + + if len(got) != 2 { + t.Fatalf("blocks = %d (%v), want one block per distinct fetched chunk", len(got), got) + } + if !strings.Contains(got[0], "Document body.") || !strings.Contains(got[1], "Second body.") { + t.Errorf("blocks = %v, want the document's chunks in reading order, each once", got) + } +} diff --git a/internal/rag/advanced_rag/harness/kbinfos.go b/internal/rag/advanced_rag/harness/kbinfos.go index 548b56d0de3..605e37545c4 100644 --- a/internal/rag/advanced_rag/harness/kbinfos.go +++ b/internal/rag/advanced_rag/harness/kbinfos.go @@ -77,7 +77,15 @@ type SearchParams struct { type SearchFn func(ctx context.Context, p SearchParams) ([]map[string]any, []map[string]any) // Kbinfos is the shared accumulation store. +// +// ONE Kbinfos is shared by a round's CONCURRENT sessions (SessionDeps.KB; see +// RunSlotResearchPass), so its mutable state is guarded by mu. Python needs no +// lock — its sessions are coroutines and every admission stretch is await-free +// (action_session.py:691-700), so asyncio cannot interleave two sessions' +// batches. Go runs the same sessions on goroutines, so the critical sections +// Python gets for free have to be locked explicitly: see Admit. type Kbinfos struct { + mu sync.Mutex Chunks []map[string]any DocAggs []map[string]any // Memory is the lossless store of raw retrieved chunks backing the (lossy) @@ -96,10 +104,99 @@ type Kbinfos struct { // HasChunks mirrors Python `bool(kbinfos.get("chunks"))`. func (k *Kbinfos) HasChunks() bool { return len(k.Chunks) > 0 } +// Admit runs fn as ONE critical section over the evidence pool. +// +// The granularity is the caller's, and it must span the stretch Python leaves +// await-free: ONE query's candidate batch, because the awaits sit in the OUTER +// query loop (action_session.py:691-700). Locking per chunk would let two +// sessions' batches interleave into pool orders Python cannot produce, and the +// pool order is observable — it drives the rendered prompt order and the `ID: n` +// numbering, extractRelevantEvidence's first-4 pick, and which chunks make it in +// under the cap. +// +// Inside fn do, per chunk, exactly what _admit_evidence does, in its order: +// +// p.Full() → skip the chunk. The cap check precedes the per-call dedup +// (:638-646), so a rejected chunk is NOT marked seen and is +// retried once room frees. +// then the call-local dedup (`seen`) and payload/ids bookkeeping; +// p.Add(c) → dedup against the live pool and append. +func (k *Kbinfos) Admit(fn func(p *PoolAdmitter)) { + if k == nil { + // No pool bound: the callback still runs — a tool hands its passages back + // either way — but nothing is pooled and the cap never blocks, which is + // what the callers' old `if deps.KB != nil` guard did. + fn(&PoolAdmitter{}) + return + } + k.mu.Lock() + defer k.mu.Unlock() + fn(&PoolAdmitter{k: k}) +} + +// PoolAdmitter is the pool handle, valid only inside Kbinfos.Admit's callback. +type PoolAdmitter struct{ k *Kbinfos } + +// Full mirrors the early stop at the top of _admit_evidence: at the cap the +// chunk is skipped, and nothing about it is recorded (so a rejected chunk is +// retried once room frees). +// +// The "pool FULL" line belongs here for the same reason it lives inside +// _admit_evidence (:639-645), and it is emitted once per PROCESS — Python +// documents _EVIDENCE_POOL_STATE as a "Per-process flag" (:62-64). sync.Once +// because concurrent sessions call this under their own pool lock. +func (p *PoolAdmitter) Full() bool { + if p.k == nil || len(p.k.Chunks) < evidencePoolCap { + return false + } + evidencePoolFullLogged.Do(func() { + _LOG.Printf("[Action Session] evidence pool FULL (%d chunks >= cap %d); early-stopping admit of further chunks.", len(p.k.Chunks), evidencePoolCap) + }) + return true +} + +// evidencePoolFullLogged mirrors Python _EVIDENCE_POOL_STATE["full_logged"]: a +// PER-PROCESS flag (action_session.py:62-64), so the line is emitted once per +// process — not once per rejected chunk, and NOT once per session. The pool never +// shrinks mid-process, so no reset is needed. +var evidencePoolFullLogged sync.Once + +// Add appends c unless the LIVE pool already holds it, reporting whether it +// appended — Python's "new to the shared pool" return. +// +// The test is against the live pool, not a snapshot taken when the call started +// (Python's `kb_seen`, :690). That snapshot is exact only because nothing can +// interleave with it; under Go's parallelism it would re-append a chunk another +// session just pooled, which Python can never do. +// +// There is deliberately NO cap check here: the compiled-expansion path appends +// uncapped in Python too, which is what pushes the pool past _EVIDENCE_POOL_CAP +// (see the comment on evidencePoolCap). Callers that admit user-facing search +// hits check Full() first. +func (p *PoolAdmitter) Add(c map[string]any) bool { + if p.k == nil { + return false + } + if p.Index(c) >= 0 { + return false + } + p.k.Chunks = append(p.k.Chunks, c) + return true +} + +// Index is the pool position of c's identity, or -1 when the pool lacks it (and +// for an unbound pool): the positional contract of Merge — a deduped chunk still +// reports its position. +func (p *PoolAdmitter) Index(c map[string]any) int { + if p.k == nil { + return -1 + } + return indexOfChunk(p.k.Chunks, chunkKey(c)) +} + // Merge appends the given chunks/aggs, deduplicating by chunkKey, and returns the // GLOBAL index (position in k.Chunks) of every contributed chunk — deduped ones -// included. len(result) is therefore NOT the count of new evidence: callers that -// need that compare len(k.Chunks) before and after. +// included. // // Mirrors orchestrator/direct.py:_merge_kbinfos, including its early return on an // empty chunk list (neither chunks nor doc_aggs are merged). @@ -107,20 +204,16 @@ func (k *Kbinfos) Merge(chunks, aggs []map[string]any) []int { if len(chunks) == 0 { return nil } - seen := make(map[string]bool, len(k.Chunks)) - for _, c := range k.Chunks { - seen[chunkKey(c)] = true - } - var added []int - for _, c := range chunks { - kk := chunkKey(c) - if !seen[kk] { - seen[kk] = true - k.Chunks = append(k.Chunks, c) + added := make([]int, 0, len(chunks)) + // One critical section for the whole merge: the dedup is against the live + // pool, so a concurrent session cannot slip the same chunk in between. + k.Admit(func(p *PoolAdmitter) { + for _, c := range chunks { + p.Add(c) + // Deduped chunks get an entry too: the return value is positional. + added = append(added, p.Index(c)) } - // Deduped chunks get an entry too: the return value is positional. - added = append(added, indexOfChunk(k.Chunks, kk)) - } + }) k.MergeDocAggs(aggs) return added } @@ -132,9 +225,11 @@ func (k *Kbinfos) Merge(chunks, aggs []map[string]any) []int { // the search tool must record a search's aggregations even when every chunk it // returned was already pooled. func (k *Kbinfos) MergeDocAggs(aggs []map[string]any) { - if len(aggs) == 0 { + if k == nil || len(aggs) == 0 { return } + k.mu.Lock() + defer k.mu.Unlock() dseen := make(map[string]bool, len(k.DocAggs)+len(aggs)) for _, d := range k.DocAggs { dseen[docAggKey(d)] = true @@ -191,6 +286,12 @@ func chunkText(c map[string]any) string { // present; otherwise falls back to a content-derived key so chunks without an // id still dedup correctly (and never collide on a shared empty key). // +// The content branch reuses chunkText — the SAME alias chain the rest of the +// harness reads (content_with_weight -> content -> text). Reading only the first +// two made two id-less chunks that carry just "text" fall through to the +// doc-level fallback and share one key, so Merge/MemoryAdd discarded distinct +// evidence. +// // This diverges from Python _chunk_key (`chunk_id or id or id(ck)`): Python's // final fallback is `id(ck)` — the dict object's memory address — which means // two equivalent chunks returned as distinct objects never share a key, so @@ -203,12 +304,7 @@ func chunkKey(c map[string]any) string { if id, ok := c["id"].(string); ok && id != "" { return "id:" + id } - content := "" - if t, ok := c["content_with_weight"].(string); ok { - content = t - } else if t, ok := c["content"].(string); ok { - content = t - } + content := chunkText(c) if content == "" { // No stable identity: fall back to the doc reference so at least // per-document grouping is preserved (rarely reached). diff --git a/internal/rag/advanced_rag/harness/kbinfos_test.go b/internal/rag/advanced_rag/harness/kbinfos_test.go index 2dc7209e5e9..2ad44d9b703 100644 --- a/internal/rag/advanced_rag/harness/kbinfos_test.go +++ b/internal/rag/advanced_rag/harness/kbinfos_test.go @@ -1,6 +1,10 @@ package harness -import "testing" +import ( + "fmt" + "sync" + "testing" +) // TestMergeSkipsAllWhenNoChunks mirrors Python _merge_kbinfos's early return: // `if not result or not result.get("chunks"): return`. When the incoming chunk @@ -49,3 +53,151 @@ func TestMergeDedupsSameDocID(t *testing.T) { t.Fatalf("same-doc_id aggs should dedup, got %d", len(kb.DocAggs)) } } + +// TestChunkKeyUsesTextFallback pins that the dedup key reads the SAME alias chain +// as chunkText (content_with_weight -> content -> text). Reading only the first +// two made two id-less, text-only chunks from one document share the doc-level +// fallback key, so Merge/MemoryAdd discarded distinct evidence. +func TestChunkKeyUsesTextFallback(t *testing.T) { + a := map[string]any{"text": "alpha", "doc_id": "d1", "docnm_kwd": "doc"} + b := map[string]any{"text": "beta", "doc_id": "d1", "docnm_kwd": "doc"} + if chunkKey(a) == chunkKey(b) { + t.Fatalf("distinct text-only chunks must not share a key: %q", chunkKey(a)) + } + // The same text under any alias must produce the same key. + if c := map[string]any{"content": "alpha"}; chunkKey(a) != chunkKey(c) { + t.Errorf("text and content aliases must agree: %q vs %q", chunkKey(a), chunkKey(c)) + } + // A chunk with no text at all still lands on the doc-level fallback. + if got := chunkKey(map[string]any{"doc_id": "d1", "docnm_kwd": "doc"}); got == "" { + t.Error("doc-level fallback key must not be empty") + } +} + +// TestMergeKeepsDistinctTextOnlyChunks pins the end-to-end consequence for the +// evidence pool: two id-less chunks that share only a document must both survive. +func TestMergeKeepsDistinctTextOnlyChunks(t *testing.T) { + kb := &Kbinfos{} + added := kb.Merge([]map[string]any{ + {"text": "alpha", "doc_id": "d1", "docnm_kwd": "doc"}, + {"text": "beta", "doc_id": "d1", "docnm_kwd": "doc"}, + }, nil) + if len(kb.Chunks) != 2 { + t.Fatalf("chunks = %d, want 2 (distinct text-only evidence must not collapse)", len(kb.Chunks)) + } + if len(added) != 2 { + t.Fatalf("added = %v, want 2 global indices", added) + } + // Re-merging identical content still dedups. + kb.Merge([]map[string]any{{"text": "alpha", "doc_id": "d1", "docnm_kwd": "doc"}}, nil) + if len(kb.Chunks) != 2 { + t.Fatalf("identical text must still dedup, chunks = %d", len(kb.Chunks)) + } +} + +// TestMemoryAddKeepsDistinctTextOnlyChunks pins the same consequence for the +// lossless memory store. +func TestMemoryAddKeepsDistinctTextOnlyChunks(t *testing.T) { + kb := &Kbinfos{} + MemoryAdd(kb, []map[string]any{ + {"text": "alpha", "doc_id": "d1", "docnm_kwd": "doc"}, + {"text": "beta", "doc_id": "d1", "docnm_kwd": "doc"}, + }) + if len(kb.Memory) != 2 { + t.Fatalf("memory = %d, want 2 (distinct text-only evidence must not collapse)", len(kb.Memory)) + } + MemoryAdd(kb, []map[string]any{{"text": "alpha", "doc_id": "d1", "docnm_kwd": "doc"}}) + if len(kb.Memory) != 2 { + t.Fatalf("identical text must still dedup, memory = %d", len(kb.Memory)) + } +} + +// TestKbinfosAdmitIsAtomic pins the pool's invariants under the concurrency the +// pool actually sees: one round's sessions run at the same time and share ONE +// Kbinfos (SessionDeps.KB; RunSlotResearchPass starts them as goroutines). +// +// Python gets both invariants for free — asyncio never preempts the await-free +// admit stretch (_admit_evidence is a plain def, action_session.py:615, and the +// per-query loop has no await, :691-700) — so Go has to lock the same stretch. +// +// The pool starts one chunk short of the cap, and both sessions offer the SAME +// first chunk. Whichever batch wins the lock pools it — once — and the cap then +// stops every further chunk, so the assertions hold whatever the schedule does: +// they fail only when the batches interleave (which is what an unlocked +// check-then-append does: both sessions read 59 and both append). +func TestKbinfosAdmitIsAtomic(t *testing.T) { + pool := &Kbinfos{} + for i := 0; i < evidencePoolCap-1; i++ { + pool.Admit(func(p *PoolAdmitter) { + p.Add(map[string]any{"chunk_id": fmt.Sprintf("p%d", i)}) + }) + } + if len(pool.Chunks) != evidencePoolCap-1 { + t.Fatalf("fixture pool = %d chunks, want %d", len(pool.Chunks), evidencePoolCap-1) + } + + var wg sync.WaitGroup + for _, tag := range []string{"a", "b"} { + wg.Add(1) + go func(tag string) { + defer wg.Done() + pool.Admit(func(p *PoolAdmitter) { + for _, c := range []map[string]any{ + {"chunk_id": "shared"}, + {"chunk_id": tag}, + } { + if p.Full() { + continue + } + p.Add(c) + } + }) + }(tag) + } + wg.Wait() + + if len(pool.Chunks) != evidencePoolCap { + t.Errorf("pool = %d chunks, want exactly the cap %d: a serialized batch stops at the cap, an interleaved one overshoots", + len(pool.Chunks), evidencePoolCap) + } + counts := map[string]int{} + for _, c := range pool.Chunks { + id, _ := c["chunk_id"].(string) + counts[id]++ + } + if counts["shared"] != 1 { + t.Errorf("chunk %q pooled %d time(s), want exactly 1: the pool must be deduped against its LIVE contents", "shared", counts["shared"]) + } + if counts["a"]+counts["b"] != 0 { + t.Errorf("session-private chunks were pooled (%d a, %d b) although only one slot was free", counts["a"], counts["b"]) + } +} + +// TestToolCacheIsConcurrencySafe exercises the cache the way a round does: the +// SAME instance handed to concurrent sessions (Python builds one dict per round, +// agentic_rag_graph.py:1407, and passes it to every session, action_session.py:2030). +// Run under -race this is what a bare map cannot survive — concurrent map writes +// are a fatal error in Go, not merely a race report. +func TestToolCacheIsConcurrencySafe(t *testing.T) { + cache := NewToolCache() + var wg sync.WaitGroup + for i := 0; i < 16; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + key := fmt.Sprintf("tool-%d", i%4) // deliberate key collisions + if _, ok := cache.Get(key); !ok { + cache.Put(key, ToolOutcome{Reason: key}) + } + }(i) + } + wg.Wait() + + for i := 0; i < 4; i++ { + key := fmt.Sprintf("tool-%d", i) + oc, ok := cache.Get(key) + if !ok || oc.Reason != key { + t.Errorf("cache[%q] = (%+v, %v), want the stored outcome", key, oc, ok) + } + } +} diff --git a/internal/rag/advanced_rag/harness/memory.go b/internal/rag/advanced_rag/harness/memory.go index b738af57789..aab01ba53bf 100644 --- a/internal/rag/advanced_rag/harness/memory.go +++ b/internal/rag/advanced_rag/harness/memory.go @@ -34,8 +34,10 @@ import ( // The store lives on Kbinfos.Memory so it travels with the request. const ( - // grepMaxChunks caps how many chunks one grep returns (Python - // memory._GREP_MAX_CHUNKS = 6). + // grepMaxChunks is Python memory.grep's default cap (_GREP_MAX_CHUNKS = 6). + // MemoryGrep takes the limit explicitly and does NOT substitute this for a + // non-positive value (Python has no such guard), so callers that want the + // Python default pass it. grepMaxChunks = 6 // grepMaxSentences caps sentences kept per chunk (hit + context). grepMaxSentences = 4 @@ -91,6 +93,11 @@ func MemoryAdd(kb *Kbinfos, chunks []map[string]any) { if kb == nil || len(chunks) == 0 { return } + // One critical section: memory.add is an await-free stretch in Python, so + // asyncio can never interleave two sessions' adds into it (the pool is shared + // across a round's concurrent sessions — see Kbinfos.Admit). + kb.mu.Lock() + defer kb.mu.Unlock() seen := make(map[string]struct{}, len(kb.Memory)) for _, c := range kb.Memory { seen[chunkKey(c)] = struct{}{} @@ -124,6 +131,8 @@ func MemorySize(kb *Kbinfos) int { // MemoryClear mirrors Python memory.clear. func MemoryClear(kb *Kbinfos) { if kb != nil { + kb.mu.Lock() + defer kb.mu.Unlock() kb.Memory = nil } } @@ -134,13 +143,15 @@ func MemoryClear(kb *Kbinfos) { // terms are plain strings (entities / numbers / key phrases) as emitted by the // analysis LLM. Each returned chunk carries a narrowed "content" so the caller // can splice it straight into an evidence list. Empty on no-hit / no-memory. +// +// limit is the maximum number of chunks returned and is NOT normalized: Python's +// grep has no such guard, so a limit <= 0 makes the `len(hits) >= limit` check +// fire on the first hit (at most one chunk comes back). Callers wanting Python's +// default pass grepMaxChunks. func MemoryGrep(kb *Kbinfos, terms []string, limit int) []map[string]any { if kb == nil || len(kb.Memory) == 0 || len(terms) == 0 { return nil } - if limit <= 0 { - limit = grepMaxChunks - } patterns, prefixPatterns := compileTerms(terms) if len(patterns) == 0 && len(prefixPatterns) == 0 { return nil @@ -173,6 +184,13 @@ func MemoryGrep(kb *Kbinfos, terms []string, limit int) []map[string]any { "doc_id": c["doc_id"], "chunk_id": c["chunk_id"], }) + // This branch continues past the shared cap below, so enforce the + // limit here too — otherwise a memory store full of matching short + // chunks comes back whole. Python's memory.grep enforces it in the + // same place. + if len(hits) >= limit { + break + } } continue } diff --git a/internal/rag/advanced_rag/harness/memory_test.go b/internal/rag/advanced_rag/harness/memory_test.go index 971df797587..e1ad0693e72 100644 --- a/internal/rag/advanced_rag/harness/memory_test.go +++ b/internal/rag/advanced_rag/harness/memory_test.go @@ -112,3 +112,35 @@ func TestChunkTextPrefersWeighted(t *testing.T) { t.Errorf("chunkText = %q, want %q", got, "primary only") } } + +// TestMemoryGrepLimitAppliesToShortChunks pins the returned-chunk cap: the +// short-chunk branch continues past the shared check, so it must enforce the +// limit itself — otherwise a memory store full of matching short chunks comes +// back whole instead of at most limit entries. +func TestMemoryGrepLimitAppliesToShortChunks(t *testing.T) { + mem := make([]map[string]any, 0, 10) + for i := 0; i < 10; i++ { + suffix := string(rune('a' + i)) // short chunk: well under shortChunkChars + mem = append(mem, memChunk("rifampicin note "+suffix, "d1", "c"+suffix)) + } + kb := &Kbinfos{Memory: mem} + + hits := MemoryGrep(kb, []string{"rifampicin"}, 2) + if len(hits) != 2 { + t.Fatalf("hits = %d, want the limit 2 (a short chunk must not bypass the cap)", len(hits)) + } + if hits[0]["content"] != "rifampicin note a" { + t.Errorf("hit content = %v, want the whole short chunk", hits[0]["content"]) + } + + // limit <= 0 is NOT normalized to the default: Python's grep has no such + // guard, so the `len(hits) >= limit` check fires on the first hit. + if got := len(MemoryGrep(kb, []string{"rifampicin"}, 0)); got != 1 { + t.Errorf("limit=0 hits = %d, want 1 (Python grep does not normalize limit)", got) + } + + // Python's default (6) is passed explicitly and caps at 6. + if got := len(MemoryGrep(kb, []string{"rifampicin"}, grepMaxChunks)); got != grepMaxChunks { + t.Errorf("default-limit hits = %d, want %d", got, grepMaxChunks) + } +} diff --git a/internal/rag/advanced_rag/harness/orchestrator/sufficient_context.go b/internal/rag/advanced_rag/harness/orchestrator/sufficient_context.go index 33cbd456c5d..c6a97627c73 100644 --- a/internal/rag/advanced_rag/harness/orchestrator/sufficient_context.go +++ b/internal/rag/advanced_rag/harness/orchestrator/sufficient_context.go @@ -21,6 +21,7 @@ import ( "fmt" "regexp" "strings" + "unicode/utf8" "ragflow/internal/rag/advanced_rag/harness" "ragflow/internal/rag/prompts" @@ -145,7 +146,7 @@ func SufficientContextAgent(ctx context.Context, deps SCADeps, question string, "overall_draft": overallDraft, }) _LOG.Printf("[SCA] unified review of %s (reports only, %d chars; overall draft %d chars)", - fmtClaimCount(len(claims)), len(claimsContext), len(overallDraft)) + fmtClaimCount(len(claims)), utf8.RuneCountInString(claimsContext), utf8.RuneCountInString(overallDraft)) result, err := deps.Model.GenJSON(ctx, prompt) if err != nil { @@ -166,7 +167,7 @@ func SufficientContextAgent(ctx context.Context, deps SCADeps, question string, if !ok { continue } - cid := strings.TrimSpace(fmt.Sprint(m["claim_id"])) + cid := strOf(m["claim_id"]) if cid == "" { continue } @@ -176,12 +177,12 @@ func SufficientContextAgent(ctx context.Context, deps SCADeps, question string, if s := strings.TrimSpace(fmt.Sprint(firstNonEmpty(um["assertion"], um["reason"]))); s != "" { ungrounded = append(ungrounded, s) } - } else if s := strings.TrimSpace(fmt.Sprint(u)); s != "" { + } else if s := strOf(u); s != "" { ungrounded = append(ungrounded, s) } } claimsOut[cid] = ClaimVerdict{ - Grounded: truthy(m["grounded"]), + Grounded: coerceBool(m["grounded"]), Ungrounded: ungrounded, MissingInformation: parseMissingInformation(m["missing_information"]), } @@ -195,19 +196,19 @@ func SufficientContextAgent(ctx context.Context, deps SCADeps, question string, if !ok { continue } - sqText := strings.TrimSpace(fmt.Sprint(m["sub_query"])) + sqText := strOf(m["sub_query"]) if sqText == "" { continue } - entry := SubQuery{SubQuery: sqText, Satisfied: truthy(m["satisfied"])} + entry := SubQuery{SubQuery: sqText, Satisfied: coerceBool(m["satisfied"])} if !entry.Satisfied { - entry.MissingFact = strings.TrimSpace(fmt.Sprint(m["missing_fact"])) - entry.SearchHint = strings.TrimSpace(fmt.Sprint(m["search_hint"])) + entry.MissingFact = strOf(m["missing_fact"]) + entry.SearchHint = strOf(m["search_hint"]) } subQueries = append(subQueries, entry) } - isSufficient := truthy(data["is_sufficient"]) + isSufficient := coerceBool(data["is_sufficient"]) // Failsafe: the SCA judged the context insufficient but returned an EMPTY // claims array (a known degradation on very long prompts). Without a gap, the @@ -237,7 +238,7 @@ func SufficientContextAgent(ctx context.Context, deps SCADeps, question string, IsSufficient: isSufficient, Confidence: clamp(data["confidence"]), Contradictions: stringList(data["contradictions"]), - Reasoning: strings.TrimSpace(fmt.Sprint(data["reasoning"])), + Reasoning: strOf(data["reasoning"]), SubQueries: subQueries, Claims: claimsOut, } @@ -315,7 +316,6 @@ func renderClaimContext(claims []ClaimDraft, kb *harness.Kbinfos) string { continue } block := fmt.Sprintf("Claim %s (draft):\n%s", c.ID, c.Draft) - used += len(block) + 2 var anchors []string for _, eid := range c.EvidenceIDs { ck, ok := id2chunk[strings.TrimSpace(eid)] @@ -337,11 +337,23 @@ func renderClaimContext(claims []ClaimDraft, kb *harness.Kbinfos) string { } } if len(anchors) > 0 { - anchorText := strings.Join(anchors, " | ") - block += "\n Evidence: " + anchorText - used += len(anchorText) + 4 + block += "\n Evidence: " + strings.Join(anchors, " | ") + } + // Apply the budget to the COMPLETE block before appending it, trimming it + // to what remains: accounting the block only AFTER appending let a single + // oversized claim blow straight past scaClaimsContextMax (the cap the + // comment claims bounds the whole rendered context). Cut by rune + // (Python's str[:N]) so the trim never splits a multibyte character. + remaining := scaClaimsContextMax - used + if remaining <= 0 { + break + } + if r := []rune(block); len(r) > remaining { + block = string(r[:remaining]) } blocks = append(blocks, block) + // The block plus the "\n\n" join separator. + used += utf8.RuneCountInString(block) + 2 if used >= scaClaimsContextMax { break } @@ -370,8 +382,11 @@ func renderOverallDraft(claims []ClaimDraft) string { return "(no overall draft)" } draft := strings.Join(parts, "\n") - if len(draft) > scaClaimsContextMax { - draft = draft[:scaClaimsContextMax] + // Truncate by RUNE, not byte: Python slices str[:N] by code point, and a byte + // slice through a multibyte (e.g. CJK) rune would emit invalid UTF-8 (or + // replacement characters) into the SCA prompt. + if r := []rune(draft); len(r) > scaClaimsContextMax { + draft = string(r[:scaClaimsContextMax]) } return draft } @@ -505,19 +520,26 @@ func clamp(v any) float64 { return f } -// truthy mirrors Python's builtin bool() on the raw JSON value, exactly as the -// Python sufficient_context path evaluates these fields (e.g. -// bool(item.get("grounded")), bool(result.get("is_sufficient"))). Python's bool() -// treats ANY non-empty string as truthy — including the literal "false" or "0" — -// because they are non-empty. We must not string-parse booleans here, or a model -// that returns grounded:"false" as a string would wrongly collapse to False while -// Python keeps it True. Only an empty string / 0 / nil / False is falsy. -func truthy(v any) bool { +// coerceBool reads an LLM-reported boolean, tolerating the string serialisations +// a drifted model reply may carry. It deliberately does NOT use raw truthiness: +// a non-empty string is truthy in both Go and Python, so bool("false") and +// bool("0") are TRUE — which would silently INVERT a verdict, marking +// insufficient context sufficient or an ungrounded claim grounded. +// +// The recognised true/false spellings are mapped explicitly; an empty or +// unrecognised value fails CLOSED (false), matching this codebase's convention +// that an unusable verdict is INSUFFICIENT (see the SCA-unavailable path in +// agentic_rag_graph.go, which treats a timeout/unparsable reply as insufficient). +func coerceBool(v any) bool { switch t := v.(type) { case bool: return t case string: - return t != "" + switch strings.ToLower(strings.TrimSpace(t)) { + case "true", "1", "yes", "y", "on": + return true + } + return false case float64: return t != 0 case int: @@ -527,19 +549,29 @@ func truthy(v any) bool { case nil: return false } - return true + return false +} + +// strOf renders a raw JSON field as a trimmed string, mapping an absent or null +// value (nil) to "". fmt.Sprint(nil) yields the literal "", which would +// otherwise masquerade as a real claim id, sub-query, gap or reasoning text. +func strOf(v any) string { + if v == nil { + return "" + } + return strings.TrimSpace(fmt.Sprint(v)) } func parseMissingInformation(v any) []MissingPiece { var out []MissingPiece for _, m := range asSlice(v) { if mm, ok := m.(map[string]any); ok { - what := strings.TrimSpace(fmt.Sprint(mm["what"])) - hint := strings.TrimSpace(fmt.Sprint(mm["search_hint"])) + what := strOf(mm["what"]) + hint := strOf(mm["search_hint"]) if what != "" || hint != "" { out = append(out, MissingPiece{What: what, SearchHint: hint}) } - } else if s := strings.TrimSpace(fmt.Sprint(m)); s != "" { + } else if s := strOf(m); s != "" { out = append(out, MissingPiece{What: s}) } } diff --git a/internal/rag/advanced_rag/harness/orchestrator/sufficient_context_test.go b/internal/rag/advanced_rag/harness/orchestrator/sufficient_context_test.go index 90593a69429..34b2a927b10 100644 --- a/internal/rag/advanced_rag/harness/orchestrator/sufficient_context_test.go +++ b/internal/rag/advanced_rag/harness/orchestrator/sufficient_context_test.go @@ -249,13 +249,14 @@ func TestSCABoostAdaptsVerdict(t *testing.T) { // Query rewriter // --------------------------------------------------------------------------- -func TestClampAndTruthy(t *testing.T) { +func TestClampCoercesNumericDrift(t *testing.T) { if got := clamp(float64(1.5)); got != 1.0 { t.Errorf("clamp(1.5) = %v, want 1.0", got) } if got := clamp(float64(-0.2)); got != 0.0 { t.Errorf("clamp(-0.2) = %v, want 0.0", got) } + // Numeric drift: a string number is still parsed. if got := clamp("0.4"); got != 0.4 { t.Errorf("clamp(\"0.4\") = %v, want 0.4", got) } @@ -263,14 +264,164 @@ func TestClampAndTruthy(t *testing.T) { if got := clamp("not a number"); got != 1.0 { t.Errorf("clamp(bad) = %v, want 1.0", got) } - for _, v := range []any{true, "true", "TRUE", "1", "yes", "false", "0", float64(1)} { - if !truthy(v) { - t.Errorf("truthy(%v) = false, want true", v) +} + +// TestCoerceBoolParsesStringDrift pins that a boolean serialised as a string is +// read by MEANING, not by raw truthiness: "false"/"0" are false, not true. An +// empty or unrecognised value fails CLOSED (false), matching the "unusable +// verdict is INSUFFICIENT" convention. +func TestCoerceBoolParsesStringDrift(t *testing.T) { + for _, v := range []any{true, "true", "TRUE", " True ", "1", "yes", "Y", "on", float64(1)} { + if !coerceBool(v) { + t.Errorf("coerceBool(%#v) = false, want true", v) } } - for _, v := range []any{false, "", float64(0), nil} { - if truthy(v) { - t.Errorf("truthy(%v) = true, want false", v) + for _, v := range []any{false, "false", "FALSE", " false ", "0", "no", "N", "off", "", float64(0), nil, "maybe"} { + if coerceBool(v) { + t.Errorf("coerceBool(%#v) = true, want false", v) } } } + +// TestSCAParsesStringBooleans pins the drift fix end to end: a model that +// serialises its verdict booleans as strings must not have them inverted. +func TestSCAParsesStringBooleans(t *testing.T) { + mdl := &stubJSONModel{value: map[string]any{ + "is_sufficient": "false", + "sub_queries": []any{ + map[string]any{"sub_query": "revenue", "satisfied": "false", + "missing_fact": "2023 revenue", "search_hint": "annual report"}, + }, + "claims": []any{ + map[string]any{"claim_id": "c1", "grounded": "false"}, + }, + }} + got := SufficientContextAgent(context.Background(), SCADeps{ + KB: &harness.Kbinfos{}, + Model: mdl, + }, "q", []ClaimDraft{{ID: "c1", Draft: "d"}}) + if got.IsSufficient { + t.Error(`is_sufficient:"false" must read as false, not true`) + } + if len(got.SubQueries) != 1 || got.SubQueries[0].Satisfied { + t.Errorf("sub_queries = %+v, want one unsatisfied", got.SubQueries) + } + if cv := got.Claims["c1"]; cv.Grounded { + t.Error(`grounded:"false" must read as false, not true`) + } + + // The "true" spelling still parses. + mdl = &stubJSONModel{value: map[string]any{"is_sufficient": "true"}} + got = SufficientContextAgent(context.Background(), SCADeps{ + KB: &harness.Kbinfos{}, + Model: mdl, + }, "q", []ClaimDraft{{ID: "c1", Draft: "d"}}) + if !got.IsSufficient { + t.Error(`is_sufficient:"true" must read as true`) + } +} + +// TestSCAIgnoresAbsentFields pins that an absent (nil) field never renders as the +// literal "": a claim without claim_id and a sub-query without sub_query are +// rejected, and the optional text fields stay empty instead of becoming "". +func TestSCAIgnoresAbsentFields(t *testing.T) { + mdl := &stubJSONModel{value: map[string]any{ + "sub_queries": []any{ + map[string]any{"satisfied": false}, // no sub_query + map[string]any{"sub_query": "ok", "satisfied": false}, // no missing_fact/search_hint + }, + "claims": []any{ + map[string]any{"grounded": true}, // no claim_id + map[string]any{"claim_id": "c1", "grounded": true}, // no missing_information + }, + }} + got := SufficientContextAgent(context.Background(), SCADeps{ + KB: &harness.Kbinfos{}, + Model: mdl, + }, "q", []ClaimDraft{{ID: "c1", Draft: "d"}}) + + if _, ok := got.Claims[""]; ok { + t.Error(`a claim with no claim_id must be rejected, not keyed as ""`) + } + if _, ok := got.Claims["c1"]; !ok { + t.Error("the claim with a real claim_id must be kept") + } + if len(got.SubQueries) != 1 { + t.Fatalf("sub_queries = %+v, want only the one with a real sub_query", got.SubQueries) + } + if sq := got.SubQueries[0]; sq.SubQuery != "ok" || sq.MissingFact != "" || sq.SearchHint != "" { + t.Errorf("absent missing_fact/search_hint must stay empty, got %+v", sq) + } + if got.Reasoning != "" { + t.Errorf(`absent reasoning must stay empty, got %q`, got.Reasoning) + } +} + +// TestSCAMissingInformationIgnoresAbsentFields pins that a missing_information +// entry with no usable text is not fabricated from nil (which fmt.Sprint would +// render as ""). +func TestSCAMissingInformationIgnoresAbsentFields(t *testing.T) { + mdl := &stubJSONModel{value: map[string]any{ + "is_sufficient": false, + "claims": []any{ + map[string]any{"claim_id": "c1", "grounded": false, "missing_information": []any{ + map[string]any{}, // both what/search_hint absent + nil, // nil element + map[string]any{"what": "the year"}, + }}, + }, + }} + got := SufficientContextAgent(context.Background(), SCADeps{ + KB: &harness.Kbinfos{}, + Model: mdl, + }, "q", []ClaimDraft{{ID: "c1", Draft: "d"}}) + mi := got.Claims["c1"].MissingInformation + if len(mi) != 1 || mi[0].What != "the year" || mi[0].SearchHint != "" { + t.Fatalf("missing_information = %+v, want only the real entry", mi) + } +} + +// TestRenderOverallDraftTruncatesByRune pins that the cap is applied by code +// point (Python's str[:N]), never mid-rune: a byte slice through a CJK rune +// would put invalid UTF-8 into the SCA prompt. +func TestRenderOverallDraftTruncatesByRune(t *testing.T) { + draft := strings.Repeat("中", scaClaimsContextMax+50) + got := renderOverallDraft([]ClaimDraft{{ID: "c1", Draft: draft}}) + if !utf8.ValidString(got) { + t.Errorf("truncated draft is not valid UTF-8: %q", got) + } + if n := utf8.RuneCountInString(got); n != scaClaimsContextMax { + t.Errorf("truncated draft has %d runes, want %d", n, scaClaimsContextMax) + } +} + +// TestRenderClaimContextBudgetIsRuneBased pins that the claim-context budget is +// counted in code points (Python's len(str)), not bytes: two CJK blocks of 20k +// runes are ~40k runes (under the 48k cap) but ~120KB bytes (far over it), so a +// byte budget would stop after the FIRST block and silently starve the SCA. +func TestRenderClaimContextBudgetIsRuneBased(t *testing.T) { + draft := strings.Repeat("中", 20000) + got := renderClaimContext([]ClaimDraft{ + {ID: "c1", Draft: draft}, + {ID: "c2", Draft: draft}, + }, &harness.Kbinfos{}) + if !strings.Contains(got, "Claim c1") || !strings.Contains(got, "Claim c2") { + t.Errorf("rune-based budget must keep both CJK blocks; got %d runes", utf8.RuneCountInString(got)) + } +} + +// TestRenderClaimContextTrimsOversizedBlock pins that the cap bounds the RENDERED +// context: a single claim longer than scaClaimsContextMax must be trimmed to the +// budget instead of being appended whole (which pushed the SCA prompt past the +// window the cap was sized for). +func TestRenderClaimContextTrimsOversizedBlock(t *testing.T) { + got := renderClaimContext([]ClaimDraft{ + {ID: "c1", Draft: strings.Repeat("中", scaClaimsContextMax+5000)}, + }, &harness.Kbinfos{}) + if !utf8.ValidString(got) { + t.Error("trimmed block is not valid UTF-8") + } + if n := utf8.RuneCountInString(got); n != scaClaimsContextMax { + t.Errorf("rendered context = %d runes, want it capped at %d", n, scaClaimsContextMax) + } +} diff --git a/internal/rag/advanced_rag/harness/tool_compiled_expansion.go b/internal/rag/advanced_rag/harness/tool_compiled_expansion.go index ff370c54d41..cebae3a4276 100644 --- a/internal/rag/advanced_rag/harness/tool_compiled_expansion.go +++ b/internal/rag/advanced_rag/harness/tool_compiled_expansion.go @@ -19,6 +19,7 @@ package harness import ( "context" "encoding/json" + "fmt" "math" "sort" "strings" @@ -154,11 +155,19 @@ func NewCompiledExpander(store CompiledStore, cfg CompiledScopeConfig) CompiledE // the three synthesis-page expansions (wiki_page / artifact_page / essence) — // each capped at max_chunks=5 — then re-sorts the whole kbinfos["chunks"] by // similarity so compiled chunks blend by relevance with the regular ones. +// +// A doc-tenant resolution failure aborts the expansion and is returned rather +// than swallowed: Python's per-doc lookup raises out of _expand_with_compiled +// (compiled_expansion.py:224) and the caller reports it (tool_search.go, +// "compiled expansion failed") while the already-retrieved chunks stay in place. func (e *compiledExpander) Expand(ctx context.Context, kb *Kbinfos, query, keywords string, docScope []string) error { if e == nil || e.store == nil || kb == nil { return nil } - before := len(kb.Chunks) + // Counted from what was actually pooled, not from a len(before)/len(after) + // delta: another session's appends land in the same pool and would be + // counted here as this expansion's contribution. + expanded := 0 seen := make(map[string]bool, len(kb.Chunks)) for _, c := range kb.Chunks { if id := ChunkIDOf(c); id != "" { @@ -170,44 +179,71 @@ func (e *compiledExpander) Expand(ctx context.Context, kb *Kbinfos, query, keywo match = strings.TrimSpace(keywords) } + // Admit one expansion batch. UNCAPPED, like Python's expansion (it appends + // straight to kbinfos, which is what pushes the pool past _EVIDENCE_POOL_CAP), + // but under the pool lock and deduped against the LIVE pool — the per-call + // `seen` snapshot it is also gated on cannot see a concurrent session's + // appends. Returns how many chunks were actually new. + admitExpansion := func(chunks []map[string]any) int { + added := 0 + kb.Admit(func(p *PoolAdmitter) { + for _, c := range chunks { + if p.Add(c) { + added++ + } + } + }) + expanded += added + return added + } + scopes := e.kgScopes(docScope) for _, sc := range scopes { // 1-hop entity-graph expansion, per template kind (Python L71-89): // compile_kwd empty, template_kind selects the template. for _, tk := range compiledEntityKinds { - chunks := e.expandCompiledStrategy(ctx, sc, match, seen, "", tk.kind, 5) - if len(chunks) > 0 { - kb.Chunks = append(kb.Chunks, chunks...) - _LOG.Printf("[Compiled expand] %s: +%d chunks", tk.label, len(chunks)) + chunks, err := e.expandCompiledStrategy(ctx, sc, match, seen, "", tk.kind, 5) + if err != nil { + return err + } + if n := admitExpansion(chunks); n > 0 { + _LOG.Printf("[Compiled expand] %s: +%d chunks", tk.label, n) } } // Tree structure graph, selected by compile_kwd (Python L91-104): // template_kind empty, compile_kwd="tree". - chunks := e.expandCompiledStrategy(ctx, sc, match, seen, "tree", "", 5) - if len(chunks) > 0 { - kb.Chunks = append(kb.Chunks, chunks...) - _LOG.Printf("[Compiled expand] tree: +%d chunks", len(chunks)) + chunks, err := e.expandCompiledStrategy(ctx, sc, match, seen, "tree", "", 5) + if err != nil { + return err + } + if n := admitExpansion(chunks); n > 0 { + _LOG.Printf("[Compiled expand] tree: +%d chunks", n) } // Synthesis pages — standalone rendered articles, searched directly // (Python L106-125). for _, ck := range compiledSynthesisKinds { - chunks := e.expandWikiPageStrategy(ctx, sc, match, seen, ck.kind, 5) - if len(chunks) > 0 { - kb.Chunks = append(kb.Chunks, chunks...) - _LOG.Printf("[Compiled expand] %s: +%d chunks", ck.label, len(chunks)) + chunks, err := e.expandWikiPageStrategy(ctx, sc, match, seen, ck.kind, 5) + if err != nil { + return err + } + if n := admitExpansion(chunks); n > 0 { + _LOG.Printf("[Compiled expand] %s: +%d chunks", ck.label, n) } } } // Re-sort so compiled-expansion chunks blend by similarity with regular ones - // (Python L127-130). - if len(kb.Chunks) > 0 { - sort.SliceStable(kb.Chunks, func(i, j int) bool { - return similarityOf(kb.Chunks[i]) > similarityOf(kb.Chunks[j]) - }) - } + // (Python L127-130). Under the pool lock: this PERMUTES the shared slice, so + // it must not run while another session reads or appends it. + kb.Admit(func(*PoolAdmitter) { + if len(kb.Chunks) > 0 { + sort.SliceStable(kb.Chunks, func(i, j int) bool { + return similarityOf(kb.Chunks[i]) > similarityOf(kb.Chunks[j]) + }) + } + }) - _LOG.Printf("[Hybrid search] Compiled expansion added %d chunks.", len(kb.Chunks)-before) + _LOG.Printf("[Hybrid search] Compiled expansion added %d chunks.", expanded) return nil } @@ -237,6 +273,10 @@ func (e *compiledExpander) kgScopes(docScope []string) []compiledScope { func (e *compiledExpander) searchCompiledRows(ctx context.Context, sc compiledScope, matchText string, topN int, filters map[string][]string) []map[string]any { rows, err := e.store.SearchCompiled(ctx, sc.kbID, sc.tenantID, sc.docIDs, filters, matchText, topN) if err != nil { + // Python logs the failed search and carries on with no rows + // (compiled_expansion.py:211): the expansion is an enrichment, so a + // missing compiled leg must not fail the regular retrieval. + _LOG.Printf("[Compiled expand] compiled-row search failed (kb=%s tenant=%s); treating as no rows: %v", sc.kbID, sc.tenantID, err) return nil } return rows @@ -247,11 +287,11 @@ func (e *compiledExpander) searchCompiledRows(ctx context.Context, sc compiledSc // hop 1-hop through adjacent relations (forward + backward), collect neighbour // entity names, look up their source_chunk_ids by exact name_kwd, then load the // referenced source chunks, deduped and capped at maxChunks. -func (e *compiledExpander) expandCompiledStrategy(ctx context.Context, sc compiledScope, match string, seen map[string]bool, compileKwd, templateKwd string, maxChunks int) []map[string]any { +func (e *compiledExpander) expandCompiledStrategy(ctx context.Context, sc compiledScope, match string, seen map[string]bool, compileKwd, templateKwd string, maxChunks int) ([]map[string]any, error) { // -- 1. Seed entities (embedding match, top 5) -- seedRows := e.searchCompiledRows(ctx, sc, match, 5, seedFilters("entity", compileKwd, templateKwd)) if len(seedRows) == 0 { - return nil + return nil, nil } seedNames := make(map[string]bool) for _, r := range seedRows { @@ -260,7 +300,7 @@ func (e *compiledExpander) expandCompiledStrategy(ctx context.Context, sc compil } } if len(seedNames) == 0 { - return nil + return nil, nil } // -- 2. Adjacent relations (outgoing + incoming), top 50 each -- @@ -296,7 +336,7 @@ func (e *compiledExpander) expandCompiledStrategy(ctx context.Context, sc compil } } if len(neighbourNames) == 0 { - return nil + return nil, nil } // -- 4. Neighbour entity source_chunk_ids (exact name_kwd lookup) -- @@ -330,11 +370,11 @@ func (e *compiledExpander) expandCompiledStrategy(ctx context.Context, sc compil // synthesis-compiled pages of one compile_kwd directly, collect their // source_chunk_ids, then load the referenced source chunks. Pages rank high, so // each loaded chunk is assigned similarity=0.9 unless it already carries one. -func (e *compiledExpander) expandWikiPageStrategy(ctx context.Context, sc compiledScope, match string, seen map[string]bool, compileKwd string, maxChunks int) []map[string]any { +func (e *compiledExpander) expandWikiPageStrategy(ctx context.Context, sc compiledScope, match string, seen map[string]bool, compileKwd string, maxChunks int) ([]map[string]any, error) { // -- 1. Search synthesis pages (no knowledge_graph_kwd filter) -- rows := e.searchSynthesisPages(ctx, sc, match, compileKwd, 5) if len(rows) == 0 { - return nil + return nil, nil } // -- 2. Collect source_chunk_ids from matching pages -- @@ -353,17 +393,20 @@ func (e *compiledExpander) expandWikiPageStrategy(ctx context.Context, sc compil } } if len(order) == 0 { - return nil + return nil, nil } // -- 3. Load chunks, assign high similarity for priority ranking -- - loaded := e.loadByDoc(ctx, sc, order, byDoc, seen, maxChunks) + loaded, err := e.loadByDoc(ctx, sc, order, byDoc, seen, maxChunks) + if err != nil { + return nil, err + } for _, c := range loaded { if _, has := c["similarity"]; !has { c["similarity"] = 0.9 // wiki pages rank high } } - return loaded + return loaded, nil } // searchSynthesisPages mirrors Python _search_synthesis_pages: find synthesis @@ -381,7 +424,11 @@ func (e *compiledExpander) searchSynthesisPages(ctx context.Context, sc compiled // global maxChunks cap and the seen-id dedup set. Returns newly added chunks in // doc order. Mirrors Python's per-doc _load_chunks_for_doc loop and its // max_chunks break/limit accounting. -func (e *compiledExpander) loadByDoc(ctx context.Context, sc compiledScope, order []string, byDoc map[string][]string, seen map[string]bool, maxChunks int) []map[string]any { +// +// A doc whose owner cannot be resolved is dropped (the documented per-row rule), +// but a doc-tenant resolution FAILURE is returned: it is a transport/database +// error, not "no row resolved", and Python surfaces it as an exception. +func (e *compiledExpander) loadByDoc(ctx context.Context, sc compiledScope, order []string, byDoc map[string][]string, seen map[string]bool, maxChunks int) ([]map[string]any, error) { // Python _load_chunks_for_doc resolves EACH row's doc_id to its owning // (kb, tenant) — not the searched scope — and loads nothing when that // resolution fails (merged dataset rows carry a pseudo/empty doc_id). Loading @@ -395,9 +442,16 @@ func (e *compiledExpander) loadByDoc(ctx context.Context, sc compiledScope, orde ids = append(ids, docID) } } - if resolved, err := e.cfg.DocTenantResolver.ResolveDocTenants(ctx, ids); err == nil { - owners = resolved + resolved, err := e.cfg.DocTenantResolver.ResolveDocTenants(ctx, ids) + if err != nil { + // Python resolves one doc at a time and lets a lookup failure raise out + // of _load_chunks_for_doc (compiled_expansion.py:224): nothing is + // loaded, and the failure is loud. Return it so the caller reports it + // instead of letting a transport error masquerade as the documented + // per-row drop below. + return nil, fmt.Errorf("doc-tenant resolution failed for %d doc(s): %w", len(ids), err) } + owners = resolved } var out []map[string]any for _, docID := range order { @@ -419,6 +473,9 @@ func (e *compiledExpander) loadByDoc(ctx context.Context, sc compiledScope, orde } rows, err := e.store.LoadChunks(ctx, kbID, tenantID, cids) if err != nil { + // Python logs the failed load per doc (compiled_expansion.py:248) and + // drops only that doc; the remaining docs still load. + _LOG.Printf("[Compiled expand] failed to load chunks for doc_id=%s: %v", docID, err) continue } for _, c := range rows { @@ -430,7 +487,7 @@ func (e *compiledExpander) loadByDoc(ctx context.Context, sc compiledScope, orde out = append(out, c) } } - return out + return out, nil } // seedNameFromRow mirrors Python L293-300: parse content_with_weight as JSON and diff --git a/internal/rag/advanced_rag/harness/tool_compiled_expansion_test.go b/internal/rag/advanced_rag/harness/tool_compiled_expansion_test.go index abe22301375..46c5748eee3 100644 --- a/internal/rag/advanced_rag/harness/tool_compiled_expansion_test.go +++ b/internal/rag/advanced_rag/harness/tool_compiled_expansion_test.go @@ -17,7 +17,10 @@ package harness import ( + "bytes" "context" + "errors" + "log" "strings" "testing" @@ -36,6 +39,9 @@ import ( type stubCompiledStore struct { rows []map[string]any chunks map[string]string + // loadErrByChunk makes LoadChunks fail when one of the requested ids is + // listed, standing in for a per-doc store error. + loadErrByChunk map[string]error } func (s *stubCompiledStore) SearchCompiled(_ context.Context, _, _ string, _ []string, filters map[string][]string, matchText string, topN int) ([]map[string]any, error) { @@ -59,6 +65,11 @@ func (s *stubCompiledStore) SearchCompiled(_ context.Context, _, _ string, _ []s } func (s *stubCompiledStore) LoadChunks(_ context.Context, _, _ string, chunkIDs []string) ([]map[string]any, error) { + for _, id := range chunkIDs { + if err, ok := s.loadErrByChunk[id]; ok { + return nil, err + } + } var out []map[string]any for _, id := range chunkIDs { if content, ok := s.chunks[id]; ok { @@ -429,3 +440,111 @@ func TestExpandCapsMaxChunksAndSkipsSeen(t *testing.T) { } } } + +// mapTenantResolver resolves each doc id to its own owner and can fail the whole +// batch, standing in for the batched DB lookup (a per-doc lookup in Python). +type mapTenantResolver struct { + owners map[string]DocTenant + err error +} + +func (m mapTenantResolver) ResolveDocTenants(_ context.Context, docIDs []string) (map[string]DocTenant, error) { + if m.err != nil { + return nil, m.err + } + out := make(map[string]DocTenant, len(docIDs)) + for _, d := range docIDs { + if o, ok := m.owners[d]; ok { + out[d] = o + } + } + return out, nil +} + +// TestCompiledExpanderReportsDocTenantResolutionFailure pins the two rules apart: +// a row whose owner cannot be resolved is dropped silently (see the test above), +// but a FAILED batched lookup is a transport error — Python lets it raise out of +// _load_chunks_for_doc, so nothing is loaded and the failure is reported instead +// of masquerading as "no row resolved". +func TestCompiledExpanderReportsDocTenantResolutionFailure(t *testing.T) { + store := &ownerRecordingStore{stubCompiledStore: &stubCompiledStore{ + rows: []map[string]any{ + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "Culdcept", "content_with_weight": `{"name":"Culdcept"}`, "doc_id": "seedDoc"}, + {"knowledge_graph_kwd": "relation", "compilation_template_kind_kwd": "knowledge_graph", + "from_entity_kwd": "Culdcept", "to_entity_kwd": "OmiyaSoft", "doc_id": "seedDoc"}, + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "OmiyaSoft", "content_with_weight": `{"name":"OmiyaSoft"}`, + "source_chunk_ids": []string{"s1"}, "doc_id": "docA"}, + }, + chunks: map[string]string{"s1": "a"}, + }} + exp := NewCompiledExpander(store, CompiledScopeConfig{ + DatasetIDs: []string{"kb1"}, + TenantID: "t1", + KBs: []*entity.Knowledgebase{{ID: "kb1", TenantID: "t1"}}, + DocTenantResolver: mapTenantResolver{err: errors.New("db unavailable")}, + }).(*compiledExpander) + + kb := &Kbinfos{} + err := exp.Expand(context.Background(), kb, "culdcept", "", nil) + if err == nil { + t.Fatal("Expand must report the resolver failure instead of silently loading nothing") + } + if !strings.Contains(err.Error(), "doc-tenant resolution failed for 1 doc(s)") { + t.Errorf("error = %q, want it to name the failed batch and its size", err) + } + if len(store.loads) != 0 { + t.Errorf("LoadChunks calls = %+v, want none after a resolver failure", store.loads) + } + if len(kb.Chunks) != 0 { + t.Errorf("chunks = %v, want none", compiledIDs(kb.Chunks)) + } +} + +// TestCompiledExpanderLogsAndKeepsOtherDocsWhenOneLoadFails mirrors Python's +// per-doc load: the failing doc is logged (compiled_expansion.py:248) and +// dropped, while the remaining docs still contribute. +func TestCompiledExpanderLogsAndKeepsOtherDocsWhenOneLoadFails(t *testing.T) { + var buf bytes.Buffer + prevLog := _LOG + _LOG = log.New(&buf, "", 0) + t.Cleanup(func() { _LOG = prevLog }) + + store := &ownerRecordingStore{stubCompiledStore: &stubCompiledStore{ + rows: []map[string]any{ + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "Culdcept", "content_with_weight": `{"name":"Culdcept"}`, "doc_id": "seedDoc"}, + {"knowledge_graph_kwd": "relation", "compilation_template_kind_kwd": "knowledge_graph", + "from_entity_kwd": "Culdcept", "to_entity_kwd": "OmiyaSoft", "doc_id": "seedDoc"}, + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "OmiyaSoft", "content_with_weight": `{"name":"OmiyaSoft"}`, + "source_chunk_ids": []string{"s1"}, "doc_id": "docA"}, + {"knowledge_graph_kwd": "entity", "compilation_template_kind_kwd": "knowledge_graph", + "name_kwd": "OmiyaSoft", "content_with_weight": `{"name":"OmiyaSoft"}`, + "source_chunk_ids": []string{"s2"}, "doc_id": "docB"}, + }, + chunks: map[string]string{"s1": "a", "s2": "b"}, + loadErrByChunk: map[string]error{"s1": errors.New("store unavailable")}, + }} + exp := NewCompiledExpander(store, CompiledScopeConfig{ + DatasetIDs: []string{"kb1"}, + TenantID: "t1", + KBs: []*entity.Knowledgebase{{ID: "kb1", TenantID: "t1"}}, + DocTenantResolver: mapTenantResolver{owners: map[string]DocTenant{ + "docA": {KBID: "kbA", TenantID: "tA"}, + "docB": {KBID: "kbB", TenantID: "tB"}, + }}, + }).(*compiledExpander) + + kb := &Kbinfos{} + if err := exp.Expand(context.Background(), kb, "culdcept", "", nil); err != nil { + t.Fatalf("Expand: %v", err) + } + if got := compiledIDs(kb.Chunks); len(got) != 1 || got[0] != "s2" { + t.Errorf("expanded = %v, want only s2 (docA's load failed)", got) + } + if !strings.Contains(buf.String(), "failed to load chunks for doc_id=docA") { + t.Errorf("log = %q, want the failing doc named", buf.String()) + } +} diff --git a/internal/rag/advanced_rag/harness/tool_executor.go b/internal/rag/advanced_rag/harness/tool_executor.go index 502361baf92..36bde2d7b8d 100644 --- a/internal/rag/advanced_rag/harness/tool_executor.go +++ b/internal/rag/advanced_rag/harness/tool_executor.go @@ -333,7 +333,7 @@ func (e *searchExecutor) navigateTree(ctx context.Context, args map[string]any) // It stays in the harness package because it depends on the agentic Retriever / // RetrieveRequest; the routing algorithm itself lives in internal/service/nav. func chunkAggRetrieveFrom(r Retriever) nav.ChunkRetriever { - return func(ctx context.Context, tenantID, kbID, query string, docScope []string, topN int, _ float64) []map[string]any { + return func(ctx context.Context, tenantID, kbID, query string, docScope []string, topN int, _ float64) ([]map[string]any, error) { chunks, err := r.Retrieve(ctx, RetrieveRequest{ Query: query, DatasetIDs: []string{kbID}, @@ -341,10 +341,13 @@ func chunkAggRetrieveFrom(r Retriever) nav.ChunkRetriever { DocScope: docScope, TopN: topN, }) - if err != nil || len(chunks) == 0 { - return nil + if err != nil { + // Surface the failure instead of folding it into an empty result: + // the router reports it as an error so the orchestrator takes its + // fallback rather than telling the model the tree routed nothing. + return nil, err } - return chunks + return chunks, nil } } @@ -502,6 +505,17 @@ func argString(args map[string]any, key string) string { return s } +// evidencePoolCap is the hard cap on the shared evidence pool +// (kbinfos["chunks"]). Mirrors Python _EVIDENCE_POOL_CAP (=60, the same ceiling +// as _MAX_SNIPPET_POOL / _SCA_VIEW_CAP): once the pool is saturated, further +// admits cannot reach the SCA view or improve the answer, so the action session +// stops admitting chunks (observed pools otherwise grew to ~106). +const evidencePoolCap = 60 + +// The cap check and its "pool FULL" line now live on PoolAdmitter.Full, where +// the pool lock is held (see kbinfos.go): the check must not read len(Chunks) +// while another session appends. + // search runs one retrieval call for a tool invocation. // // Python's retrieve/search_chunks both funnel into tools/search.py, differing @@ -549,13 +563,10 @@ func (e *searchExecutor) search(ctx context.Context, name string, args map[strin newChunks := 0 // Per-call admittance state, mirroring Python _run_search/_admit_evidence // (action_session.py:_run_search): `seen` dedups chunks ACROSS the queries of - // this one call; kbSeen holds the shared pool's existing identities - // (Python `kb_seen`). + // this one call. The pool-side dedup is Kbinfos.Admit's job, against the LIVE + // pool — a per-call snapshot of it (Python's `kb_seen`) is exact only while + // nothing can interleave, and another session appending makes it stale. seen := map[string]bool{} - kbSeen := make(map[string]bool, len(e.deps.KB.Chunks)) - for _, c := range e.deps.KB.Chunks { - kbSeen[chunkKey(c)] = true - } for _, q := range queries { // Per-tool top_n (mirrors Python action_session: retrieve=10, // search_chunks=20). They were previously collapsed onto e.req.TopN, @@ -571,10 +582,11 @@ func (e *searchExecutor) search(ctx context.Context, name string, args map[strin // global switch can no longer disable the semantic leg. // // Python's search_chunks tool ALWAYS enables compiled-structure expansion - // (action_session.py:execute_tool passes use_compiled=True); retrieve/grep_search - // never do. So Go mirrors that: compiled is on for search_chunks and off - // for every other retrieve-family tool, independent of e.req.UseCompiled - // (which gates the L1 direct retrieve, not the action_session tool loop). + // in ALL modes, not just high (action_session.py:execute_tool passes + // use_compiled=True); retrieve/grep_search never do. So Go mirrors that: + // compiled is on for search_chunks and off for every other retrieve-family + // tool, independent of e.req.UseCompiled (which gates the L1 direct + // retrieve, not the action_session tool loop). var searchFn func(context.Context, SearchDeps, SearchParams) ([]map[string]any, []map[string]any) useCompiled := name == "search_chunks" if useCompiled { @@ -627,24 +639,33 @@ func (e *searchExecutor) search(ctx context.Context, name string, args map[strin // id, the chunk ID as the evidence reference (Python's `ids` holds ids, // not pool positions), and only chunks NEW to the shared pool appended // to it — so REDUNDANT means "nothing new", not "nothing returned". - for _, c := range chunks { - cid := ChunkIDOf(c) - if seen[cid] { - continue - } - seen[cid] = true - evidenceIDs = append(evidenceIDs, cid) - payload = append(payload, passageFromChunk(c)) - // Pool identity uses chunkKey (Go's stable key): Python's _chunk_key - // falls back to id(ck) — the dict's address — so an equivalent - // re-retrieved chunk never matches and is appended again. - key := chunkKey(c) - if !kbSeen[key] { - kbSeen[key] = true - e.deps.KB.Chunks = append(e.deps.KB.Chunks, c) - newChunks++ + // + // ONE query's batch is one critical section: Python's per-query loop has + // no await (the awaits sit in the outer query loop, :691-700), so asyncio + // cannot interleave two sessions' batches. Locking per chunk would let + // them interleave into pool orders Python can never produce. + e.deps.KB.Admit(func(p *PoolAdmitter) { + for _, c := range chunks { + // Python _admit_evidence early-stops at the top once the shared pool + // reaches the cap, BEFORE the per-call dedup. + if p.Full() { + continue + } + cid := ChunkIDOf(c) + if seen[cid] { + continue + } + seen[cid] = true + evidenceIDs = append(evidenceIDs, cid) + payload = append(payload, passageFromChunk(c)) + // Pool identity uses chunkKey (Go's stable key): Python's _chunk_key + // falls back to id(ck) — the dict's address — so an equivalent + // re-retrieved chunk never matches and is appended again. + if p.Add(c) { + newChunks++ + } } - } + }) // Pool this search's doc_aggs (skipped when it returned no chunks, like // _merge_kbinfos). e.deps.KB.MergeDocAggs(aggs) @@ -920,14 +941,18 @@ type RuntimeRetriever struct{} func (r *RuntimeRetriever) Retrieve(ctx context.Context, req RetrieveRequest) ([]map[string]any, error) { svc := runtime.GetRetrievalService() chunks, err := svc.Search(ctx, nil, runtime.RetrievalRequest{ - Query: req.Query, - DatasetIDs: req.DatasetIDs, - DocScope: req.DocScope, - TopN: req.TopN, - TopK: req.TopK, - RerankCandidatesCount: req.RerankCandidatesCount, - SimilarityThreshold: &req.SimilarityThreshold, - KeywordsSimilarityWeight: &req.KeywordsSimilarityWeight, + Query: req.Query, + DatasetIDs: req.DatasetIDs, + DocScope: req.DocScope, + TopN: req.TopN, + TopK: req.TopK, + RerankCandidatesCount: req.RerankCandidatesCount, + // Passed through as pointers: nil (the caller did not supply one) must + // stay nil so the retrieval service keeps its own default, while a zero + // is a real override. Taking the address of a zero value here forced + // "threshold 0 / full vector weight" onto every caller that omitted them. + SimilarityThreshold: req.SimilarityThreshold, + KeywordsSimilarityWeight: req.KeywordsSimilarityWeight, TenantID: req.TenantID, RankFeature: req.RankFeature, // ExcludeCompiled maps Python hybrid_search's diff --git a/internal/rag/advanced_rag/harness/tool_executor_test.go b/internal/rag/advanced_rag/harness/tool_executor_test.go index 2af207ce097..50e93107a10 100644 --- a/internal/rag/advanced_rag/harness/tool_executor_test.go +++ b/internal/rag/advanced_rag/harness/tool_executor_test.go @@ -17,6 +17,7 @@ package harness import ( "bytes" "context" + "errors" "fmt" "log" "strings" @@ -28,12 +29,17 @@ import ( ) // stubRetrievalService returns a fixed set of child chunks so the harness -// retireval path can be exercised without a live search backend. +// retireval path can be exercised without a live search backend. lastReq, when +// set, receives the request the harness handed down. type stubRetrievalService struct { - chunks []runtime.RetrievalChunk + chunks []runtime.RetrievalChunk + lastReq *runtime.RetrievalRequest } -func (s stubRetrievalService) Search(_ context.Context, _ *gorm.DB, _ runtime.RetrievalRequest) ([]runtime.RetrievalChunk, error) { +func (s stubRetrievalService) Search(_ context.Context, _ *gorm.DB, req runtime.RetrievalRequest) ([]runtime.RetrievalChunk, error) { + if s.lastReq != nil { + *s.lastReq = req + } return s.chunks, nil } @@ -52,6 +58,78 @@ func (s stubDocEngine) GetChunk(_ context.Context, _, chunkID string, _ []string return nil, fmt.Errorf("parent %s not found", chunkID) } +// TestRuntimeRetrieverPreservesUnsetControls pins the presence semantics of the +// retrieval controls: an omitted threshold/weight must reach the retrieval +// service as nil so it keeps its own default, while an explicit zero is a real +// override. Taking the address of a zero value used to force "no threshold +// floor + the vector leg at full weight" onto every caller that omitted them. +func TestRuntimeRetrieverPreservesUnsetControls(t *testing.T) { + prev := runtime.GetRetrievalService() + var got runtime.RetrievalRequest + runtime.SetRetrievalService(stubRetrievalService{lastReq: &got}) + t.Cleanup(func() { runtime.SetRetrievalService(prev) }) + + r := &RuntimeRetriever{} + if _, err := r.Retrieve(context.Background(), RetrieveRequest{Query: "q", DatasetIDs: []string{"kb-1"}}); err != nil { + t.Fatalf("Retrieve: %v", err) + } + if got.SimilarityThreshold != nil || got.KeywordsSimilarityWeight != nil { + t.Errorf("omitted controls = %v / %v, want nil so the service keeps its defaults", + got.SimilarityThreshold, got.KeywordsSimilarityWeight) + } + + threshold, weight := 0.35, 0.3 + if _, err := r.Retrieve(context.Background(), RetrieveRequest{ + Query: "q", + SimilarityThreshold: &threshold, + KeywordsSimilarityWeight: &weight, + }); err != nil { + t.Fatalf("Retrieve: %v", err) + } + if got.SimilarityThreshold == nil || *got.SimilarityThreshold != threshold { + t.Errorf("SimilarityThreshold = %v, want %v", got.SimilarityThreshold, threshold) + } + if got.KeywordsSimilarityWeight == nil || *got.KeywordsSimilarityWeight != weight { + t.Errorf("KeywordsSimilarityWeight = %v, want %v", got.KeywordsSimilarityWeight, weight) + } +} + +// TestChunkAggRetrieveLeavesControlsUnset pins the caller side: the chunk-agg +// retriever has no threshold/weight of its own, so it must omit both rather +// than pass zero overrides. +func TestChunkAggRetrieveLeavesControlsUnset(t *testing.T) { + r := &stubRetriever{chunks: []map[string]any{{"chunk_id": "c1"}}} + + chunks, err := chunkAggRetrieveFrom(r)(context.Background(), "t1", "kb-1", "q", nil, 5, 0.9) + if err != nil { + t.Fatalf("chunkAggRetrieveFrom: %v", err) + } + if len(chunks) != 1 { + t.Fatalf("chunks = %d, want the retrieved chunk", len(chunks)) + } + req := r.lastReq(t) + if req.SimilarityThreshold != nil || req.KeywordsSimilarityWeight != nil { + t.Errorf("controls = %v / %v, want nil (zero is a valid value, not an unset marker)", + req.SimilarityThreshold, req.KeywordsSimilarityWeight) + } +} + +// TestChunkAggRetrievePropagatesError pins the adapter half of the router +// contract: a retrieval failure must reach the router as an error, not as an +// empty chunk list (which the router would report as a successful empty route). +func TestChunkAggRetrievePropagatesError(t *testing.T) { + wantErr := errors.New("retrieval down") + r := &stubRetriever{err: wantErr} + + chunks, err := chunkAggRetrieveFrom(r)(context.Background(), "t1", "kb-1", "q", nil, 5, 0.9) + if !errors.Is(err, wantErr) { + t.Fatalf("err = %v, want %v", err, wantErr) + } + if chunks != nil { + t.Errorf("chunks = %v, want nil alongside the error", chunks) + } +} + // TestRuntimeRetrieverPromotesChildrenToParent verifies that // RuntimeRetriever.Retrieve threads child chunks through retrieval_by_children: // two child fragments sharing a mom_id collapse into the single parent chunk, @@ -343,6 +421,39 @@ func TestListChunksCapsDeepReadAndOutput(t *testing.T) { } } +// TestEvidencePoolCapStopsAdmitting pins the PR's _EVIDENCE_POOL_CAP early-stop: +// once the shared pool reaches the cap, a search admits no further chunk, so its +// outcome collapses to MISS (nothing new was admitted) — a saturated session +// stops bloating the pool beyond what the SCA view can read. +func TestEvidencePoolCapStopsAdmitting(t *testing.T) { + pre := make([]map[string]any, 0, evidencePoolCap) + for i := 0; i < evidencePoolCap; i++ { + pre = append(pre, map[string]any{"chunk_id": fmt.Sprintf("pre-%d", i), "content": "old"}) + } + deps, kb := newTestSearchDeps(&stubRetriever{chunks: []map[string]any{{"content": "hit", "chunk_id": "c1"}}}) + kb.Chunks = pre + ex := NewSearchExecutor(deps, RunRequest{DatasetIDs: []string{"kb1"}}) + oc, err := ex.Execute(context.Background(), "retrieve", map[string]any{"query": "q"}) + if err != nil { + t.Fatalf("retrieve: %v", err) + } + if oc.Status != StatusMiss { + t.Errorf("status = %s, want %s (a full pool admits nothing)", oc.Status, StatusMiss) + } + if len(kb.Chunks) != evidencePoolCap { + t.Errorf("kb.Chunks = %d, want the pool to stay at the cap %d", len(kb.Chunks), evidencePoolCap) + } + // Dropping one chunk frees a slot and admission resumes. + kb.Chunks = kb.Chunks[:evidencePoolCap-1] + oc, err = ex.Execute(context.Background(), "retrieve", map[string]any{"query": "q"}) + if err != nil { + t.Fatalf("retrieve after freeing a slot: %v", err) + } + if oc.Status != StatusOK { + t.Errorf("status after freeing a slot = %s, want %s", oc.Status, StatusOK) + } +} + // TestWebSearchAdmitsToPool pins the web_search parity fix: web results merge // into the SAME shared evidence pool as corpus hits (Python _exec_web_search → // _admit_evidence), so downstream formalize/compose can cite them, and the diff --git a/internal/rag/advanced_rag/harness/tool_exploration.go b/internal/rag/advanced_rag/harness/tool_exploration.go index 00502a58bf4..0359def2231 100644 --- a/internal/rag/advanced_rag/harness/tool_exploration.go +++ b/internal/rag/advanced_rag/harness/tool_exploration.go @@ -357,6 +357,11 @@ func resolveKGScope(deps SearchDeps, docScope, datasetIDs []string) []kgScope { key := DocTenant{KBID: owner.KBID, TenantID: owner.TenantID} byOwner[key] = append(byOwner[key], docID) } + } else { + // Python's per-doc lookup raises here (exploration.py:68); Go degrades + // to the bound datasets below, so the lost owner grouping must not be + // silent. + _LOG.Printf("[Graph explore] doc-tenant resolution failed for %d doc(s); falling back to the bound datasets: %v", len(docScope), err) } } @@ -463,7 +468,7 @@ func ExploreGraph(ctx context.Context, deps SearchDeps, tenantID string, dataset // (1) Seeds: dense KNN (similarity>=_KG_SEED_SIM) over the scoped entity // rows, re-ranked by mention_count_int desc; falls back to keyword match // when the embedding model is unavailable. - seedRows := kgSeedSearch(ctx, de, sc.TenantID, sc.KBID, sc.Docs, text, scopeKwd, seedVec) + seedRows := kgSeedSearch(ctx, de, sc.TenantID, sc.KBID, sc.Docs, text, scopeKwd, seedVec, deps.IndexName) var seeds []kgEntity for _, r := range seedRows { if e, ok := kgParseEntity(r); ok { @@ -479,9 +484,9 @@ func ExploreGraph(ctx context.Context, deps SearchDeps, tenantID string, dataset } terms := endpointTerms(frontier) relRows := kgSearch(ctx, de, sc.TenantID, sc.KBID, sc.Docs, "relation", "", kgRelLimit, scopeKwd, - map[string]interface{}{"from_entity_kwd": terms}, "", 0) + map[string]interface{}{"from_entity_kwd": terms}, "", 0, deps.IndexName) relRows = append(relRows, kgSearch(ctx, de, sc.TenantID, sc.KBID, sc.Docs, "relation", "", kgRelLimit, scopeKwd, - map[string]interface{}{"to_entity_kwd": terms}, "", 0)...) + map[string]interface{}{"to_entity_kwd": terms}, "", 0, deps.IndexName)...) // Dedup keys: Python keeps a relation unless its source row id is // already seen (rel_rows is a dict keyed by row id), so the same // endpoint pair from *different* rows survives. Mirror that: prefer @@ -535,7 +540,7 @@ func ExploreGraph(ctx context.Context, deps SearchDeps, tenantID string, dataset limit = len(neighFiltered) } neighRows := kgSearch(ctx, de, sc.TenantID, sc.KBID, sc.Docs, "entity", "", limit, scopeKwd, - map[string]interface{}{"name_kwd": endpointTerms(neighFiltered)}, "", 0) + map[string]interface{}{"name_kwd": endpointTerms(neighFiltered)}, "", 0, deps.IndexName) var neighbours []kgEntity for _, r := range neighRows { if e, ok := kgParseEntity(r); ok { @@ -674,8 +679,9 @@ func defaultSeedEncoder(ctx context.Context, tenantID, text string) []float64 { // kgSeedSearch searches the compiled KG entity rows for seeds (mirrors Python // _kg_search dense branch): dense KNN over name_kwd with similarity>=0.8, // re-ranked by mention_count_int desc, top kgSeeds. Falls back to keyword match -// when seedVec is nil (embedding model unavailable). -func kgSeedSearch(ctx context.Context, de engine.DocEngine, tenantID, kbID string, docIDs []string, text, scopeKwd string, seedVec []float64) []map[string]interface{} { +// when seedVec is nil (embedding model unavailable). indexName is the caller's +// configured index override (deps.IndexName); empty keeps ragflow_. +func kgSeedSearch(ctx context.Context, de engine.DocEngine, tenantID, kbID string, docIDs []string, text, scopeKwd string, seedVec []float64, indexName string) []map[string]interface{} { if seedVec != nil { dense := &types.MatchDenseExpr{ VectorColumnName: fmt.Sprintf("q_%d_vec", len(seedVec)), @@ -685,11 +691,11 @@ func kgSeedSearch(ctx context.Context, de engine.DocEngine, tenantID, kbID strin TopN: kgSeedPool, ExtraOptions: map[string]interface{}{"similarity": kgSeedSim}, } - rows := kgSearchRaw(ctx, de, tenantID, kbID, docIDs, "entity", scopeKwd, nil, []interface{}{dense}, "mention_count_int", kgSeedPool) + rows := kgSearchRaw(ctx, de, tenantID, kbID, docIDs, "entity", scopeKwd, nil, []interface{}{dense}, "mention_count_int", kgSeedPool, indexName) return topMentionCount(rows, kgSeeds) } // Text fallback (mirrors Python _kg_search `embed_mdl is None` path). - return kgSearch(ctx, de, tenantID, kbID, docIDs, "entity", text, kgSeeds, scopeKwd, nil, "mention_count_int", kgSeedPool) + return kgSearch(ctx, de, tenantID, kbID, docIDs, "entity", text, kgSeeds, scopeKwd, nil, "mention_count_int", kgSeedPool, indexName) } // topMentionCount re-ranks rows by mention_count_int desc and returns topN. @@ -719,8 +725,15 @@ func mentionCount(row map[string]interface{}) int { // kgSearchRaw is the low-level KG row search with explicit match exprs and any // extra filter keys (e.g. from_entity_kwd/to_entity_kwd/name_kwd). -func kgSearchRaw(ctx context.Context, de engine.DocEngine, tenantID, kbID string, docIDs []string, kind, scopeKwd string, extra map[string]interface{}, matchExprs []interface{}, orderDesc string, limit int) []map[string]interface{} { - idx := fmt.Sprintf("ragflow_%s", tenantID) +// +// indexName is the caller's configured index override (deps.IndexName): the KG +// rows are written to the same index the chunk loads read (ExploreGraph loads +// its evidence with indexNameFor(deps.TenantID, deps.IndexName)), so a tenant +// that overrides the name must have it honoured here too — otherwise the walk +// queries one index and loads passages from another. Empty falls back to +// ragflow_, which is what Python's search.index_name always returns. +func kgSearchRaw(ctx context.Context, de engine.DocEngine, tenantID, kbID string, docIDs []string, kind, scopeKwd string, extra map[string]interface{}, matchExprs []interface{}, orderDesc string, limit int, indexName string) []map[string]interface{} { + idx := indexNameFor(tenantID, indexName) condition := map[string]interface{}{"knowledge_graph_kwd": kind} if scopeKwd != "" { condition["scope_kwd"] = scopeKwd @@ -754,7 +767,7 @@ func kgSearchRaw(ctx context.Context, de engine.DocEngine, tenantID, kbID string // kgSearch searches the compiled KG rows of one KB (mirrors Python _kg_search), // using keyword match. It only builds the MatchTextExpr (with the pool-based // TopN) and delegates the request construction to kgSearchRaw. -func kgSearch(ctx context.Context, de engine.DocEngine, tenantID, kbID string, docIDs []string, kind, text string, topN int, scopeKwd string, extra map[string]interface{}, orderDesc string, pool int) []map[string]interface{} { +func kgSearch(ctx context.Context, de engine.DocEngine, tenantID, kbID string, docIDs []string, kind, text string, topN int, scopeKwd string, extra map[string]interface{}, orderDesc string, pool int, indexName string) []map[string]interface{} { var matchExprs []interface{} if text != "" { knnTopN := topN @@ -767,7 +780,7 @@ func kgSearch(ctx context.Context, de engine.DocEngine, tenantID, kbID string, d TopN: knnTopN, }} } - return kgSearchRaw(ctx, de, tenantID, kbID, docIDs, kind, scopeKwd, extra, matchExprs, orderDesc, topN) + return kgSearchRaw(ctx, de, tenantID, kbID, docIDs, kind, scopeKwd, extra, matchExprs, orderDesc, topN, indexName) } func kgParseEntity(row map[string]interface{}) (kgEntity, bool) { diff --git a/internal/rag/advanced_rag/harness/tool_exploration_test.go b/internal/rag/advanced_rag/harness/tool_exploration_test.go new file mode 100644 index 00000000000..fbada281c3c --- /dev/null +++ b/internal/rag/advanced_rag/harness/tool_exploration_test.go @@ -0,0 +1,84 @@ +// +// 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. +// + +package harness + +import ( + "context" + "testing" + + "ragflow/internal/engine" + "ragflow/internal/engine/types" +) + +// kgIndexCapturingEngine records the index names of every search it serves. +type kgIndexCapturingEngine struct { + engine.DocEngine + indexNames []string +} + +func (e *kgIndexCapturingEngine) Search(_ context.Context, req *types.SearchRequest) (*types.SearchResult, error) { + e.indexNames = append(e.indexNames, req.IndexNames...) + return &types.SearchResult{}, nil +} + +// TestKGSearchUsesConfiguredIndexName pins that the knowledge-graph walk searches +// the SAME index the rest of the request reads: ExploreGraph loads its evidence +// with indexNameFor(deps.TenantID, deps.IndexName), so a tenant that overrides +// the index name must have it honoured by the KG rows too. Hardcoding +// ragflow_ made the walk query one index and return passages loaded +// from another. Empty keeps the default, matching Python's search.index_name. +func TestKGSearchUsesConfiguredIndexName(t *testing.T) { + ctx := context.Background() + for _, tc := range []struct { + name string + indexName string + want string + }{ + {"configured override", "custom_idx", "custom_idx"}, + {"default", "", "ragflow_tenantA"}, + } { + t.Run(tc.name, func(t *testing.T) { + for _, call := range []struct { + name string + fn func(de engine.DocEngine) + }{ + {"kgSearchRaw", func(de engine.DocEngine) { + kgSearchRaw(ctx, de, "tenantA", "kb1", nil, "entity", "dataset", nil, nil, "", 5, tc.indexName) + }}, + {"kgSearch", func(de engine.DocEngine) { + kgSearch(ctx, de, "tenantA", "kb1", nil, "entity", "q", 5, "dataset", nil, "", 0, tc.indexName) + }}, + {"kgSeedSearch", func(de engine.DocEngine) { + kgSeedSearch(ctx, de, "tenantA", "kb1", nil, "q", "dataset", nil, tc.indexName) + }}, + } { + t.Run(call.name, func(t *testing.T) { + de := &kgIndexCapturingEngine{} + call.fn(de) + if len(de.indexNames) == 0 { + t.Fatal("no search was issued") + } + for _, got := range de.indexNames { + if got != tc.want { + t.Errorf("index = %q, want %q", got, tc.want) + } + } + }) + } + }) + } +} diff --git a/internal/rag/advanced_rag/harness/tool_navigation.go b/internal/rag/advanced_rag/harness/tool_navigation.go index aae882f6209..3303aac2830 100644 --- a/internal/rag/advanced_rag/harness/tool_navigation.go +++ b/internal/rag/advanced_rag/harness/tool_navigation.go @@ -134,16 +134,35 @@ func loadStructureGraph(ctx context.Context, indexName, docID string, kinds map[ kindList = append(kindList, k) } rawEntities, rawRels := ParseCompiledStructure(rows, kindList) + return structureGraphFromRaw(rawEntities, rawRels) +} + +// structureGraphFromRaw maps what ParseCompiledStructure returns onto the typed +// entities/relations the drill-down consumes. +// +// A field the compiled payload omits must read as ABSENT, not as its Go +// rendering: fmt.Sprint(nil) is the non-empty string "", which survives +// navTypeOr's empty check and reaches the model as "- Name (): " with +// a phantom edge to "". Python renders "- Name (other)" and no description, +// because `(e.get("type") or "other")` / `(e.get("description") or "")` treat a +// missing key as falsy (navigation.py:1714-1715), and it DROPS a relation with a +// missing endpoint instead of keeping it (navigation.py:1783-1786). Leaving the +// field empty is also what lets the renderers apply Python's defaults — +// "other" for a type (navigation.py:1714), "related_to" for a relation type +// (navigation.py:1788). +func structureGraphFromRaw(rawEntities, rawRels []map[string]any) ([]structureEntity, []structureRel) { var out []structureEntity for _, e := range rawEntities { name, _ := e["name"].(string) if strings.TrimSpace(name) == "" { continue } + typ, _ := e["type"].(string) + desc, _ := e["description"].(string) se := structureEntity{ Name: name, - Type: fmt.Sprint(e["type"]), - Description: fmt.Sprint(e["description"]), + Type: typ, + Description: desc, } if v, ok := e["_vec"].([]float64); ok { se.Vec = v @@ -159,16 +178,19 @@ func loadStructureGraph(ctx context.Context, indexName, docID string, kinds map[ } var rels []structureRel for _, r := range rawRels { - p := strings.TrimSpace(fmt.Sprint(r["from"])) - c := strings.TrimSpace(fmt.Sprint(r["to"])) + pRaw, _ := r["from"].(string) + cRaw, _ := r["to"].(string) + p := strings.TrimSpace(pRaw) + c := strings.TrimSpace(cRaw) // Python _build_toc_tree skips empty or self-loop relations. if p == "" || c == "" || p == c { continue } + relType, _ := r["type"].(string) rels = append(rels, structureRel{ from: p, to: c, - relType: fmt.Sprint(r["type"]), + relType: relType, }) } return out, rels @@ -333,9 +355,23 @@ type NavResult struct { // A query-level miss is not a structure absence. func (n NavResult) HasStructure() bool { return n.EmptyReason != ReasonNoStructure } -// navEmpty returns an empty NavResult with the given reason and matching status. +// navEmpty returns an empty NavResult carrying Python's text: +// count="0" plus an error="
Contact
" + sres = _sres({"c1": {"content_with_weight": html, "content_ltks": "contact"}}) + _dealer().rerank_by_model(rr, sres, "q") + assert "" in rr.docs[0] and "" in rr.docs[0] + + +def test_keyword_similarity_still_uses_tokenized_tokens(): + spy = {} + rr = _CapturingRerank() + sres = _sres({"c1": {"content_with_weight": "Natural prose.", "content_ltks": "natur pros", "important_kwd": ["kw1"]}}) + _dealer(token_similarity_spy=spy).rerank_by_model(rr, sres, "q") + # The keyword blend input stays the tokenized tokens, not the natural text. + assert spy["ins_tw"] == [["natur", "pros", "kw1"]] From 78d426abda2c8640bfe26465f66825de87ff24ae Mon Sep 17 00:00:00 2001 From: changshenhan <1829967558hsl@gmail.com> Date: Fri, 11 Sep 2026 17:29:10 +0800 Subject: [PATCH 115/568] fix(chunker): one BPE pass per hardSplitPiece iteration instead of two (#18648) --- internal/ingestion/component/chunker/token.go | 16 +++- .../chunker/token_encoder_missing_test.go | 73 +++++++++++++++++ .../component/chunker/token_helpers_test.go | 22 +++++ .../component/chunker/token_invariant_test.go | 80 +++++++++++++++++++ .../component/chunker/token_perf_test.go | 32 ++++++++ 5 files changed, 219 insertions(+), 4 deletions(-) create mode 100644 internal/ingestion/component/chunker/token_encoder_missing_test.go create mode 100644 internal/ingestion/component/chunker/token_helpers_test.go create mode 100644 internal/ingestion/component/chunker/token_invariant_test.go create mode 100644 internal/ingestion/component/chunker/token_perf_test.go diff --git a/internal/ingestion/component/chunker/token.go b/internal/ingestion/component/chunker/token.go index 22f6ff132d5..040f874563b 100644 --- a/internal/ingestion/component/chunker/token.go +++ b/internal/ingestion/component/chunker/token.go @@ -83,7 +83,6 @@ import ( deepdoctype "ragflow/internal/deepdoc/parser/type" "ragflow/internal/ingestion/component/globals" "ragflow/internal/ingestion/component/schema" - "ragflow/internal/tokenizer" "ragflow/internal/parser/chunk" ) @@ -1325,9 +1324,18 @@ func splitSentencesLossless(text string) []string { func hardSplitPiece(text string, docType string, target int) []schema.ChunkDoc { var out []schema.ChunkDoc rest := text - for tokenizeStr(rest) > target { - head := tokenizer.TrimContentToTokenLimit(rest, target) - if head == "" || head == rest { + for { + // One BPE pass per iteration instead of two: trimToTokenLimit (the + // package-level tokenizer seam, see title_cap.go) returns rest + // unchanged exactly when rest fits within target tokens, so its + // result doubles as the loop-exit condition. The shrinking remainder + // is still re-encoded from scratch each round — one encode per + // iteration, not two. + head := trimToTokenLimit(rest, target) + if head == rest { + break // rest already fits; the trailing append emits it + } + if head == "" { break // cannot shrink further; avoid an infinite loop } // TrimContentToTokenLimit decodes a token prefix; if that lands on a diff --git a/internal/ingestion/component/chunker/token_encoder_missing_test.go b/internal/ingestion/component/chunker/token_encoder_missing_test.go new file mode 100644 index 00000000000..7e01566ab04 --- /dev/null +++ b/internal/ingestion/component/chunker/token_encoder_missing_test.go @@ -0,0 +1,73 @@ +package chunker + +import ( + "strings" + "testing" + "unicode/utf8" +) + +// byteTrimStub reproduces tokenizer.TrimContentToTokenLimit's encoder-missing +// fallback (UTF-8-safe byte-length trim) verbatim, minus the global encoder +// lookup. Swapping it into the trimToTokenLimit seam pins the encoder-missing +// path of hardSplitPiece deterministically: no global tiktoken state is +// touched, so the test is order-independent in full-package runs (tiktoken-go +// caches the loaded encoding in a package-level map that no reset can evict). +func byteTrimStub(s string, limit int) string { + if limit < 0 { + limit = 0 + } + if limit <= 0 { + return "" + } + b := []byte(s) + if len(b) <= limit { + return s + } + for limit > 0 && !utf8.Valid(b[:limit]) { + limit-- + } + return string(b[:limit]) +} + +// TestHardSplitPiece_EncoderMissingFallback pins the encoder-missing fallback +// path of hardSplitPiece. With the encoder unavailable, trimToTokenLimit falls +// back to a UTF-8-safe byte-length trim. The pre-optimization loop guard +// (tokenizeStr(rest) > target) never fired in that state, so the whole +// over-limit remainder was emitted as ONE piece; the current loop drives off +// the trim result and keeps emitting bounded pieces instead — strictly more +// correct, and the behavior this test locks in so the fallback stays a +// first-class, tested path. +func TestHardSplitPiece_EncoderMissingFallback(t *testing.T) { + orig := trimToTokenLimit + trimToTokenLimit = byteTrimStub + t.Cleanup(func() { trimToTokenLimit = orig }) + + // Pure ASCII+CJK text with no @@...## tags: adjustCutPastTag extends a cut + // past a tag when tokenizeStr(head) <= target, which a dead encoder makes + // always true and would swallow the byte-bounded shape under test. + text := hardSplitBenchText() + const target = 64 + + got := hardSplitPiece(text, "", target) + + // The fallback must emit bounded pieces, not one giant remainder (the old + // guard-never-fires behavior). + if len(got) < 2 { + t.Fatalf("encoder-missing fallback produced %d piece(s); want bounded pieces (>1)", len(got)) + } + // Lossless: the pieces concatenate back to the input exactly, each within + // the byte budget and valid UTF-8 (the byte-trim fallback's guarantees). + var sb strings.Builder + for i, p := range got { + if len(p.Text) > target { + t.Fatalf("piece %d is %d bytes; byte-trim fallback must keep pieces <= %d bytes", i, len(p.Text), target) + } + if !utf8.ValidString(p.Text) { + t.Fatalf("piece %d is not valid UTF-8", i) + } + sb.WriteString(p.Text) + } + if sb.String() != text { + t.Fatalf("pieces do not concatenate back to the input (got %d bytes, want %d)", sb.Len(), len(text)) + } +} diff --git a/internal/ingestion/component/chunker/token_helpers_test.go b/internal/ingestion/component/chunker/token_helpers_test.go new file mode 100644 index 00000000000..d0acc36623f --- /dev/null +++ b/internal/ingestion/component/chunker/token_helpers_test.go @@ -0,0 +1,22 @@ +package chunker + +import ( + "strings" +) + +// hardSplitBenchText builds a realistic oversized boundary-less run: a long +// unbroken sequence without sentence delimiters, mixing CJK and ASCII like a +// dense paragraph of a scanned/OCR'd document. This is exactly the input that +// hardSplitPiece must token-split, and the reason the function exists. Sized +// so a single hardSplitPiece call takes on the order of milliseconds: large +// enough for the per-iteration encode work to dominate a benchmark, small +// enough that every test sharing it stays fast. Shared by benchmarks and +// fallback-path tests alike. +func hardSplitBenchText() string { + var b strings.Builder + const sentence = "企业知识库检索系统需要高效处理海量非结构化文档的解析切分与向量化入库RAGFlow整合了文档理解文本切分混合检索与重排等多个环节Knowledgebase ingestion splits long passages into token-bounded chunks for embedding. " + for b.Len() < 12_000 { + b.WriteString(sentence) + } + return b.String() +} diff --git a/internal/ingestion/component/chunker/token_invariant_test.go b/internal/ingestion/component/chunker/token_invariant_test.go new file mode 100644 index 00000000000..ebe48069131 --- /dev/null +++ b/internal/ingestion/component/chunker/token_invariant_test.go @@ -0,0 +1,80 @@ +package chunker + +import ( + "strings" + "testing" + "unicode/utf8" +) + +// tagSlackTokens bounds how far past target a piece may legitimately go when +// adjustCutPastTag swallows a leading @@...## coordinate tag whole instead of +// splitting it: the trim result is within target, and the extension past the +// closing "##" adds at most the tag's own tokens (corpus tags measure <= 6). +const tagSlackTokens = 16 + +// TestHardSplitPieceInvariants pins the output contract of hardSplitPiece that +// callers rely on. It replaces the retired differential-against-reference +// harness: a second implementation of the same algorithm is a permanent +// maintenance liability, while these invariants hold for any correct +// token-splitting of this shape. +// +// 1. Bounded pieces: each piece is at most target tokens plus the documented +// one-token drift a re-encoded continuation piece can carry (cl100k is +// byte-level; a cut trimmed off a mid-multibyte boundary is re-absorbed by +// the next piece). Inputs without coordinate tags get the strict bound; +// tag inputs additionally allow the leading-tag-whole extension slack. +// 2. Lossless at the byte level: the pieces concatenate back to the input +// exactly. Pieces are byte-prefixes, not rune-prefixes — a cut may land +// mid-multibyte and leave raw continuation bytes at a piece's tail +// (observed with emoji/CJK corpora), repaired by the next piece's head; +// the downstream JSON layer replaces any residual invalid tail. +// 3. Monotone progress: pieces are non-empty and each is a true byte prefix +// of the not-yet-emitted remainder — the split never revisits or reorders +// bytes. +func TestHardSplitPieceInvariants(t *testing.T) { + inputs := []string{ // plain, CJK, coordinate tags, emoji, degenerate + strings.Repeat("boundary-less run of text with no sentence delimiter ", 60), + strings.Repeat("中文中文中文无句读", 200), + strings.Repeat("prelude @@12,34## body @@56,78## tail ", 80), + strings.Repeat("mid-char🎉emoji🎉run-", 80), + strings.Repeat("a", 600), + "single-token", + "", + "\n\n\n", + } + for _, target := range []int{32, 64, 128, 512} { + for _, in := range inputs { + hasTags := strings.Contains(in, "@@") + got := hardSplitPiece(in, "", target) + + var joined strings.Builder + progress := 0 + for i, p := range got { + if p.Text == "" { + t.Fatalf("target=%d in=%d bytes: piece %d is empty", target, len(in), i) + } + if !strings.HasPrefix(in[progress:], p.Text) { + t.Fatalf("target=%d in=%d bytes: piece %d is not a prefix of the remainder (monotone progress broken)", target, len(in), i) + } + progress += len(p.Text) + + // +utf8.UTFMax: a cut landing mid-multibyte leaves up to + // UTFMax-1 dangling raw bytes at the tail, which re-encode as + // individual single-byte tokens (cl100k is byte-level), plus + // the one-token continuation drift. + bound := target + utf8.UTFMax + if hasTags { + bound += tagSlackTokens + } + if n := tokenizeStr(p.Text); n > bound { + t.Fatalf("target=%d in=%d bytes: piece %d has %d tokens; bound is %d", target, len(in), i, n, bound) + } + joined.WriteString(p.Text) + } + if joined.String() != in { + t.Fatalf("target=%d in=%d bytes: pieces do not reproduce input (%d != %d bytes)", + target, len(in), joined.Len(), len(in)) + } + } + } +} diff --git a/internal/ingestion/component/chunker/token_perf_test.go b/internal/ingestion/component/chunker/token_perf_test.go new file mode 100644 index 00000000000..775bc57f3df --- /dev/null +++ b/internal/ingestion/component/chunker/token_perf_test.go @@ -0,0 +1,32 @@ +package chunker + +import ( + "strings" + "testing" +) + +// benchHardSplit runs hardSplitPiece and reports both the elapsed time and the +// number of produced pieces, so the benchmark stays honest about output size +// (a regression that halves the pieces would mask a speedup). +func benchHardSplit(b *testing.B, text string) { + b.Helper() + var pieces int + b.ResetTimer() + for i := 0; i < b.N; i++ { + pieces = len(hardSplitPiece(text, "", 512)) + } + b.ReportMetric(float64(pieces), "pieces/op") +} + +func BenchmarkHardSplitPiece_Text(b *testing.B) { + text := hardSplitBenchText() + if n := tokenizeStr(text); n <= 512 { + b.Fatalf("benchmark input only has %d tokens; it must exceed the 512-token target", n) + } + benchHardSplit(b, text) +} + +func BenchmarkHardSplitPiece_CJK(b *testing.B) { + text := strings.Repeat("无句读长文知识库检索切分处理效率优化", 250) + benchHardSplit(b, text) +} From c12224304210944dd28973bfaa6ea1cea721c79f Mon Sep 17 00:00:00 2001 From: buua436 Date: Fri, 11 Sep 2026 17:31:51 +0800 Subject: [PATCH 116/568] fix: update knowledge artifacts on document status changes (#19532) --- .../ingestion/knowledge_compile/consumer.go | 85 ++++++++++------ internal/ingestion/knowledge_compile/event.go | 25 ++++- .../document/document_dataset_update.go | 1 + internal/service/document/document_parse.go | 1 + .../document/knowledge_compile_status.go | 99 +++++++++++++++++++ 5 files changed, 178 insertions(+), 33 deletions(-) create mode 100644 internal/service/document/knowledge_compile_status.go diff --git a/internal/ingestion/knowledge_compile/consumer.go b/internal/ingestion/knowledge_compile/consumer.go index d7a95ad452b..f8cd8546d12 100644 --- a/internal/ingestion/knowledge_compile/consumer.go +++ b/internal/ingestion/knowledge_compile/consumer.go @@ -511,6 +511,7 @@ func (c *Consumer) processBatch(ctx context.Context, tenant, kb, token string, e tomb := c.tombs[kb] var completed []BacklogEntry var deleted []string + var disabled []BacklogEntry // Per-document tombstone clears are staged locally and committed only after // the write/delete paths below return without error, so a failed batch // leaves c.tombs untouched and can be retried on reclaim. @@ -553,6 +554,8 @@ func (c *Consumer) processBatch(ctx context.Context, tenant, kb, token string, e } tomb[docID] = 1 deleted = append(deleted, docID) + case EventTypeDisabled: + disabled = append(disabled, BacklogEntry{DocID: docID, EventType: string(EventTypeDisabled), Variants: st.variants}) case EventTypeCompleted: // A re-ingest after an earlier deletion: clear the prior // tombstone (deferred until the batch succeeds). @@ -562,6 +565,8 @@ func (c *Consumer) processBatch(ctx context.Context, tenant, kb, token string, e // Preserve the winning event's variants so the dispatch below can // route this doc to the matching dataset-level compile path (A0-4). completed = append(completed, BacklogEntry{DocID: docID, EventType: string(EventTypeCompleted), Variants: st.variants}) + case EventTypeEnabled: + completed = append(completed, BacklogEntry{DocID: docID, EventType: string(EventTypeEnabled), Variants: st.variants}) } } // Sort for deterministic iteration in the delete/load passes below. @@ -580,9 +585,10 @@ func (c *Consumer) processBatch(ctx context.Context, tenant, kb, token string, e zap.String("dataset_id", kb), zap.Int("completed_docs", len(completed)), zap.Int("deleted_docs", len(deleted)), + zap.Int("disabled_docs", len(disabled)), zap.Strings("entries", entryDetails)) - if len(deleted) == 0 && len(completed) == 0 { + if len(deleted) == 0 && len(disabled) == 0 && len(completed) == 0 { c.reportProgress(ctx, tenant, kb, token, 1, "completed", "No document products require merging") return nil } @@ -613,54 +619,46 @@ func (c *Consumer) processBatch(ctx context.Context, tenant, kb, token string, e return nil } - deduper, err := c.factory(tenant) - if err != nil || deduper == nil { - // A no-op deduper would silently disable dataset-level LLM merging: every - // candidate (including e.g. a "吕布" wiki_page) would be written as its own - // merged row and duplicates would accumulate across runs. That degradation - // is never acceptable here, so fail loudly instead of papering over it. - common.Fatal("knowledge_compile: dataset-level LLM deduper unavailable, refusing to continue with a no-op merge", - zap.String("kb_id", kb), - zap.String("tenant_id", tenant), - zap.String("factory_err", func() string { - if err != nil { - return err.Error() - } - return "deduper factory returned nil" - }())) - } c.reportProgress(ctx, tenant, kb, token, 0.12, "deleting", fmt.Sprintf("Deleting products for %d document(s)", len(deleted))) - // --- Deletion (two sequential DocEngine calls, no in-memory load) --- - // Deleted wins regardless of batch order, so we process deletions first. - // The deleted docs' products are never loaded into memory: the DocEngine - // does all the work in two calls: + // --- Retraction (sequential DocEngine calls, no in-memory load) --- + // Deleted and disabled docs are handled before completion merges. Their + // dataset-level contributions are removed without loading document products: + // - deleted docs also lose their document-level compiled products; + // - disabled docs retain document-level products for a later re-enable. + // The DocEngine does the dataset-level work in two calls: // 1. DeleteDocLevelForDocs drops every per-document (doc-level) product of - // the deleted docs in a single engine call. + // deleted docs in a single engine call. // 2. StripMergedSources removes the deleted doc ids from the source_doc_ids // array of every dataset-level merged product and deletes any product // whose array became empty. // A merged product referencing several deleted docs is pruned in one pass, // and an emptied product is removed exactly once. - if len(deleted) > 0 { - delIDs := make([]string, 0, len(deletedSet)) + if len(deleted) > 0 || len(disabled) > 0 { + delIDs := make([]string, 0, len(deletedSet)+len(disabled)) for d := range deletedSet { delIDs = append(delIDs, d) } + for _, entry := range disabled { + delIDs = append(delIDs, entry.DocID) + } + delIDs = uniqueSortedStrings(delIDs) // Each destructive write runs under the scheduler's per-dataset // write/rebuild lock with the generation check performed INSIDE the lock, // so a rewrite can neither land between the check and the write nor // interleave with the write itself (it must wait for this lock). This // closes the TOCTOU window where a worker past its fence could repopulate // storage the rebuild just cleared. - if err := c.withWriteLock(ctx, kb, token, func() error { - return c.writer.DeleteDocLevelForDocs(ctx, tenant, kb, delIDs) - }); err != nil { - if errors.Is(err, errClaimSuperseded) { - common.Info("knowledge_compile: batch stale before delete, aborting (rewrite barrier)", - zap.String("dataset_id", kb)) + if len(deleted) > 0 { + if err := c.withWriteLock(ctx, kb, token, func() error { + return c.writer.DeleteDocLevelForDocs(ctx, tenant, kb, deleted) + }); err != nil { + if errors.Is(err, errClaimSuperseded) { + common.Info("knowledge_compile: batch stale before delete, aborting (rewrite barrier)", + zap.String("dataset_id", kb)) + } + return err } - return err } // The second destructive call is its own locked section: a rewrite can // land between the two, in which case the stale batch must not apply its @@ -686,6 +684,31 @@ func (c *Consumer) processBatch(ctx context.Context, tenant, kb, token string, e return err } } + if len(completed) == 0 && len(wikiDiff.affectedKeys) == 0 { + c.mu.Lock() + for _, docID := range pendingTombClear { + delete(c.tombs[kb], docID) + } + c.mu.Unlock() + c.reportProgress(ctx, tenant, kb, token, 1, "completed", "Document availability changes applied") + return nil + } + deduper, err := c.factory(tenant) + if err != nil || deduper == nil { + // A no-op deduper would silently disable dataset-level LLM merging: every + // candidate (including e.g. a "吕布" wiki_page) would be written as its own + // merged row and duplicates would accumulate across runs. That degradation + // is never acceptable here, so fail loudly instead of papering over it. + common.Fatal("knowledge_compile: dataset-level LLM deduper unavailable, refusing to continue with a no-op merge", + zap.String("kb_id", kb), + zap.String("tenant_id", tenant), + zap.String("factory_err", func() string { + if err != nil { + return err.Error() + } + return "deduper factory returned nil" + }())) + } // --- Completion merge --- // Load only the per-document products of the completed (and not deleted) diff --git a/internal/ingestion/knowledge_compile/event.go b/internal/ingestion/knowledge_compile/event.go index fa949389af0..bdc707b7f2c 100644 --- a/internal/ingestion/knowledge_compile/event.go +++ b/internal/ingestion/knowledge_compile/event.go @@ -44,10 +44,12 @@ type EventType string const ( EventTypeCompleted EventType = "doc_completed" EventTypeDeleted EventType = "doc_deleted" + EventTypeEnabled EventType = "doc_enabled" + EventTypeDisabled EventType = "doc_disabled" ) -// KCCompileEvent is the payload published when a document's pipeline finishes -// (doc_completed) or is deleted (doc_deleted). It is intentionally decoupled +// KCCompileEvent is the payload published when a document's pipeline finishes, +// its availability changes, or it is deleted. It is intentionally decoupled // from common.TaskMessage because the consumer reads the raw JSON body. type KCCompileEvent struct { TenantID string `json:"tenant_id"` @@ -123,3 +125,22 @@ func PublishDeleted(ctx context.Context, tenantID, datasetID, docID string) erro } return defaultPublisher.Publish(ctx, tenantID, datasetID, docID, string(EventTypeDeleted), nil) } + +// PublishEnabled records that a document with compiled products became +// available again and must be merged into dataset-level products. +func PublishEnabled(ctx context.Context, tenantID, datasetID, docID string, variants []string) error { + if defaultPublisher == nil { + return nil + } + return defaultPublisher.Publish(ctx, tenantID, datasetID, docID, string(EventTypeEnabled), variants) +} + +// PublishDisabled records that a document with compiled products became +// unavailable. The consumer retracts only its dataset-level contributions; +// document-level compiled rows remain available for a later re-enable. +func PublishDisabled(ctx context.Context, tenantID, datasetID, docID string, variants []string) error { + if defaultPublisher == nil { + return nil + } + return defaultPublisher.Publish(ctx, tenantID, datasetID, docID, string(EventTypeDisabled), variants) +} diff --git a/internal/service/document/document_dataset_update.go b/internal/service/document/document_dataset_update.go index c123e74745b..ea2929dbe9b 100644 --- a/internal/service/document/document_dataset_update.go +++ b/internal/service/document/document_dataset_update.go @@ -94,6 +94,7 @@ func (s *DocumentService) BatchUpdateDocumentStatus(ctx context.Context, userID, } } s.markDocumentWikiDirty(ctx, kb.TenantID, doc.KbID, docID) + s.publishKnowledgeCompileStatusChange(ctx, kb.TenantID, doc.KbID, docID, statusInt) result[docID] = map[string]string{"status": status} } diff --git a/internal/service/document/document_parse.go b/internal/service/document/document_parse.go index ce1c7f8da7c..d4f4f826c8b 100644 --- a/internal/service/document/document_parse.go +++ b/internal/service/document/document_parse.go @@ -570,5 +570,6 @@ func (s *DocumentService) updateDocumentStatusOnly(ctx context.Context, doc *ent } } s.markDocumentWikiDirty(ctx, kb.TenantID, doc.KbID, doc.ID) + s.publishKnowledgeCompileStatusChange(ctx, kb.TenantID, doc.KbID, doc.ID, status) return nil } diff --git a/internal/service/document/knowledge_compile_status.go b/internal/service/document/knowledge_compile_status.go new file mode 100644 index 00000000000..cc0478b82a1 --- /dev/null +++ b/internal/service/document/knowledge_compile_status.go @@ -0,0 +1,99 @@ +// +// 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. + +package document + +import ( + "context" + "fmt" + "sort" + "strings" + + "ragflow/internal/common" + "ragflow/internal/engine/types" + kccommon "ragflow/internal/ingestion/component/knowledge_compiler/common" + knowledge_compile "ragflow/internal/ingestion/knowledge_compile" + + "go.uber.org/zap" +) + +// publishKnowledgeCompileStatusChange notifies the dataset-level consumer when +// a document's retrieval availability changes. Documents without compiled +// products do not wake the consumer because they cannot contribute to any +// dataset-level knowledge artifact. +func (s *DocumentService) publishKnowledgeCompileStatusChange(ctx context.Context, tenantID, datasetID, documentID string, status int) { + variants, err := s.documentKnowledgeCompileVariants(ctx, tenantID, datasetID, documentID) + if err != nil { + common.Warn("document mutation: failed to resolve knowledge compile variants", + zap.String("document_id", documentID), zap.Error(err)) + return + } + if len(variants) == 0 { + return + } + var publishErr error + if status == 0 { + publishErr = knowledge_compile.PublishDisabled(ctx, tenantID, datasetID, documentID, variants) + } else { + publishErr = knowledge_compile.PublishEnabled(ctx, tenantID, datasetID, documentID, variants) + } + if publishErr != nil { + common.Warn("document mutation: failed to publish knowledge compile status change", + zap.String("document_id", documentID), zap.Int("status", status), zap.Error(publishErr)) + } +} + +func (s *DocumentService) documentKnowledgeCompileVariants(ctx context.Context, tenantID, datasetID, documentID string) ([]string, error) { + if s.docEngine == nil { + return nil, nil + } + indexName := fmt.Sprintf("ragflow_%s", tenantID) + seen := make(map[string]struct{}) + for offset := 0; ; offset += 1000 { + result, err := s.docEngine.Search(ctx, &types.SearchRequest{ + IndexNames: []string{indexName}, + KbIDs: []string{datasetID}, + Offset: offset, + Limit: 1000, + SelectFields: []string{"compile_kwd", "compilation_template_kind_kwd"}, + Filter: map[string]any{"doc_id": []string{documentID}}, + }) + if err != nil { + return nil, err + } + if result == nil || len(result.Chunks) == 0 { + break + } + for _, row := range result.Chunks { + kind := strings.TrimSpace(documentStoreString(row["compilation_template_kind_kwd"])) + variant, variantErr := kccommon.KindToVariant(kind) + if variantErr != nil { + variant, variantErr = knowledge_compile.KwdToVariant(strings.TrimSpace(documentStoreString(row["compile_kwd"]))) + } + if variantErr == nil { + seen[string(variant)] = struct{}{} + } + } + if int64(offset+len(result.Chunks)) >= result.Total { + break + } + } + variants := make([]string, 0, len(seen)) + for variant := range seen { + variants = append(variants, variant) + } + sort.Strings(variants) + return variants, nil +} From a36615c6fab23bb9397039b60e7095857eb52d97 Mon Sep 17 00:00:00 2001 From: xugangqiang Date: Fri, 11 Sep 2026 17:39:11 +0800 Subject: [PATCH 117/568] Migrate cache backend from Valkey 8 to apache/kvrocks:2.16.0 (#19374) --- .github/workflows/kvrocks-parity.yml | 67 ++++ docker/docker-compose-base.yml | 42 +- docker/docker-compose-go.yml | 8 + docker/kvrocks-entrypoint.sh | 38 ++ helm/values.yaml | 6 + .../canvas/kvrocks_runtracker_parity_test.go | 225 +++++++++++ internal/engine/redis/kvrocks_config_test.go | 84 ++++ internal/engine/redis/kvrocks_deploy_test.go | 110 ++++++ internal/engine/redis/kvrocks_parity_test.go | 371 ++++++++++++++++++ 9 files changed, 950 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/kvrocks-parity.yml create mode 100755 docker/kvrocks-entrypoint.sh create mode 100644 internal/agent/canvas/kvrocks_runtracker_parity_test.go create mode 100644 internal/engine/redis/kvrocks_config_test.go create mode 100644 internal/engine/redis/kvrocks_deploy_test.go create mode 100644 internal/engine/redis/kvrocks_parity_test.go diff --git a/.github/workflows/kvrocks-parity.yml b/.github/workflows/kvrocks-parity.yml new file mode 100644 index 00000000000..8c8c3a4fd03 --- /dev/null +++ b/.github/workflows/kvrocks-parity.yml @@ -0,0 +1,67 @@ +name: Kvrocks Parity + +# Regression fence for the Valkey -> apache/kvrocks:2.16.0 migration. Runs the +# //go:build integration parity tests (internal/engine/redis, internal/agent/canvas) +# against a real Kvrocks instance. These tests are NOT part of the default +# `go test` run, so this workflow is what actually executes them in CI. +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +# Only one in-flight run per ref; cancel superseded runs on PR pushes. +concurrency: + group: kvrocks-parity-${{ github.ref }} + cancel-in-progress: true + +jobs: + kvrocks-parity: + runs-on: ubuntu-latest + env: + # CI=true makes the parity tests hard-fail (not skip) if Kvrocks is absent. + CI: "true" + KV_PASSWORD: ci-test-pass + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + go-version: "1.26" + cache: true + + # Pinned to 2.16.0+ on purpose (TTL contract + no maxmemory). Reuse the repo + # entrypoint script so this job also exercises the deployment's conf renderer. + # `-e REDIS_PASSWORD` forwards the password into the container so the + # entrypoint can render requirepass; without it Kvrocks starts open and the + # parity tests fail to AUTH. + - name: Start Kvrocks + run: | + docker run -d --name kvrocks -p 6379:6379 -e REDIS_PASSWORD \ + -v "${{ github.workspace }}/docker/kvrocks-entrypoint.sh:/etc/kvrocks/entrypoint.sh:ro" \ + --user 0:0 --entrypoint /bin/sh apache/kvrocks:2.16.0 -c "/etc/kvrocks/entrypoint.sh" + env: + REDIS_PASSWORD: ci-test-pass + + - name: Wait for Kvrocks + env: + REDIS_PASSWORD: ci-test-pass + run: | + for i in $(seq 1 30); do + if docker exec kvrocks redis-cli -a "${REDIS_PASSWORD}" ping 2>/dev/null | grep -q PONG; then + echo "Kvrocks ready"; break + fi + sleep 1 + done + + - name: Run parity tests + run: | + CGO_ENABLED=0 go test -tags integration -count=1 -timeout 300s \ + ./internal/engine/redis/... ./internal/agent/canvas/... + env: + KV_ADDR: "localhost:6379" + KV_PASSWORD: ci-test-pass + + - name: Stop Kvrocks + if: always() + run: docker rm -f kvrocks diff --git a/docker/docker-compose-base.yml b/docker/docker-compose-base.yml index 751451035bf..5dce3477c1a 100644 --- a/docker/docker-compose-base.yml +++ b/docker/docker-compose-base.yml @@ -267,7 +267,9 @@ services: retries: 120 redis: - # swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/valkey/valkey:8 + # Valkey 8 is the cache/queue backend for the Python services. The Go + # services use a separate `kvrocks` service (defined below) so the Python + # path is left unchanged by the Valkey -> apache/kvrocks migration. image: valkey/valkey:8 command: ["redis-server", "--requirepass", "${REDIS_PASSWORD}", "--maxmemory", "128mb", "--maxmemory-policy", "volatile-lru"] env_file: .env @@ -284,6 +286,42 @@ services: timeout: 10s retries: 120 + kvrocks: + # Apache Kvrocks: a RocksDB-backed, Redis-protocol-compatible store used + # ONLY by the Go services (ragflow-cpu / ragflow-gpu), which override + # REDIS_HOST=kvrocks in docker-compose-go.yml. The Python services keep + # using the `redis` (Valkey) service above, so this is a dual-backend setup. + # Pinned to 2.16.0+ on purpose (see docker/kvrocks-entrypoint.sh): older + # tags such as kvrocks/kvrocks:latest (== 2.0.6) carry a TTL contract bug + # that breaks the RunTracker CAS lease, and they reject the Redis-style + # maxmemory/maxmemory-policy settings. + image: apache/kvrocks:2.16.0 + # Kvrocks' config file does not expand ${ENV} and its CLI rejects + # `--requirepass` as a flag, so the entrypoint renders the config (including + # the password from REDIS_PASSWORD) at startup. `user: "0"` lets it write the + # config and the RocksDB data dir regardless of the mounted volume ownership. + entrypoint: ["/bin/sh", "/etc/kvrocks/entrypoint.sh"] + user: "0:0" + env_file: .env + # No host port publish: the Go services reach Kvrocks over the internal + # docker network at `kvrocks:6379`. Gated to the Go stack profile so the + # Python-only stack does not spin up an unused container. + profiles: + - ragflow-go + volumes: + - kvrocks_data:/var/lib/kvrocks + - ./kvrocks-entrypoint.sh:/etc/kvrocks/entrypoint.sh:ro + networks: + - ragflow + restart: unless-stopped + healthcheck: + # The Kvrocks image ships redis-cli and requirepass is enforced, so ping + # with the password. (The image has no nc, so a raw-tcp probe is wrong.) + test: ["CMD", "redis-cli", "-a", "${REDIS_PASSWORD}", "ping"] + interval: 10s + timeout: 10s + retries: 120 + jaeger: profiles: - jaeger @@ -426,6 +464,8 @@ volumes: driver: local redis_data: driver: local + kvrocks_data: + driver: local tei_data: driver: local kibana_data: diff --git a/docker/docker-compose-go.yml b/docker/docker-compose-go.yml index aa8915c8478..4ad60768c5c 100644 --- a/docker/docker-compose-go.yml +++ b/docker/docker-compose-go.yml @@ -69,6 +69,10 @@ services: - ./service_conf.yaml.template:/ragflow/conf/service_conf.yaml.template - ./entrypoint-go.sh:/ragflow/entrypoint.sh env_file: .env-go + # Route the Go services' cache/queue backend to the separate Kvrocks service + # (overriding REDIS_HOST=redis from .env-go). The Python services keep Valkey. + environment: + - REDIS_HOST=kvrocks networks: - ragflow restart: unless-stopped @@ -125,6 +129,10 @@ services: - ./service_conf.yaml.template:/ragflow/conf/service_conf.yaml.template - ./entrypoint.sh:/ragflow/entrypoint.sh env_file: .env-go + # Route the Go services' cache/queue backend to the separate Kvrocks service + # (overriding REDIS_HOST=redis from .env-go). The Python services keep Valkey. + environment: + - REDIS_HOST=kvrocks networks: - ragflow restart: unless-stopped diff --git a/docker/kvrocks-entrypoint.sh b/docker/kvrocks-entrypoint.sh new file mode 100755 index 00000000000..56353d45260 --- /dev/null +++ b/docker/kvrocks-entrypoint.sh @@ -0,0 +1,38 @@ +#!/bin/sh +# Kvrocks entrypoint for the RAGFlow cache service. +# +# Kvrocks 2.16.0 does NOT support ${ENV} expansion inside its config file and +# rejects `--requirepass` as a CLI flag (gflags intercepts the config key before +# Kvrocks' own handler runs). To preserve the password-based auth from the +# previous Valkey deployment without committing the secret, we render the config +# from the REDIS_PASSWORD environment variable (injected via the compose +# env_file) at container start. +# +# This service is configured with `user: "0"` so the entrypoint can write the +# generated config and the RocksDB data directory regardless of the mounted +# volume's ownership; kvrocks then runs as root. (The upstream image normally +# drops to an unprivileged user via its own entrypoint, which we override here.) +# +# Config keys verified against apache/kvrocks:2.16.0: +# bind, port, dir, requirepass +# Intentionally omitted (invalid in kvrocks 2.16.0): maxmemory, maxmemory-policy. +set -eu + +# REDIS_PASSWORD is mandatory: the previous Valkey deployment always required it, +# and an unauthenticated cache/queue backend is a security exposure. Refuse to +# start rather than silently run open. +: "${REDIS_PASSWORD:?REDIS_PASSWORD must be set (inject via compose env_file or -e)}" + +# KVROCKS_DIR overrides the RocksDB data/config dir (defaults to the compose +# mount point). Test harnesses use it to redirect writes to a temp dir. +KVROCKS_DIR="${KVROCKS_DIR:-/var/lib/kvrocks}" +mkdir -p "$KVROCKS_DIR" + +{ + echo "bind 0.0.0.0" + echo "port 6379" + echo "dir $KVROCKS_DIR" + printf 'requirepass %s\n' "$REDIS_PASSWORD" +} > "$KVROCKS_DIR/kvrocks.conf" + +exec kvrocks -c "$KVROCKS_DIR/kvrocks.conf" --dir "$KVROCKS_DIR" diff --git a/helm/values.yaml b/helm/values.yaml index e5b5dec0f69..353a8f25b6d 100644 --- a/helm/values.yaml +++ b/helm/values.yaml @@ -222,6 +222,12 @@ mysql: service: type: ClusterIP +# NOTE: The docker-compose deployment migrated from Valkey 8 to +# apache/kvrocks:2.16.0 (see docker/kvrocks-entrypoint.sh). This Helm/Kubernetes +# path is intentionally LEFT on Valkey: the template invokes `redis-server` +# directly with Valkey-specific flags (helm/templates/redis.yaml), which Kvrocks +# rejects. A Kvrocks-on-K8s migration is a separate workstream and must rewrite +# the redis template, not just swap this image. redis: enabled: true image: diff --git a/internal/agent/canvas/kvrocks_runtracker_parity_test.go b/internal/agent/canvas/kvrocks_runtracker_parity_test.go new file mode 100644 index 00000000000..89fe4d68b81 --- /dev/null +++ b/internal/agent/canvas/kvrocks_runtracker_parity_test.go @@ -0,0 +1,225 @@ +// +// 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. +// + +//go:build integration + +// Package canvas holds the RunTracker CAS regression guard for the +// Valkey→Kvrocks migration. RunTracker relies on four inline Lua scripts that +// use HGET/HSET/DEL/EXISTS/SET(PX)/PEXPIRE to implement a distributed +// active-run lease. These scripts must behave identically on Kvrocks 2.16.0, +// otherwise the agent runtime could lose its single-owner guarantee or fail to +// cancel/stale-clean runs. This file drives the real RunTracker against a live +// apache/kvrocks:2.16.0 and asserts the lease semantics. +// +// Run (KV_ADDR/KV_PASSWORD mirror the redis parity test): +// +// KV_ADDR=localhost:6379 KV_PASSWORD= bash build.sh --test-integration ./internal/agent/canvas/... +package canvas + +import ( + "os" + "testing" + "time" + + "github.com/redis/go-redis/v9" +) + +func newKVRunTracker(t *testing.T) (*RunTracker, *redis.Client) { + t.Helper() + addr := os.Getenv("KV_ADDR") + if addr == "" { + if os.Getenv("CI") != "" { + t.Fatal("KV_ADDR not set: RunTracker Kvrocks parity tests require a live apache/kvrocks:2.16.0 in CI") + } + t.Skip("KV_ADDR not set; skipping RunTracker Kvrocks parity test") + } + client := redis.NewClient(&redis.Options{ + Addr: addr, + Password: os.Getenv("KV_PASSWORD"), + }) + t.Cleanup(func() { _ = client.Close() }) + if err := client.Ping(t.Context()).Err(); err != nil { + t.Fatalf("kvrocks ping %s: %v", addr, err) + } + return NewRunTrackerWithClient(client, 30*time.Second), client +} + +// TestRunTrackerKvrocksCAS walks every RunTracker Lua script against Kvrocks +// and asserts the single-owner lease contract holds. +func TestRunTrackerKvrocksCAS(t *testing.T) { + rt, client := newKVRunTracker(t) + ctx := t.Context() + const ( + userID = "u1" + canvasID = "c1" + runA = "run-a" + runB = "run-b" + tokenA = "tok-a" + tokenB = "tok-b" + wrongTok = "tok-z" + sessionID = "kvp-session-1" + ) + + cleanup := func() { + client.Del(ctx, activeSessionKey(sessionID), cancelKey(sessionID)) + } + t.Cleanup(cleanup) + + t.Run("RegisterExclusivity", func(t *testing.T) { + cleanup() + ok, err := rt.RegisterActiveSession(ctx, ActiveSession{ + SessionID: sessionID, Token: tokenA, UserID: userID, CanvasID: canvasID, RunID: runA, + }) + if err != nil { + t.Fatalf("register A: %v", err) + } + if !ok { + t.Fatal("register A returned false, want true (first owner)") + } + got, err := rt.GetActiveSession(ctx, sessionID) + if err != nil { + t.Fatalf("get A: %v", err) + } + if got == nil || got.RunID != runA || got.Token != tokenA { + t.Fatalf("get A = %+v, want RunID=run-a Token=tok-a", got) + } + // A second, different owner must be rejected while A holds the lease. + ok, err = rt.RegisterActiveSession(ctx, ActiveSession{ + SessionID: sessionID, Token: tokenB, UserID: userID, CanvasID: canvasID, RunID: runB, + }) + if err != nil { + t.Fatalf("register B: %v", err) + } + if ok { + t.Fatal("register B returned true, want false (lease already owned by A)") + } + got, _ = rt.GetActiveSession(ctx, sessionID) + if got.RunID != runA { + t.Fatalf("after rejected B, active RunID = %s, want run-a", got.RunID) + } + }) + + t.Run("ReleaseWrongTokenKeepsLease", func(t *testing.T) { + cleanup() + if ok, _ := rt.RegisterActiveSession(ctx, ActiveSession{ + SessionID: sessionID, Token: tokenA, UserID: userID, CanvasID: canvasID, RunID: runA, + }); !ok { + t.Fatal("register A failed") + } + ok, err := rt.ReleaseActiveSession(ctx, sessionID, wrongTok) + if err != nil { + t.Fatalf("release wrong: %v", err) + } + if ok { + t.Fatal("release with wrong token succeeded, want false") + } + if got, _ := rt.GetActiveSession(ctx, sessionID); got == nil { + t.Fatal("lease lost after wrong-token release, want retained") + } + }) + + t.Run("ReleaseThenReRegister", func(t *testing.T) { + cleanup() + if ok, _ := rt.RegisterActiveSession(ctx, ActiveSession{ + SessionID: sessionID, Token: tokenA, UserID: userID, CanvasID: canvasID, RunID: runA, + }); !ok { + t.Fatal("register A failed") + } + ok, err := rt.ReleaseActiveSession(ctx, sessionID, tokenA) + if err != nil { + t.Fatalf("release A: %v", err) + } + if !ok { + t.Fatal("release A returned false, want true") + } + // After release, a new owner may take over. + ok, err = rt.RegisterActiveSession(ctx, ActiveSession{ + SessionID: sessionID, Token: tokenB, UserID: userID, CanvasID: canvasID, RunID: runB, + }) + if err != nil { + t.Fatalf("register B after release: %v", err) + } + if !ok { + t.Fatal("register B after release returned false, want true") + } + got, _ := rt.GetActiveSession(ctx, sessionID) + if got.RunID != runB || got.Token != tokenB { + t.Fatalf("after re-register, active = %+v, want RunID=run-b Token=tok-b", got) + } + }) + + t.Run("RefreshLease", func(t *testing.T) { + cleanup() + if ok, _ := rt.RegisterActiveSession(ctx, ActiveSession{ + SessionID: sessionID, Token: tokenA, UserID: userID, CanvasID: canvasID, RunID: runA, + }); !ok { + t.Fatal("register A failed") + } + ok, err := rt.RefreshActiveSession(ctx, sessionID, tokenA) + if err != nil { + t.Fatalf("refresh A: %v", err) + } + if !ok { + t.Fatal("refresh with correct token returned false, want true") + } + ok, err = rt.RefreshActiveSession(ctx, sessionID, wrongTok) + if err != nil { + t.Fatalf("refresh wrong: %v", err) + } + if ok { + t.Fatal("refresh with wrong token returned true, want false") + } + }) + + t.Run("CancelMarker", func(t *testing.T) { + cleanup() + if ok, _ := rt.RegisterActiveSession(ctx, ActiveSession{ + SessionID: sessionID, Token: tokenA, UserID: userID, CanvasID: canvasID, RunID: runA, + }); !ok { + t.Fatal("register A failed") + } + // Wrong token must not publish a cancel marker. + ok, err := rt.RequestCancelActiveSession(ctx, sessionID, wrongTok) + if err != nil { + t.Fatalf("cancel wrong: %v", err) + } + if ok { + t.Fatal("cancel with wrong token returned true, want false") + } + if n, _ := client.Exists(ctx, cancelKey(sessionID)).Result(); n != 0 { + t.Fatal("cancel marker set by wrong token, want absent") + } + // Correct token publishes a PX-scoped cancel marker. + ok, err = rt.RequestCancelActiveSession(ctx, sessionID, tokenA) + if err != nil { + t.Fatalf("cancel A: %v", err) + } + if !ok { + t.Fatal("cancel with correct token returned false, want true") + } + if n, _ := client.Exists(ctx, cancelKey(sessionID)).Result(); n != 1 { + t.Fatal("cancel marker not present after correct cancel") + } + ttl, err := client.TTL(ctx, cancelKey(sessionID)).Result() + if err != nil { + t.Fatalf("cancel marker TTL: %v", err) + } + // RequestCancelTTL is 24h; the marker must carry a positive expiry. + if ttl <= 0 { + t.Fatalf("cancel marker TTL = %v, want > 0", ttl) + } + }) +} diff --git a/internal/engine/redis/kvrocks_config_test.go b/internal/engine/redis/kvrocks_config_test.go new file mode 100644 index 00000000000..278c68bfd5e --- /dev/null +++ b/internal/engine/redis/kvrocks_config_test.go @@ -0,0 +1,84 @@ +// +// 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. +// + +// Package redis holds deployment-config regression guards for the +// Valkey->Kvrocks migration. These are plain unit tests (no external service): +// they assert that the deployment artifacts (CI workflow, compose file) encode +// the required fixes so a future edit cannot silently regress the migration. +package redis + +import ( + "os" + "path/filepath" + "runtime" + "strings" + "testing" +) + +// repoRoot walks up from this source file to the module root (go.mod). +func repoRoot(t *testing.T) string { + t.Helper() + _, file, _, ok := runtime.Caller(0) + if !ok { + t.Fatal("runtime.Caller failed") + } + dir := filepath.Dir(file) + for { + if _, err := os.Stat(filepath.Join(dir, "go.mod")); err == nil { + return dir + } + parent := filepath.Dir(dir) + if parent == dir { + t.Fatal("repo root (go.mod) not found") + } + dir = parent + } +} + +func readFile(t *testing.T, path string) string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return string(b) +} + +// TestKvrocksDeploymentConfig guards the deployment artifacts that the parity +// integration tests cannot reach on their own: the CI workflow must forward the +// password into the container, and the compose healthcheck must authenticate +// now that requirepass is enforced. +func TestKvrocksDeploymentConfig(t *testing.T) { + root := repoRoot(t) + + t.Run("WorkflowForwardsRedisPassword", func(t *testing.T) { + wf := readFile(t, filepath.Join(root, ".github/workflows/kvrocks-parity.yml")) + if !strings.Contains(wf, "-e REDIS_PASSWORD") { + t.Fatal("kvrocks-parity.yml: the docker run must forward REDIS_PASSWORD into the container (-e REDIS_PASSWORD); without it Kvrocks starts unauthenticated and the parity tests fail to AUTH") + } + }) + + t.Run("ComposeHealthcheckAuthenticates", func(t *testing.T) { + compose := readFile(t, filepath.Join(root, "docker/docker-compose-base.yml")) + // requirepass is enforced, so the healthcheck must authenticate. The + // Kvrocks image ships redis-cli (but not nc), so the probe is + // `redis-cli -a ${REDIS_PASSWORD} ping`. A bare PING would be rejected + // and mark the service permanently unhealthy. + if !strings.Contains(compose, "redis-cli") || !strings.Contains(compose, "${REDIS_PASSWORD}") { + t.Fatal("docker-compose redis healthcheck must use `redis-cli -a ${REDIS_PASSWORD} ping` (the Kvrocks image has no nc); a bare PING fails now that requirepass is enforced") + } + }) +} diff --git a/internal/engine/redis/kvrocks_deploy_test.go b/internal/engine/redis/kvrocks_deploy_test.go new file mode 100644 index 00000000000..8fc22224c27 --- /dev/null +++ b/internal/engine/redis/kvrocks_deploy_test.go @@ -0,0 +1,110 @@ +// +// 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. +// + +//go:build integration + +package redis + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/redis/go-redis/v9" +) + +// TestKvrocksEntrypointRequiresPassword drives the real entrypoint script with a +// stub `kvrocks` on PATH so we can assert its pre-exec behavior without a real +// Kvrocks binary. It guards Improvement 1: the entrypoint must refuse to start +// without REDIS_PASSWORD (the previous Valkey deployment always required it) and +// must render requirepass from it. +func TestKvrocksEntrypointRequiresPassword(t *testing.T) { + root := repoRoot(t) + ep := filepath.Join(root, "docker/kvrocks-entrypoint.sh") + if _, err := os.Stat(ep); err != nil { + t.Fatalf("entrypoint not found: %v", err) + } + + // runEntrypoint executes the entrypoint with a stub `kvrocks` on PATH and a + // temp KVROCKS_DIR, injecting (or omitting) REDIS_PASSWORD. + runEntrypoint := func(t *testing.T, password string) error { + t.Helper() + dir := t.TempDir() + stub := filepath.Join(dir, "kvrocks") + if err := os.WriteFile(stub, []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + cmd := exec.Command("sh", ep) + env := []string{ + "PATH=" + dir + ":" + os.Getenv("PATH"), + "KVROCKS_DIR=" + dir, + "HOME=" + dir, + } + if password != "" { + env = append(env, "REDIS_PASSWORD="+password) + } + cmd.Env = env + return cmd.Run() + } + + t.Run("MissingPasswordFails", func(t *testing.T) { + if err := runEntrypoint(t, ""); err == nil { + t.Fatal("entrypoint should fail (non-zero) when REDIS_PASSWORD is unset") + } + }) + + t.Run("RendersRequirepass", func(t *testing.T) { + dir := t.TempDir() + stub := filepath.Join(dir, "kvrocks") + if err := os.WriteFile(stub, []byte("#!/bin/sh\n"), 0o755); err != nil { + t.Fatal(err) + } + cmd := exec.Command("sh", ep) + cmd.Env = []string{ + "PATH=" + dir + ":" + os.Getenv("PATH"), + "KVROCKS_DIR=" + dir, + "HOME=" + dir, + "REDIS_PASSWORD=ci-test-pass", + } + if err := cmd.Run(); err != nil { + t.Fatalf("entrypoint failed with password set: %v", err) + } + conf, err := os.ReadFile(filepath.Join(dir, "kvrocks.conf")) + if err != nil { + t.Fatalf("read conf: %v", err) + } + if !strings.Contains(string(conf), "requirepass ci-test-pass") { + t.Fatalf("conf missing requirepass: %q", string(conf)) + } + }) +} + +// TestKvrocksRequirepassEnforced asserts that the live Kvrocks enforces +// requirepass: a client without a password cannot PING. This is the runtime +// contract that Blocker A (workflow must forward -e REDIS_PASSWORD) and +// Improvement 1 (entrypoint requires the password) both produce. +func TestKvrocksRequirepassEnforced(t *testing.T) { + _ = newKVClient(t) // ensures a live, password-protected Kvrocks + ctx := t.Context() + addr := os.Getenv("KV_ADDR") + noAuth := redis.NewClient(&redis.Options{Addr: addr}) + defer func() { _ = noAuth.Close() }() + if err := noAuth.Ping(ctx).Err(); err == nil { + t.Fatal("PING without password succeeded; requirepass not enforced") + } +} diff --git a/internal/engine/redis/kvrocks_parity_test.go b/internal/engine/redis/kvrocks_parity_test.go new file mode 100644 index 00000000000..ee640698c60 --- /dev/null +++ b/internal/engine/redis/kvrocks_parity_test.go @@ -0,0 +1,371 @@ +// +// 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. +// + +//go:build integration + +// Package redis holds the regression guard for the Valkey→Kvrocks migration. +// These tests drive the real application Client (internal/engine/redis) against +// a live apache/kvrocks:2.16.0 instance and assert that every command family +// the codebase relies on behaves compatibly with Redis/Valkey. They are the +// "no regression" guard: if a future Kvrocks bump or config change breaks any +// contract the app depends on, these tests turn red. +// +// Run (mirrors the deployment: the entrypoint renders the config, including the +// password from REDIS_PASSWORD, at startup): +// +// docker run -d -p 6379:6379 \ +// -v $(pwd)/docker/kvrocks-entrypoint.sh:/etc/kvrocks/entrypoint.sh:ro \ +// -e REDIS_PASSWORD= --user 0:0 --entrypoint /bin/sh \ +// apache/kvrocks:2.16.0 -c "/etc/kvrocks/entrypoint.sh" +// KV_ADDR=localhost:6379 KV_PASSWORD= bash build.sh --test-integration ./internal/engine/redis/... +// +// Without KV_ADDR the test skips locally for convenience, but fails hard (CI=true) +// so a misconfigured CI job never turns green without a live Kvrocks. +package redis + +import ( + "os" + "testing" + "time" + + "github.com/google/uuid" + "github.com/redis/go-redis/v9" +) + +// newKVClient wires a Client against a live Kvrocks. +// +// Guard policy: the parity tests are a regression fence, so a missing backend +// must be loud, not silent. KV_ADDR unset in CI (CI=true) is a misconfigured +// job and fails hard; unset outside CI simply skips (local convenience). A set +// but unreachable KV_ADDR always fails (the Ping below), so a CI run that forgot +// to start Kvrocks can never pass green. +func newKVClient(t *testing.T) *Client { + t.Helper() + addr := os.Getenv("KV_ADDR") + if addr == "" { + if os.Getenv("CI") != "" { + t.Fatal("KV_ADDR not set: Kvrocks parity tests require a live apache/kvrocks:2.16.0 in CI") + } + t.Skip("KV_ADDR not set; skipping Kvrocks parity test (needs apache/kvrocks:2.16.0)") + } + c := &Client{ + client: redis.NewClient(&redis.Options{ + Addr: addr, + Password: os.Getenv("KV_PASSWORD"), + }), + luaDeleteIfEqual: redis.NewScript(luaDeleteIfEqualScript), + luaTokenBucket: redis.NewScript(luaTokenBucketScript), + } + t.Cleanup(func() { _ = c.client.Close() }) + if err := c.client.Ping(t.Context()).Err(); err != nil { + t.Fatalf("kvrocks ping %s: %v", addr, err) + } + return c +} + +// TestKvrocksParity exercises the full command surface the application uses. +// It is one test with subtests so a single backend connection is reused. +func TestKvrocksParity(t *testing.T) { + c := newKVClient(t) + ctx := t.Context() + // One-shot unique prefix: Kvrocks data persists across test processes, so + // a fresh prefix each run prevents cross-run key collisions. + prefix := "kvp:" + uuid.NewString() + ":" + + t.Run("String", func(t *testing.T) { + k := prefix + "str" + if !c.Set(ctx, k, "v1", time.Minute) { + t.Fatal("Set failed") + } + if v, _ := c.Get(ctx, k); v != "v1" { + t.Fatalf("Get = %q, want v1", v) + } + if ok, _ := c.Exist(ctx, k); !ok { + t.Fatal("Exist = false, want true") + } + // SetNX must not overwrite an existing key. + if c.SetNX(ctx, k, "v2", time.Minute) { + t.Fatal("SetNX overwrote existing key") + } + if v, _ := c.Get(ctx, k); v != "v1" { + t.Fatalf("SetNX side effect: Get = %q, want v1", v) + } + if n, _ := c.IncrBy(ctx, k+"-c", 5); n != 5 { + t.Fatalf("IncrBy = %d, want 5", n) + } + if n, _ := c.IncrBy(ctx, k+"-c", 3); n != 8 { + t.Fatalf("IncrBy = %d, want 8", n) + } + if n, _ := c.DecrBy(ctx, k+"-c", 2); n != 6 { + t.Fatalf("DecrBy = %d, want 6", n) + } + if !c.Expire(ctx, k, 10*time.Second) { + t.Fatal("Expire failed") + } + if tt := c.TTL(ctx, k); tt <= 0 || tt > 10*time.Second { + t.Fatalf("TTL = %v, want (0,10s]", tt) + } + if !c.Delete(ctx, k) { + t.Fatal("Delete failed") + } + if ok, _ := c.Exist(ctx, k); ok { + t.Fatal("Exist = true after Delete, want false") + } + }) + + t.Run("Hash", func(t *testing.T) { + k := prefix + "hash" + c.client.Del(ctx, k) + if err := c.client.HSet(ctx, k, map[string]any{ + "a": "1", "b": "2", + }).Err(); err != nil { + t.Fatalf("HSet: %v", err) + } + got, err := c.client.HGetAll(ctx, k).Result() + if err != nil { + t.Fatalf("HGetAll: %v", err) + } + if got["a"] != "1" || got["b"] != "2" { + t.Fatalf("HGetAll = %v, want a=1 b=2", got) + } + // TokenBucket Lua exercises HMGET/HMSET/EXPIRE inside Kvrocks. + tb := &TokenBucket{client: c, key: k + "-tb", capacity: 2, rate: 0.1} + if ok, _ := tb.Allow(ctx, 1); !ok { + t.Fatal("TokenBucket first call denied, want allowed") + } + if ok, _ := tb.Allow(ctx, 1); !ok { + t.Fatal("TokenBucket second call denied, want allowed") + } + if ok, _ := tb.Allow(ctx, 1); ok { + t.Fatal("TokenBucket third call allowed, want denied (bucket exhausted)") + } + }) + + t.Run("Set", func(t *testing.T) { + k := prefix + "set" + c.client.Del(ctx, k) + if !c.SAdd(ctx, k, "m1") { + t.Fatal("SAdd m1 failed") + } + if !c.SAdd(ctx, k, "m2") { + t.Fatal("SAdd m2 failed") + } + if !c.SIsMember(ctx, k, "m1") { + t.Fatal("SIsMember m1 = false, want true") + } + if c.SIsMember(ctx, k, "mX") { + t.Fatal("SIsMember mX = true, want false") + } + members, err := c.SMembers(ctx, k) + if err != nil { + t.Fatalf("SMembers: %v", err) + } + if len(members) != 2 { + t.Fatalf("SMembers len = %d, want 2", len(members)) + } + if !c.SRem(ctx, k, "m1") { + t.Fatal("SRem m1 failed") + } + if c.SIsMember(ctx, k, "m1") { + t.Fatal("SIsMember m1 = true after SRem, want false") + } + }) + + t.Run("ZSet", func(t *testing.T) { + k := prefix + "zset" + c.client.Del(ctx, k) + if !c.ZAdd(ctx, k, "a", 1) { + t.Fatal("ZAdd a failed") + } + if !c.ZAdd(ctx, k, "b", 5) { + t.Fatal("ZAdd b failed") + } + if !c.ZAdd(ctx, k, "c", 10) { + t.Fatal("ZAdd c failed") + } + if n := c.ZCount(ctx, k, 0, 6); n != 2 { + t.Fatalf("ZCount(0,6) = %d, want 2", n) + } + got, err := c.ZRangeByScore(ctx, k, 0, 6) + if err != nil { + t.Fatalf("ZRangeByScore: %v", err) + } + if len(got) != 2 || got[0] != "a" || got[1] != "b" { + t.Fatalf("ZRangeByScore = %v, want [a b]", got) + } + popped, err := c.ZPopMin(ctx, k, 1) + if err != nil { + t.Fatalf("ZPopMin: %v", err) + } + if len(popped) != 1 || popped[0].Member.(string) != "a" { + t.Fatalf("ZPopMin = %v, want [a]", popped) + } + // After ZPopMin removed "a"(score 1), remaining b(5) and c(10). + // Removing the [0,6] range must drop only "b" -> 1 removed. + if n := c.ZRemRangeByScore(ctx, k, 0, 6); n != 1 { + t.Fatalf("ZRemRangeByScore(0,6) = %d, want 1", n) + } + }) + + t.Run("Stream", func(t *testing.T) { + q := prefix + "stream" + c.client.Del(ctx, q) + if !c.QueueProduct(ctx, q, map[string]string{"hello": "world"}) { + t.Fatal("QueueProduct failed") + } + // Consumer group creation is implicit in QueueConsumer. + msg, err := c.QueueConsumer(ctx, q, "grp", "cons", "") + if err != nil { + t.Fatalf("QueueConsumer: %v", err) + } + if msg == nil { + t.Fatal("QueueConsumer returned nil message") + } + // QueueProduct stored {"hello":"world"} under the stream "message" + // field; GetMessage() returns the JSON-decoded payload map. + if got := msg.GetMessage()["hello"]; got != "world" { + t.Fatalf("consumed payload hello = %v, want world", got) + } + if !msg.Ack(ctx) { + t.Fatal("Ack failed") + } + pending, err := c.GetPendingMsg(ctx, q, "grp") + if err != nil { + t.Fatalf("GetPendingMsg: %v", err) + } + if len(pending) != 0 { + t.Fatalf("GetPendingMsg len = %d, want 0 (acked)", len(pending)) + } + // XRange round-trips the stored entry (RequeueMsg path). + ranged, err := c.client.XRange(ctx, q, "-", "+").Result() + if err != nil { + t.Fatalf("XRange: %v", err) + } + if len(ranged) == 0 { + t.Fatal("XRange returned no entries") + } + }) + + t.Run("LuaDeleteIfEqual", func(t *testing.T) { + k := prefix + "die" + c.client.Del(ctx, k) + if !c.Set(ctx, k, "expect", time.Minute) { + t.Fatal("Set failed") + } + // Wrong expected value must not delete. + if c.DeleteIfEqual(ctx, k, "wrong") { + t.Fatal("DeleteIfEqual deleted on wrong value") + } + if ok, _ := c.Exist(ctx, k); !ok { + t.Fatal("key gone after wrong DeleteIfEqual") + } + // Correct expected value deletes. + if !c.DeleteIfEqual(ctx, k, "expect") { + t.Fatal("DeleteIfEqual failed on correct value") + } + if ok, _ := c.Exist(ctx, k); ok { + t.Fatal("key still present after correct DeleteIfEqual") + } + }) + + t.Run("TokenBucketStrict", func(t *testing.T) { + // EvalTokenBucketStrict is the fail-closed counterpart used by the webhook + // rate limiter (agent_webhook_security.go). It shares the TokenBucket Lua + // but must surface its result/errors to the caller rather than silently + // passing traffic. Verify the allow/deny sequence on Kvrocks. + k := prefix + "tbs" + c.client.Del(ctx, k) + ok, err := c.EvalTokenBucketStrict(ctx, k, 2, 0.1) + if err != nil { + t.Fatalf("call 1: %v", err) + } + if !ok { + t.Fatal("call 1: expected allowed") + } + if ok, err = c.EvalTokenBucketStrict(ctx, k, 2, 0.1); err != nil || !ok { + t.Fatalf("call 2: ok=%v err=%v, want allowed", ok, err) + } + ok, err = c.EvalTokenBucketStrict(ctx, k, 2, 0.1) + if err != nil { + t.Fatalf("call 3: %v", err) + } + if ok { + t.Fatal("call 3: expected denied (bucket exhausted), got allowed") + } + }) + + t.Run("PipelineSetNX", func(t *testing.T) { + k := prefix + "pipe" + c.client.Del(ctx, k) + if !c.Transaction(ctx, k, "v", time.Minute) { + t.Fatal("Transaction (pipeline SetNX) failed") + } + // Second call hits an existing key: SetNX inside the pipeline does not + // overwrite, so the value must remain "v" (Transaction returns on + // Exec success, not SetNX success — assert the value, not the bool). + c.Transaction(ctx, k, "v2", time.Minute) + if v, _ := c.Get(ctx, k); v != "v" { + t.Fatalf("pipeline SetNX overwrote existing key: Get = %q, want v", v) + } + }) + + t.Run("TTLContract", func(t *testing.T) { + // Kvrocks >= 2.11 reads metadata.Expired() on the read path, so a key + // whose TTL elapsed must report EXISTS=0 immediately (no 2-3s + // compaction lag). This is the exact bug that 2.0.6 had and that + // motivated pinning apache/kvrocks:2.16.0. Guard it. + k := prefix + "ttl" + c.client.Del(ctx, k) + if !c.Set(ctx, k, "x", 1200*time.Millisecond) { + t.Fatal("Set with TTL failed") + } + if ok, _ := c.Exist(ctx, k); !ok { + t.Fatal("key should exist before TTL elapses") + } + time.Sleep(1500 * time.Millisecond) + if ok, _ := c.Exist(ctx, k); ok { + t.Fatal("EXISTS=1 long after TTL elapsed: Kvrocks read-path expiry broken (regression of 2.0.6 bug)") + } + if tt := c.TTL(ctx, k); tt != -2 { + t.Fatalf("TTL = %v, want -2 (key gone)", tt) + } + }) + + t.Run("Auth", func(t *testing.T) { + // The live client authenticated at connect time. A second client with + // a wrong password must fail to PING (NOAUTH), proving requirepass is + // enforced — important because Kvrocks rejects multi-user ACLs. + pw := os.Getenv("KV_PASSWORD") + if pw == "" { + t.Skip("KV_PASSWORD empty; auth-enforcement check skipped") + } + bad := redis.NewClient(&redis.Options{Addr: os.Getenv("KV_ADDR"), Password: "definitely-wrong"}) + defer func() { _ = bad.Close() }() + if err := bad.Ping(ctx).Err(); err == nil { + t.Fatal("PING with wrong password succeeded; requirepass not enforced") + } + }) + + t.Run("Info", func(t *testing.T) { + // Info must not panic on Kvrocks' differently-shaped INFO output. + info := c.Info(ctx) + if info == nil { + t.Fatal("Info returned nil") + } + // server_mode is empty on Kvrocks (field name differs) — that is + // acceptable and only affects monitoring, not functionality. + }) +} From 9386b42eaedc33c25ff3da64a29950c9b9f040bb Mon Sep 17 00:00:00 2001 From: YanZhang <143392188+Yannnnnnny@users.noreply.github.com> Date: Fri, 11 Sep 2026 18:18:40 +0800 Subject: [PATCH 118/568] =?UTF-8?q?docs=EF=BC=9A=20update=20FAQs=20(#19538?= =?UTF-8?q?)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update FAQs Recover the deleted sandbox_quickstart.md --- .../configurations/sandbox_quickstart.md | 241 +++++++++++++++++ docs/faq.mdx | 242 ++++++++++-------- ...ion.md => Mutimodel_comparison_and_FAQ.md} | 14 +- docs/guides/dataset/notes_and_faqs.md | 5 + 4 files changed, 390 insertions(+), 112 deletions(-) create mode 100644 docs/administrator/configurations/sandbox_quickstart.md rename docs/guides/chat/{testing_and_evaluation.md => Mutimodel_comparison_and_FAQ.md} (66%) diff --git a/docs/administrator/configurations/sandbox_quickstart.md b/docs/administrator/configurations/sandbox_quickstart.md new file mode 100644 index 00000000000..8234ac8b360 --- /dev/null +++ b/docs/administrator/configurations/sandbox_quickstart.md @@ -0,0 +1,241 @@ +--- +sidebar_position: 2 +title: Sandbox Quickstart +sidebar_label: Sandbox Quickstart +slug: /sandbox_quickstart +sidebar_custom_props: { + categoryIcon: LucideCog +} +--- +# Sandbox quickstart + +RAGFlow's `CodeExec` agent component needs a sandbox provider to run Python and JavaScript code. + +The simplest setup flow is: + +1. Start the required sandbox services. +2. Open the RAGFlow admin page. +3. Go to **Admin > Sandbox Settings**. +4. Choose a provider and save the configuration. +5. Test the connection in the same page. + +## Admin page + +Configure sandbox providers from the admin page: + +- `self_managed`: Uses the executor manager service. +- `local`: Runs code on the current machine. +- `ssh`: Runs code on a remote machine over SSH. +- `aliyun_codeinterpreter`, `e2b`, and `tenki`: Cloud providers. + +admin-sandbox-settings + +## Provider options + + +RAGFlow supports multiple sandbox providers. Configure the active provider in +Admin > Sandbox Settings after the services are up. + +- `self_managed`: Runs code inside Docker-managed sandbox containers. This is the default provider. +- `local`: Runs code as local Python or Node.js subprocesses. Use this only in trusted development environments. +- `ssh`: Runs code on a remote machine over SSH. +- `aliyun_codeinterpreter` and `e2b`: Cloud-hosted providers that remain available in the admin provider list. +- `tenki`: Cloud-hosted provider that runs each execution in a disposable [Tenki](https://tenki.cloud) microVM. See [Tenki](#tenki) below. + +### Tenki + +`tenki` runs each code execution in a fresh Tenki microVM and destroys it afterwards. It is cloud-hosted, so it needs no local sandbox services, gVisor, or Docker base images — only outbound network access and an API key. + +The `tenki-sandbox` SDK is an optional dependency (it requires `protobuf>=6.31`, which differs from RAGFlow's default gRPC stack), so it is not installed by default. Install it into the RAGFlow runtime before selecting this provider: + +```bash +pip install tenki-sandbox +``` + +Configure it in **Admin > Sandbox Settings**: + +- `api_key` (required): Tenki API key. Create one at [app.tenki.cloud](https://app.tenki.cloud) under **API Keys**. +- `project_id` (required): the Tenki project that sandboxes are created under. +- `base_url` (optional): override the Tenki API endpoint. +- `image` (optional): sandbox base image. Leave empty to use the Tenki default image, which includes `python3` and `node`. +- `allow_outbound` (optional, security-relevant): whether the sandbox may make outbound network connections. Defaults to `false` so sandboxed code has no network access; set it to `true` when code needs the network (for example, to install packages). +- `timeout`, `max_lifetime`, `cpu_cores`, `memory_mb`, `disk_size_gb`, and the output/artifact limits have sensible defaults and can be tuned in the same page. + +Notes: + +- Supported languages are Python and JavaScript. +- Files written to the `artifacts/` directory of the working directory are returned as run artifacts. +- The provider uses only Tenki's create/exec/destroy operations; it does not use volumes or snapshots. + +## Prerequisites + +- Linux distribution compatible with gVisor. +- gVisor installed and configured. +- Docker version 25.0 or higher (API 1.44+). Ensure your executor manager image ships with Docker CLI `29.1.0` or higher to stay compatible with the latest Docker daemons. +- Docker Compose version 2.26.1 or higher (similar to RAGFlow requirements). +- uv package and project manager installed. +- (Optional) GNU Make for simplified command-line management. + +:::tip NOTE +The error message `client version 1.43 is too old. Minimum supported API version is 1.44` indicates that your executor manager image's built-in Docker CLI version is lower than `29.1.0` required by the Docker daemon in use. +::: + +## Build Docker base images + +The sandbox uses isolated base images for secure containerized execution environments. + +### Option 1: Build from source + +Build the runtime base images: + +```bash +docker build -t sandbox-base-python:latest ./sandbox_base_image/python +docker build -t sandbox-base-nodejs:latest ./sandbox_base_image/nodejs +``` + +Alternatively, build all base images at once using the Makefile: + +```bash +make build +``` + +Build the executor manager image: + +```bash +docker build -t sandbox-executor-manager:latest ./executor_manager +``` + +### Option 2: Pull base images from Docker Hub + +If you do not need to customize runtime dependencies, pull the published base images and tag them with the names used by standalone Docker Compose: + +```bash +docker pull infiniflow/sandbox-base-python:latest +docker pull infiniflow/sandbox-base-nodejs:latest + +docker tag infiniflow/sandbox-base-python:latest sandbox-base-python:latest +docker tag infiniflow/sandbox-base-nodejs:latest sandbox-base-nodejs:latest +``` + +Then restart the standalone sandbox services: + +```bash +docker compose -f docker-compose.yml down +docker compose -f docker-compose.yml up -d +``` + +## Running with RAGFlow + +1. Verify that gVisor is properly installed and operational. + +2. Configure the .env file located at docker/.env: + +- Set `SANDBOX_ENABLED=1`. +- Include `sandbox` in `COMPOSE_PROFILES` if you want the default + `self_managed` executor-manager service. +- Keep the self-managed deployment defaults in `.env` if you need to change the + sandbox-executor-manager image, pool size, base images, seccomp, memory, or + timeout. + +3. Add the following entry to your /etc/hosts file to resolve the executor manager service: + + ```bash + 127.0.0.1 es01 infinity mysql minio redis sandbox-executor-manager + ``` + +4. Start the RAGFlow service as usual. +5. Open **Admin > Sandbox Settings**. +6. Select a provider. +7. Fill in the required fields. +8. Click **Save**. +9. Click **Test Connection** if needed. + +## Environment variables + +The variables in `docker/.env` are grouped by scope. + +### System-level variables + +These variables apply to sandbox support in general: + +- `SANDBOX_ENABLED`: Enables sandbox support in RAGFlow. +- `COMPOSE_PROFILES`: Include `sandbox` to start the default self-managed executor-manager service. +- `SANDBOX_ARTIFACT_BUCKET`: MinIO bucket used for files generated by sandbox code. +- `SANDBOX_ARTIFACT_EXPIRE_DAYS`: Number of days before sandbox artifacts expire. + +### Self-managed deployment defaults + +These variables are shown in Admin as deployment defaults for `self_managed`. +Changing them requires restarting `sandbox-executor-manager`. + +- `SANDBOX_EXECUTOR_MANAGER_IMAGE`: Docker image for the executor manager service. +- `SANDBOX_EXECUTOR_MANAGER_POOL_SIZE`: Number of Python and Node.js sandbox containers kept in the pool. +- `SANDBOX_BASE_PYTHON_IMAGE`: Python runtime image used by executor-managed containers. +- `SANDBOX_BASE_NODEJS_IMAGE`: Node.js runtime image used by executor-managed containers. +- `SANDBOX_EXECUTOR_MANAGER_PORT`: Host port exposed by the executor manager. +- `SANDBOX_ENABLE_SECCOMP`: Enables the optional seccomp profile for sandbox containers. +- `SANDBOX_MAX_MEMORY`: Memory limit for each sandbox runtime container. +- `SANDBOX_TIMEOUT`: Default execution timeout. + +### Admin-managed runtime settings + +Provider selection and runtime settings are configured in **Admin > Sandbox Settings**. + +Examples: + +- Choose the active provider +- Configure `self_managed` runtime settings +- Configure all `local` settings +- Configure all `ssh` settings + +For `self_managed`: + +- Runtime settings are editable in Admin +- Deployment defaults come from `.env` and are shown as read-only values + +## Running standalone + +### Manual setup + +1. Initialize the environment variables: + + ```bash + cp .env.example .env + ``` + +2. Launch the sandbox services with Docker Compose: + + ```bash + docker compose -f docker-compose.yml up + ``` + +3. Test the sandbox setup: + + ```bash + source .venv/bin/activate + export PYTHONPATH=$(pwd) + uv pip install -r executor_manager/requirements.txt + uv run tests/sandbox_security_tests_full.py + ``` + +### Using Makefile + +Run all setup, build, launch, and tests with a single command: + +```bash +make +``` + +### Monitoring + +To follow logs of the executor manager container: + +```bash +docker logs -f sandbox-executor-manager +``` + +Or use the Makefile shortcut: + +```bash +make logs +``` diff --git a/docs/faq.mdx b/docs/faq.mdx index cbc6c29ed70..2c4c02a6d2f 100644 --- a/docs/faq.mdx +++ b/docs/faq.mdx @@ -21,17 +21,16 @@ import TOCInline from '@theme/TOCInline'; ### What sets RAGFlow apart from other RAG products? -The "garbage in garbage out" status quo remains unchanged despite the fact that LLMs have advanced Natural Language Processing (NLP) significantly. In its response, RAGFlow introduces two unique features compared to other Retrieval-Augmented Generation (RAG) products. +RAGFlow provides an end-to-end RAG platform that goes beyond basic document chunking and retrieval. Its key strengths include: -- Fine-grained document parsing: Document parsing involves images and tables, with the flexibility for you to intervene as needed. -- Traceable answers with reduced hallucinations: You can trust RAGFlow's responses as you can view the citations and references supporting them. +- **Deep document understanding** for complex content such as text, tables, and images. +- **Flexible retrieval and traceable answers** with multiple retrieval strategies, reranking, and citations. +- **Agentic capabilities** for multi-step retrieval, reasoning, tool use, and workflows. +- **Knowledge compilation** for organizing documents into structured knowledge artifacts. +- **Broad model and integration support** for building different RAG applications. --- -### Which embedding models can be deployed locally? - -Starting from `v0.22.0`, we ship only the slim edition and no longer append the **-slim** suffix to the image tag. - --- ### Where to find the version of RAGFlow? How to interpret it? @@ -60,11 +59,11 @@ Where: --- -### Why not use other open-source vector databases as the document engine? +### Why does RAGFlow use Elasticsearch or Infinity as its default document engine? -Currently, only Elasticsearch and [Infinity](https://github.com/infiniflow/infinity) meet the hybrid search requirements of RAGFlow. Most open-source vector databases have limited support for full-text search, and sparse embedding is not an alternative to full-text search. Additionally, these vector databases lack critical features essential to RAGFlow, such as phrase search and advanced ranking capabilities. - -These limitations led us to develop [Infinity](https://github.com/infiniflow/infinity), the AI-native database, from the ground up. +Elasticsearch and [Infinity](https://github.com/infiniflow/infinity) meet RAGFlow's core hybrid search requirements, including full-text search, vector search, phrase search, and advanced ranking capabilities. +RAGFlow also supports other document engines, including OpenSearch, OceanBase, SeekDB, and GaussDB. Support levels and available features may vary between document engines. +[Infinity](https://github.com/infiniflow/infinity) is an AI-native database developed by InfiniFlow and optimized for RAG workloads. --- @@ -76,21 +75,17 @@ You can deploy an open-source RAGFlow service and call it from a Python client o --- -### Why does it take longer for RAGFlow to parse a document than LangChain? +### Why does RAGFlow require substantial system resources? -We put painstaking effort into document pre-processing tasks like layout analysis, table structure recognition, and OCR (Optical Character Recognition) using our vision models. This contributes to the additional time required. +RAGFlow runs multiple components for document parsing, embedding, full-text and vector indexing, retrieval, task processing, metadata storage, caching, and object storage. Some document parsers also load or download machine-learning models and may require significant memory or GPU resources. ---- - -### Why does RAGFlow require more resources than other projects? - -RAGFlow has a number of built-in models for document structure parsing, which account for the additional computational resources. +Actual resource usage depends on the selected document engine, parser, model provider, document volume, and workload. See the deployment prerequisites and configuration documentation for the current minimum requirements. --- ### Which architectures or devices does RAGFlow support? -We officially support x86 CPU and nvidia GPU. While we also test RAGFlow on ARM64 platforms, we do not maintain RAGFlow Docker images for ARM. If you are on an ARM platform, follow [this guide](./develop/build_docker_image.mdx) to build a RAGFlow Docker image. +We officially support x86 CPUs and NVIDIA GPUs. While we also test RAGFlow on ARM64 platforms, we do not maintain RAGFlow Docker images for ARM. If you are on an ARM platform, follow [this guide](./develop/build_docker_image.mdx) to build a RAGFlow Docker image. --- @@ -118,28 +113,12 @@ RESTful: --- -### Do you support sharing dialogue through URL? +### Key differences between search and chat? -No, this feature is not supported. +- **Search** is designed for direct knowledge retrieval. It retrieves and ranks relevant content from one or more datasets and presents the results for users to review. +- **Chat** is designed for conversational question answering. It retrieves relevant knowledge and uses an LLM to generate answers, supporting multi-turn conversations and more advanced retrieval capabilities such as Agentic Retrieval. ---- - -### Do you support multiple rounds of dialogues, referencing previous dialogues as context for the current query? - -Yes, we support enhancing user queries based on existing context of an ongoing conversation: - -1. On the **Chat** page, hover over the desired assistant and select **Edit**. -2. In the **Chat Configuration** popup, click the **Prompt engine** tab. -3. Switch on **Multi-turn optimization** to enable this feature. - ---- - -### Key differences between AI search and chat? - -- **AI search**: This is a single-turn AI conversation using a predefined retrieval strategy (a hybrid search of weighted keyword similarity and weighted vector similarity) and the system's default chat model. It does not involve advanced RAG strategies like knowledge graph, auto-keyword, or auto-question. Retrieved chunks will be listed below the chat model's response. -- **AI chat**: This is a multi-turn AI conversation where you can define your retrieval strategy (a weighted reranking score can be used to replace the weighted vector similarity in a hybrid search) and choose your chat model. In an AI chat, you can configure advanced RAG strategies, such as knowledge graphs, auto-keyword, and auto-question, for your specific case. Retrieved chunks are not displayed along with the answer. - -When debugging your chat assistant, you can use AI search as a reference to verify your model settings and retrieval strategy. +Use **Search** when you want to find and inspect relevant knowledge directly, and **Chat** when you want generated answers based on that knowledge. --- @@ -160,9 +139,11 @@ See [Build a RAGFlow Docker image](./develop/build_docker_image.mdx). --- -### Cannot access https://huggingface.co +### PDF parsing fails because required Hugging Face models cannot be downloaded + +Some RAGFlow document parsers download required model files from [Hugging Face](https://huggingface.co). If the RAGFlow container cannot access Hugging Face and the files are not already cached, model initialization or document parsing may fail. -A locally deployed RAGFlow downloads OCR models from [Huggingface website](https://huggingface.co) by default. If your machine is unable to access this site, the following error occurs and PDF parsing fails: +For example: ``` FileNotFoundError: [Errno 2] No such file or directory: '/root/.cache/huggingface/hub/models--InfiniFlow--deepdoc/snapshots/be0c1e50eef6047b412d1800aa89aba4d275f997/ocr.res' @@ -193,7 +174,11 @@ To fix this issue, use https://hf-mirror.com instead: ### `Fail to access model(Ollama/xxxxx)` -Ollama may time out or fail during its first model load due to memory constraints or out-of-memory (OOM). It is best to test your local model in isolation first. If sharing hardware with other services, memory exhaustion is likely. To resolve this, switch to a smaller model or increase RAM. +This error means that RAGFlow cannot access the configured Ollama model. Check that Ollama is running, the model has been downloaded, the model name is correct, and the Ollama Base URL is reachable from the RAGFlow container. + +If the request times out while loading the model, check the Ollama logs and available memory. Try a smaller model or allocate more memory if necessary. + +See [Deploy a local LLM](./guides/models/deploy_local_llm.mdx) for more information. --- @@ -202,7 +187,7 @@ Ollama may time out or fail during its first model load due to memory constraint This error suggests that you do not have Internet access or are unable to connect to hf-mirror.com. Try the following: 1. Manually download the resource files from [huggingface.co/InfiniFlow/deepdoc](https://huggingface.co/InfiniFlow/deepdoc) to your local folder **~/deepdoc**. -2. Add a volumes to **docker-compose.yml**, for example: +2. Add a volume mapping to **docker/docker-compose.yml**, for example: ``` - ~/deepdoc:/ragflow/rag/res/deepdoc @@ -224,12 +209,6 @@ To resolve this, either download the missing file from the corresponding tag on --- -### `WARNING: can't find /ragflow/rag/res/borker.tm` - -Ignore this warning and continue. All system warnings can be ignored. - ---- - ### `network anomaly There is an abnormality in your network and you cannot connect to the server.` ![anomaly](https://github.com/infiniflow/ragflow/assets/93570324/beb7ad10-92e4-4a58-8886-bfb7cbd09e5d) @@ -248,8 +227,8 @@ You will not log in to RAGFlow unless the server is fully initialized. Run `dock * Running on all addresses (0.0.0.0) * Running on http://127.0.0.1:9380 * Running on http://x.x.x.x:9380 - INFO:werkzeug:Press CTRL+C to quit ``` +Then use the [system health API](./references/http_api_reference.md#check-system-health) to check the database, Redis, document engine, and object storage. --- @@ -263,7 +242,7 @@ Ignore this warning and continue. All system warnings can be ignored. ### `xxx tasks are ahead in the queue` -### For RAGFlow versions earlier than v0.26.0 +#### For RAGFlow versions earlier than v0.26.0 1. Clear the Redis task queue: @@ -283,7 +262,7 @@ FLUSHDB ```bash # Option 1: Restart specific container -docekr restart docker-redis-1 docker-ragflow-cpu-1 +docker restart docker-redis-1 docker-ragflow-cpu-1 # Option 2: Recreate containers via Docker Compose docker compose -f docker/docker-compose.yml down @@ -295,7 +274,7 @@ docker stop $(docker ps -aq) docker rm $(docker ps -aq) ``` -### For RAGFlow v0.26.0 and later +#### For RAGFlow v0.26.0 and later 1. Clear the Redis task queue: @@ -305,17 +284,18 @@ $ docker exec -it ragflow-redis /bin/bash $ redis-cli -a infini_rag_flow # In redis-cli select 1 -XGROUP DESTROY te.0.common_queue te.0.common_task_broker -XGROUP CREATE te.0.common_queue te.0.common_task_broker $ MKSTREAM -# When CREATE raises and error: -FLUSHDB +XGROUP DESTROY te.0.common rag_flow_svr_task_broker +XGROUP CREATE te.0.common rag_flow_svr_task_broker $ MKSTREAM + +XGROUP DESTROY te.1.common rag_flow_svr_task_broker +XGROUP CREATE te.1.common rag_flow_svr_task_broker $ MKSTREAM ``` 2. If the parser remains stuck at 0%, restart the RAGFlow containers using one of the following methods: ```bash # Option 1: Restart specific container -docekr restart docker-redis-1 docker-ragflow-cpu-1 +docker restart docker-redis-1 docker-ragflow-cpu-1 # Option 2: Recreate containers via Docker Compose docker compose -f docker/docker-compose.yml down @@ -369,7 +349,9 @@ docker compose up -d ### `Index failure` -An index failure usually indicates an unavailable Elasticsearch service. +An index failure means that RAGFlow could not write the processed document chunks to the configured document engine. + +Check the task logs, embedding model, document engine connection, and system health. If you use Elasticsearch, OpenSearch, Infinity, or another supported document engine, verify that the corresponding service is running and accessible. --- @@ -383,26 +365,20 @@ tail -f ragflow/docker/ragflow-logs/*.log ### How to check the status of each component in RAGFlow? -1. Check the status of the Elasticsearch Docker container: +1. Check the status of the RAGFlow Docker container: ```bash - $ docker ps + $ docker compose ps ``` - - *The following is an example result:* - + Review the service logs: ```bash - 5bc45806b680 infiniflow/ragflow:latest "./entrypoint.sh" 11 hours ago Up 11 hours 0.0.0.0:80->80/tcp, :::80->80/tcp, 0.0.0.0:443->443/tcp, :::443->443/tcp, 0.0.0.0:9380->9380/tcp, :::9380->9380/tcp docker-ragflow-cpu-1 - 91220e3285dd docker.elastic.co/elasticsearch/elasticsearch:8.11.3 "/bin/tini -- /usr/l…" 11 hours ago Up 11 hours (healthy) 9300/tcp, 0.0.0.0:9200->9200/tcp, :::9200->9200/tcp ragflow-es-01 - d8c86f06c56b mysql:5.7.18 "docker-entrypoint.s…" 7 days ago Up 16 seconds (healthy) 0.0.0.0:3306->3306/tcp, :::3306->3306/tcp ragflow-mysql - cd29bcb254bc pgsty/silo:RELEASE.2026-08-06T00-00-00Z "/usr/bin/docker-ent…" 2 weeks ago Up 11 hours 0.0.0.0:9001->9001/tcp, :::9001->9001/tcp, 0.0.0.0:9000->9000/tcp, :::9000->9000/tcp ragflow-minio + docker compose logs -f ragflow + ``` -2. Follow [the system health API](./references/http_api_reference.md#check-system-health) to check the health status of the Elasticsearch service. +2. Use the [system health API](./references/http_api_reference.md#check-system-health) to check the database, Redis, document engine, and object storage. -:::danger IMPORTANT -The status of a Docker container status does not necessarily reflect the status of the service. You may find that your services are unhealthy even when the corresponding Docker containers are up running. Possible reasons for this include network failures, incorrect port numbers, or DNS issues. -::: +A running container does not necessarily mean that the service inside it is healthy. Check the health API and logs for connection, port, DNS, and configuration errors. --- @@ -500,30 +476,21 @@ See [Deploy a local LLM](./guides/models/deploy_local_llm.mdx) for more informat ### Do you offer examples of using DeepDoc to parse PDF or other files? -Yes, we do. See the Python files under the **rag/app** folder. +Yes. See the parser entry points and examples in the [`rag/app`](https://github.com/infiniflow/ragflow/tree/main/rag/app) directory. + +For example, `rag/app/naive.py` shows how RAGFlow selects and invokes document parsers for different file types. --- ### `FileNotFoundError: [Errno 2] No such file or directory` -1. Check the status of the MinIO Docker container: +This error means that RAGFlow cannot find a required file. Check the complete error message and stack trace to identify the missing path. - ```bash - $ docker ps - ``` - - *The status of a healthy Elasticsearch component should look as follows:* - - ```bash - cd29bcb254bc pgsty/silo:RELEASE.2026-08-06T00-00-00Z "/usr/bin/docker-ent…" 2 weeks ago Up 11 hours 0.0.0.0:9001->9001/tcp, :::9001->9001/tcp, 0.0.0.0:9000->9000/tcp, :::9000->9000/tcp ragflow-minio - ``` - -2. Follow [the system health API](./references/http_api_reference.md#check-system-health) to check the health status of the Elasticsearch service. - -:::danger IMPORTANT -The status of a Docker container status does not necessarily reflect the status of the service. You may find that your services are unhealthy even when the corresponding Docker containers are up running. Possible reasons for this include network failures, incorrect port numbers, or DNS issues. -::: +- If a model file is missing, check whether the required model was downloaded successfully. +- If an uploaded document is missing, check the configured object storage service. +- If a temporary or local file is missing, check the container volume mappings and file permissions. +Use the [system health API](./references/http_api_reference.md#check-system-health) to verify the configured object storage and other dependencies. --- ## Usage @@ -566,19 +533,6 @@ It is not recommended to manually change the 32-file batch upload limit. However --- -### `Error: Range of input length should be [1, 30000]` - -This error occurs because there are too many chunks matching your search criteria. Try reducing the **TopN** and increasing **Similarity threshold** to fix this issue: - -1. Click **Chat** in the middle top of the page. -2. Right-click the desired conversation > **Edit** > **Prompt engine** -3. Reduce the **TopN** and/or raise **Similarity threshold**. -4. Click **OK** to confirm your changes. - -![topn](https://github.com/infiniflow/ragflow/assets/93570324/7ec72ab3-0dd2-4cff-af44-e2663b67b2fc) - ---- - ### How to get an API key for integration with third-party applications? See [Acquire a RAGFlow API key](./develop/acquire_ragflow_api_key.md). @@ -595,7 +549,11 @@ See [Upgrade RAGFlow](./administrator/upgrade_ragflow.mdx) for more information. To switch your document engine from Elasticsearch to [Infinity](https://github.com/infiniflow/infinity): -1. Stop all running containers: +:::danger WARNING +Switching the document engine requires rebuilding the document indexes. The following command deletes Docker volumes and existing data. Back up any data you need before continuing. +::: + +1. Stop all running containers and remove the existing volumes: ```bash $ docker compose -f docker/docker-compose.yml down -v @@ -604,18 +562,25 @@ To switch your document engine from Elasticsearch to [Infinity](https://github.c `-v` will delete all Docker container volumes, and the existing data will be cleared. ::: -2. In **docker/.env**, set `DOC_ENGINE=${DOC_ENGINE:-infinity}` +2. Set the following value in **docker/.env** : + +```env + DOC_ENGINE=infinity +``` + 3. Restart your Docker image: ```bash - $ docker compose -f docker-compose.yml up -d + $ docker compose -f docker/docker-compose.yml up -d ``` --- -### Where are my uploaded files stored in RAGFlow's image? +### Where are uploaded files stored in RAGFlow? + +Uploaded files are stored in the configured object storage backend. MinIO is used by default, while other supported options include Amazon S3, Azure Blob Storage, Alibaba Cloud OSS, Google Cloud Storage, and OpenDAL-compatible storage. -All uploaded files are stored in Minio, RAGFlow's object storage solution. For instance, if you upload your file directly to a dataset, it is located at `/filename`. +The internal bucket and object path depend on how and where the file was uploaded. Manage uploaded files through RAGFlow instead of relying on a fixed storage path. --- @@ -625,6 +590,67 @@ You can control the batch size for document parsing and embedding by setting the --- +### Why can't I retrieve relevant content in Search or Chat even though the document was parsed successfully? + +Successful parsing only means that the document has been parsed and chunked. It does not guarantee that relevant content can be retrieved. + +First, use **Retrieval testing** to check whether the expected chunks can be retrieved. If not, check the chunking results, embedding model, similarity threshold, and reranker settings. If the expected chunks are retrieved but Chat still gives an incorrect answer, check the Chat retrieval settings, system prompt, and LLM. + +--- + +### Why does the same query produce different results in Retrieval testing, Search, and Chat? + +**Retrieval testing** is mainly used to evaluate whether relevant chunks can be retrieved from a dataset. **Search** further filters and ranks retrieved content according to its configuration, while **Chat** uses the retrieved content as context for an LLM to generate an answer. + +Therefore, even when using the same dataset, differences in retrieval settings, reranking, and answer generation can lead to different results. + +--- + +### How can I tell whether a problem comes from document parsing, chunking, retrieval, or answer generation? + +Check the RAG pipeline step by step: + +1. Verify that the document has been parsed correctly. +2. Check whether the resulting chunks contain the expected content. +3. Use **Retrieval testing** to verify that the relevant chunks can be retrieved. +4. If retrieval works correctly but Chat or Agent produces an unexpected answer, check the application settings, system prompt, and LLM. + +This helps identify which stage of the pipeline is causing the problem. + +--- + +### Can the same dataset be used by Search, Chat, and Agent? + +Yes. The same dataset can be used by different knowledge applications and Agents. + +The dataset manages and indexes the underlying knowledge, while Search, Chat, and Agent use that knowledge in different ways. Changing application-level settings generally does not modify the original documents or chunks in the dataset. + +--- + +### Should I adjust chunking, retrieval settings, or models first? + +Start by verifying that the document is parsed and chunked correctly. Then use **Retrieval testing** to evaluate retrieval quality. + +If retrieval needs improvement, adjust settings such as the similarity threshold, vector similarity weight, or reranker. If retrieval results are already relevant but the generated answer is still unsatisfactory, consider adjusting the prompt or changing the LLM. + +--- + +### What needs to be reprocessed after changing the embedding model, reranker, or LLM? + +- Changing the **embedding model** requires rebuilding the document indexes. RAGFlow does not normally allow you to change the embedding model after documents in the dataset have been parsed. Create a new dataset or remove the existing parsed data before using another embedding model. +- Changing the **reranker** affects only the ranking of retrieved results and does not require reparsing the documents. +- Changing the **LLM** affects query understanding and answer generation and does not normally require reparsing the dataset. + +--- + +### Why can the model still hallucinate when the answer exists in the dataset? + +Having the correct information in the dataset does not guarantee that it will be retrieved or that the LLM will strictly follow the retrieved context. + +Check whether the content has been indexed correctly, whether the relevant chunks are retrieved, and whether the model uses the retrieved context appropriately when generating its answer. + +--- + ### How to accelerate the question-answering speed of my chat assistant? To reduce response latency, consider the following: @@ -635,8 +661,6 @@ To reduce response latency, consider the following: - Use a reranker only when it provides a meaningful improvement in retrieval quality. - Make sure the deployed model service has sufficient computing resources and low network latency. -See [here](./guides/chat/best_practices/accelerate_question_answering.mdx). - --- ### How to accelerate the question-answering speed of my Agent? diff --git a/docs/guides/chat/testing_and_evaluation.md b/docs/guides/chat/Mutimodel_comparison_and_FAQ.md similarity index 66% rename from docs/guides/chat/testing_and_evaluation.md rename to docs/guides/chat/Mutimodel_comparison_and_FAQ.md index 3889b31d4d8..282a43b72af 100644 --- a/docs/guides/chat/testing_and_evaluation.md +++ b/docs/guides/chat/Mutimodel_comparison_and_FAQ.md @@ -1,8 +1,8 @@ --- sidebar_position: 4 -title: Multimodel Comparison -sidebar_label: Multimodel_Comparison -slug: /chat_Multimodel_Comparison +title: Multimodel Comparison & FAQ +sidebar_label: Multimodel_Comparison_and_FAQ +slug: /chat_Multimodel_Comparison_and_FAQ sidebar_custom_props: categoryIcon: LucideTestTube --- @@ -21,3 +21,11 @@ Select the models to compare, enter a test question, and run the comparison. Foc Use representative questions from actual business scenarios instead of selecting a model based on a single question. Multi-model comparison is primarily intended for model selection and debugging. For example, after changing a model provider or model version, use the same questions to quickly compare the practical performance of the old and new models. +# FAQ +## Do you support multiple rounds of dialogues, referencing previous dialogues as context for the current query? + +Yes, we support enhancing user queries based on existing context of an ongoing conversation: + +1. On the **Chat** page, hover over the desired assistant and select **Edit**. +2. In the **Chat Configuration** popup, click the **Prompt engine** tab. +3. Switch on **Multi-turn optimization** to enable this feature. diff --git a/docs/guides/dataset/notes_and_faqs.md b/docs/guides/dataset/notes_and_faqs.md index 82304ac7e24..4c52eefd5b5 100644 --- a/docs/guides/dataset/notes_and_faqs.md +++ b/docs/guides/dataset/notes_and_faqs.md @@ -107,6 +107,11 @@ The following screenshot shows retrieval testing using the knowledge graph. It s Yes. Your LLM participates in analyzing your query and extracting relevant entities and relationships from the knowledge graph. This also explains why extra tokens and time are consumed. +#### Why does it take longer for RAGFlow to parse a document than LangChain? + +We put painstaking effort into document pre-processing tasks like layout analysis, table structure recognition, and OCR (Optical Character Recognition) using our vision models. This contributes to the additional time required. + + ## Best Practices: Index Acceleration A checklist for accelerating document parsing and indexing. From fbd374e92f391ed26d3cca28d9988f038d0d84a9 Mon Sep 17 00:00:00 2001 From: jay77721 <164177721+jay77721@users.noreply.github.com> Date: Fri, 11 Sep 2026 18:52:15 +0800 Subject: [PATCH 119/568] refactor(parser): unify parser outputs to structured JSON items (#19467) --- internal/ingestion/component/chunker/page.go | 7 +- .../ingestion/component/chunker/qa_id_test.go | 2 +- .../ingestion/component/chunker/token_test.go | 74 ++ .../ingestion/component/media_dispatch.go | 74 +- .../component/media_dispatch_test.go | 29 +- internal/ingestion/component/parser.go | 379 ++++------ .../ingestion/component/parser_check_test.go | 5 +- .../ingestion/component/parser_dispatch.go | 276 ++----- .../parser_dispatch_pdf_vision_cgo_test.go | 4 +- .../component/parser_dispatch_test.go | 711 ++++++++---------- internal/ingestion/component/parser_test.go | 222 +++--- .../component/pdf_vision_dispatch.go | 161 ++-- .../component/pdf_vision_dispatch_test.go | 71 +- internal/ingestion/component/schema/parser.go | 123 +-- .../ingestion/component/schema/schema_test.go | 96 +-- .../ingestion/component/vision_enhancement.go | 5 +- .../component/vision_enhancement_test.go | 33 +- internal/parser/parser/charset_test.go | 12 +- internal/parser/parser/csv_parser.go | 29 +- internal/parser/parser/csv_parser_test.go | 124 +++ internal/parser/parser/doc_parser.go | 64 +- .../parser/parser/doc_parser_synth_test.go | 18 +- internal/parser/parser/email_parser.go | 82 +- internal/parser/parser/email_parser_test.go | 60 +- internal/parser/parser/markdown_parser.go | 22 +- .../parser/parser/office_parsers_no_cgo.go | 5 - internal/parser/parser/office_table_render.go | 38 +- .../parser/parser/office_table_render_test.go | 30 +- internal/parser/parser/parse_result.go | 83 +- internal/parser/parser/parse_result_test.go | 11 + internal/parser/parser/picture_parser.go | 5 +- internal/parser/parser/xls_parser.go | 29 +- internal/parser/parser/xls_parser_test.go | 112 +++ internal/parser/parser/xls_tcadp_test.go | 10 +- .../parser/parser/xlsx_parse_method_test.go | 9 +- internal/parser/parser/xlsx_parser.go | 22 +- internal/service/file/file_content.go | 57 +- internal/service/file/file_content_test.go | 93 ++- 38 files changed, 1629 insertions(+), 1558 deletions(-) create mode 100644 internal/parser/parser/csv_parser_test.go create mode 100644 internal/parser/parser/xls_parser_test.go diff --git a/internal/ingestion/component/chunker/page.go b/internal/ingestion/component/chunker/page.go index f9d8d0621a5..a59e2aeadb5 100644 --- a/internal/ingestion/component/chunker/page.go +++ b/internal/ingestion/component/chunker/page.go @@ -87,10 +87,9 @@ func (c *PageChunkerComponent) invoke(_ context.Context, inputs map[string]any) }, nil } - // The presentation template only configures pdf and slides - // parser setups, matching Python's restriction to .pptx/.ppt/.pdf. - // The upstream parser therefore always emits per-slide JSON, never - // flat text/markdown/html, so every payload keeps one-chunk-per-slide. + // The Page chunker preserves one incoming JSON item per output chunk. + // It has no file-family restriction: item granularity is determined by + // the upstream parser backend. items := slideItems(upstream.JSONResult, upstream.Chunks) if len(items) == 0 { return emptyOutputs(), nil diff --git a/internal/ingestion/component/chunker/qa_id_test.go b/internal/ingestion/component/chunker/qa_id_test.go index 22f728bc135..b175c3a87bd 100644 --- a/internal/ingestion/component/chunker/qa_id_test.go +++ b/internal/ingestion/component/chunker/qa_id_test.go @@ -9,7 +9,7 @@ import ( ) // xlsxQATableHTML is the HTML the spreadsheet parser emits for a -// headerless two-column Q&A workbook (renderSheetTables repeats the +// headerless two-column Q&A workbook (the table renderer repeats the // first row as the /
Contact header; extractQATable still reads it as a pair). const xlsxQATableHTML = ` diff --git a/internal/ingestion/component/chunker/token_test.go b/internal/ingestion/component/chunker/token_test.go index 93095b954f9..4fe546146e9 100644 --- a/internal/ingestion/component/chunker/token_test.go +++ b/internal/ingestion/component/chunker/token_test.go @@ -228,6 +228,41 @@ func TestTokenChunker_InvokeJSONPayload(t *testing.T) { } } +func TestTokenChunker_InvokeJSONPayload_IndexesHeaderOnlyEmail(t *testing.T) { + c, err := NewTokenChunker(map[string]any{ + "delimiter_mode": "delimiter", + "delimiters": []string{"\n"}, + }) + if err != nil { + t.Fatalf("NewTokenChunker: %v", err) + } + // Email's structured body item can have no text for a header-only + // message. Parser emits the second text item specifically so headers are + // still indexed through the JSON path. + items := []map[string]any{ + {"from": "sender@example.com", "subject": "Status", "doc_type_kwd": "text"}, + {"text": "from:sender@example.com\nsubject:Status\n", "doc_type_kwd": "text"}, + } + out, err := c.Invoke(context.Background(), nil, map[string]any{ + "name": "message.eml", + "output_format": "json", + "json": items, + }) + if err != nil { + t.Fatalf("Invoke: %v", err) + } + chunks, ok := out["chunks"].([]map[string]any) + if !ok || len(chunks) == 0 { + t.Fatalf("chunks missing: %#v", out["chunks"]) + } + for _, chunk := range chunks { + if text, _ := chunk["text"].(string); strings.Contains(text, "subject:Status") { + return + } + } + t.Fatalf("header item was not indexed: %#v", chunks) +} + // TestTokenChunker_InvokeJSONPayload_KeepsNonTextStandalone is the // regression lock for #17889: when merging adjacent segments, only // "text" segments may be merged; "table"/"image" (any non-text type) @@ -281,6 +316,10 @@ func TestTokenChunker_InvokeJSONPayload_KeepsNonTextStandalone(t *testing.T) { if got != wantTypes[i] { t.Errorf("chunk %d: doc_type_kwd = %q, want %q (full chunk: %+v)", i, got, wantTypes[i], ch) } + ckType, _ := ch["ck_type"].(string) + if ckType != wantTypes[i] { + t.Errorf("chunk %d: ck_type = %q, want %q (derived from doc_type_kwd)", i, ckType, wantTypes[i]) + } } // The two text segments on either side of the table/image must remain // distinct — they must NOT be merged across the non-text segments. @@ -357,6 +396,41 @@ func TestTokenChunker_InputsOutputs_NonEmpty(t *testing.T) { } } +// TestTokenChunker_SpreadsheetTablePreservesSelectionRange guards the Parser +// JSON path: spreadsheet positions describe a sheet selection, not a PDF +// bounding box, and a table item must pass through without proportional text +// splitting or coordinate rewriting. +func TestTokenChunker_SpreadsheetTablePreservesSelectionRange(t *testing.T) { + c, err := NewTokenChunker(map[string]any{"delimiter": "\n"}) + if err != nil { + t.Fatalf("NewTokenChunker: %v", err) + } + wantPositions := [][]float64{{1, 2, 10, 1, 5}} + out, err := c.Invoke(t.Context(), nil, map[string]any{ + "name": "book.xlsx", + "output_format": "json", + "json": []map[string]any{{ + "text": "
Sheet1
门打不开怎么办请家人回来开门
\n
A
B
", + "doc_type_kwd": "table", + "positions": wantPositions, + "sheet": "Sheet1", + }}, + }) + if err != nil { + t.Fatalf("Invoke: %v", err) + } + chunks, _ := out["chunks"].([]map[string]any) + if len(chunks) != 1 { + t.Fatalf("chunks = %d, want one unsplit table item", len(chunks)) + } + if got := chunks[0]["ck_type"]; got != "table" { + t.Errorf("ck_type = %v, want table", got) + } + if got := chunks[0]["positions"]; !reflect.DeepEqual(got, wantPositions) { + t.Errorf("positions = %#v, want unchanged %#v", got, wantPositions) + } +} + // TestTokenChunker_NewRejectsBadParam enforces the param validation // at construction time (mirrors python `check()`). func TestTokenChunker_NewRejectsBadParam(t *testing.T) { diff --git a/internal/ingestion/component/media_dispatch.go b/internal/ingestion/component/media_dispatch.go index 08eeb38c748..8fdd9cd1d63 100644 --- a/internal/ingestion/component/media_dispatch.go +++ b/internal/ingestion/component/media_dispatch.go @@ -21,7 +21,7 @@ // // These follow the maybeDispatchPDFVision pattern: they bypass // dispatchParse and call the model directly from the component -// layer, returning a parserDispatchResult. +// layer, returning a parser.ParseResult. package component @@ -65,12 +65,12 @@ func maybeDispatchVideo( binary []byte, inputs map[string]any, setups map[string]schema.ParserSetup, -) (parserDispatchResult, bool, error) { +) (parser.ParseResult, bool, error) { if fileType != utility.FileTypeVIDEO { - return parserDispatchResult{}, false, nil + return parser.ParseResult{}, false, nil } if _, ok := setups["video"]; !ok { - return parserDispatchResult{}, false, nil + return parser.ParseResult{}, false, nil } // Video parsing is intentionally not implemented yet: the underlying @@ -81,8 +81,10 @@ func maybeDispatchVideo( // video_url. Returning an explicit error is safer than silently producing // a description from the prompt text alone. The real implementation must // be provider-specific (OpenAI-compatible: frame extraction -> image_url; - // Gemini: raw-bytes inline_data; Qwen: file://) - return parserDispatchResult{}, true, + // Gemini: raw-bytes inline_data; Qwen: file://). + // When video analysis is implemented, it emits standard Text JSON items: + // [{"text": transcript, "doc_type_kwd": "text"}] with output_format "json". + return parser.ParseResult{}, true, fmt.Errorf("Parser: video parsing is not yet supported; underlying video analysis capability is pending") } @@ -102,17 +104,17 @@ func maybeDispatchImage( binary []byte, inputs map[string]any, setups map[string]schema.ParserSetup, -) (parserDispatchResult, bool, error) { +) (parser.ParseResult, bool, error) { if fileType != utility.FileTypeVISUAL { - return parserDispatchResult{}, false, nil + return parser.ParseResult{}, false, nil } setup, ok := setups["image"] if !ok { - return parserDispatchResult{}, false, nil + return parser.ParseResult{}, false, nil } tenantID := getStringOr(inputs, "tenant_id", "") if tenantID == "" { - return parserDispatchResult{}, true, + return parser.ParseResult{}, true, fmt.Errorf("parser: image requires tenant_id") } @@ -181,7 +183,7 @@ func maybeDispatchImage( if ocrText != "" { return imageDispatchResult(ocrText, dataURI), true, nil } - return parserDispatchResult{}, true, + return parser.ParseResult{}, true, fmt.Errorf("parser: picture image2text model: %w", err) } @@ -205,7 +207,7 @@ func maybeDispatchImage( if ocrText != "" { return imageDispatchResult(ocrText, dataURI), true, nil } - return parserDispatchResult{}, true, + return parser.ParseResult{}, true, fmt.Errorf("parser: picture describe: %w", err) } vlmText := "" @@ -230,10 +232,9 @@ func maybeDispatchImage( // family: a single item carrying the combined text, the image attachment // (data URI), and doc_type_kwd "image". Mirrors Python // rag/app/picture.py:71-72. -func imageDispatchResult(text, dataURI string) parserDispatchResult { - return parserDispatchResult{ +func imageDispatchResult(text, dataURI string) parser.ParseResult { + return parser.ParseResult{ OutputFormat: "json", - DocType: "image", JSON: []map[string]any{{ "text": text, "image": dataURI, @@ -256,17 +257,17 @@ func maybeDispatchAudio( binary []byte, inputs map[string]any, setups map[string]schema.ParserSetup, -) (parserDispatchResult, bool, error) { +) (parser.ParseResult, bool, error) { if fileType != utility.FileTypeAURAL { - return parserDispatchResult{}, false, nil + return parser.ParseResult{}, false, nil } setup, ok := setups["audio"] if !ok { - return parserDispatchResult{}, false, nil + return parser.ParseResult{}, false, nil } tenantID := getStringOr(inputs, "tenant_id", "") if tenantID == "" { - return parserDispatchResult{}, true, + return parser.ParseResult{}, true, fmt.Errorf("parser: audio requires tenant_id") } @@ -286,20 +287,20 @@ func maybeDispatchAudio( driver, modelName, apiConfig, _, err = resolveTenantModelByType(ctx, db, tenantID, entity.ModelTypeSpeech2Text) } if err != nil { - return parserDispatchResult{}, true, + return parser.ParseResult{}, true, fmt.Errorf("parser: audio speech2text model: %w", err) } tmpFile, err := writeTempAudioFile(filename, binary) if err != nil { - return parserDispatchResult{}, true, + return parser.ParseResult{}, true, fmt.Errorf("parser: audio temp file: %w", err) } defer os.Remove(tmpFile) resp, err := driver.TranscribeAudio(ctx, &modelName, &tmpFile, apiConfig, nil, nil) if err != nil { - return parserDispatchResult{}, true, + return parser.ParseResult{}, true, fmt.Errorf("Parser: audio transcription: %w", err) } @@ -308,29 +309,12 @@ func maybeDispatchAudio( transcription = resp.Text } - outputFormat, _ := setup["output_format"].(string) - if outputFormat == "" { - outputFormat = "json" - } - // Diff 2.11: when output_format is "json" the transcription must be - // carried as a JSON item. Returning it only in Text made the Invoke - // switch silently drop it (the switch has no "json" branch and the - // JSON slice was empty). Mirror the JSON-item shape used by the - // other parser branches. - if outputFormat == "json" { - return parserDispatchResult{ - OutputFormat: "json", - DocType: "audio", - JSON: []map[string]any{{ - "text": transcription, - "doc_type_kwd": "audio", - }}, - }, true, nil - } - return parserDispatchResult{ - OutputFormat: outputFormat, - DocType: "audio", - Text: transcription, + return parser.ParseResult{ + OutputFormat: "json", + JSON: []map[string]any{{ + "text": transcription, + "doc_type_kwd": "text", + }}, }, true, nil } diff --git a/internal/ingestion/component/media_dispatch_test.go b/internal/ingestion/component/media_dispatch_test.go index 89cfe824880..f07e675ce77 100644 --- a/internal/ingestion/component/media_dispatch_test.go +++ b/internal/ingestion/component/media_dispatch_test.go @@ -318,15 +318,12 @@ func TestMaybeDispatchAudio_JSONCarriesTranscription(t *testing.T) { if got, _ := res.JSON[0]["text"].(string); got != want { t.Fatalf("JSON[0].text = %q, want %q", got, want) } - if got, _ := res.JSON[0]["doc_type_kwd"].(string); got != "audio" { - t.Fatalf("JSON[0].doc_type_kwd = %q, want audio", got) + if got, _ := res.JSON[0]["doc_type_kwd"].(string); got != "text" { + t.Fatalf("JSON[0].doc_type_kwd = %q, want text", got) } } -// TestMaybeDispatchAudio_TextCarriesTranscription guards the text path: with -// output_format "text" the transcription stays in the Text field and JSON is -// empty (current default after aligning with Python parser.py:232). -func TestMaybeDispatchAudio_TextCarriesTranscription(t *testing.T) { +func TestMaybeDispatchAudio_IgnoresLegacyOutputFormat(t *testing.T) { origResolver := resolveTenantModelByType defer func() { resolveTenantModelByType = origResolver }() @@ -355,24 +352,20 @@ func TestMaybeDispatchAudio_TextCarriesTranscription(t *testing.T) { if !dispatched { t.Fatalf("expected dispatched=true for AURAL file") } - if res.OutputFormat != "text" { - t.Fatalf("OutputFormat = %q, want text", res.OutputFormat) + if res.OutputFormat != "json" { + t.Fatalf("OutputFormat = %q, want json", res.OutputFormat) } - if res.Text != want { - t.Fatalf("Text = %q, want %q", res.Text, want) + if len(res.JSON) != 1 { + t.Fatalf("JSON len = %d, want 1", len(res.JSON)) } - if len(res.JSON) != 0 { - t.Fatalf("JSON len = %d, want 0 for text output", len(res.JSON)) + if got, _ := res.JSON[0]["text"].(string); got != want { + t.Fatalf("JSON[0].text = %q, want %q", got, want) } } // TestMaybeDispatchAudio_DefaultOutputFormatJson covers the -// maybeDispatchAudio fallback: when an audio setup omits -// output_format entirely, the dispatch defaults to "json" and wraps -// the transcription as a JSON item. (The defaultSetups value is -// "text" to mirror the Python audio setup in parser.py; this test -// deliberately supplies an empty setup to exercise the fallback -// inside the dispatch itself.) +// maybeDispatchAudio always returns a JSON transcription item, including when +// the setup has no output_format key. func TestMaybeDispatchAudio_DefaultOutputFormatJson(t *testing.T) { const want = "hello world" drv := &audioTranscribeDriver{transcription: want} diff --git a/internal/ingestion/component/parser.go b/internal/ingestion/component/parser.go index 946d1da9300..d264ac95136 100644 --- a/internal/ingestion/component/parser.go +++ b/internal/ingestion/component/parser.go @@ -28,10 +28,8 @@ // - Per-page parallelism is delegated to the parser backends // (e.g. internal/deepdoc/parser/pdf fans out one worker per // page and assembles the results in page order). This -// component only reshapes the parser output into the -// schema.Page layout and keeps the deterministic, page-number -// sorted merge contract (plan §8 R8) that the downstream -// chunker / tokenizer rely on for stable chunk IDs. +// component normalizes the parser output into structured JSON +// items while preserving the backend's deterministic item order. // // - Progress (start/done callback) and elapsed-time stamping // (_created_time / _elapsed_time) are owned by the canvas @@ -74,15 +72,14 @@ // tenant default models (resolveTenantModelByType) rather than // setup["vlm"]["llm_id"], so that check is intentionally omitted. // -// - NO PERSISTENCE: parsed pages live only in the per-run -// output map, exactly as the schema.Page type is intended. +// - NO PERSISTENCE: structured parser items live only in the per-run +// output map. package component import ( "context" "errors" "fmt" - "sort" "strings" "unicode/utf8" @@ -93,6 +90,7 @@ import ( "ragflow/internal/common" "ragflow/internal/ingestion/component/globals" "ragflow/internal/ingestion/component/schema" + "ragflow/internal/parser/parser" "ragflow/internal/utility" ) @@ -105,43 +103,41 @@ const ComponentNameParser = "Parser" const pageFormFeed = '\f' // ParserComponent runs the configured parser branch against the -// upstream "binary" payload and returns a deterministic, page- -// sorted slice of schema.Page values. +// upstream "binary" payload and returns structured parser outputs. // // The instance is safe for concurrent invocation: each Invoke call // builds its own per-batch goroutine tree and merges results in // the goroutine that returned from Invoke. The static Param is // read-only after construction. type ParserComponent struct { - Setups map[string]schema.ParserSetup - Param schema.ParserParam + setups map[string]schema.ParserSetup } // NewParserComponent constructs a Parser from a DSL param map. -// The map is decoded into schema.ParserParam.Defaults() and then -// overlaid with the supplied values. This matches the Python -// "default + override" pattern in parser.py:ParserParam.__init__. +// The default setups are overlaid with the supplied values. Historical +// output_format values are accepted but normalized to JSON so downstream +// components consume one parser output protocol. This applies to every +// family, including PDF and office documents: Markdown is an internal +// backend representation only and is never a public Parser output. // -// Param map shape (all keys optional; missing keys fall back to -// schema.ParserParam.Defaults() values): +// Param map shape (all keys optional): // // { // "pdf": map[string]any, // "docx": map[string]any, // ... -// "allowed_output_format": map[string][]string, // } // // Errors here surface as canvas compile failures so a malformed // param is caught at build time rather than mid-run. func NewParserComponent(params map[string]any) (runtime.Component, error) { - p := schema.ParserParam{}.Defaults() s := defaultSetups() if params == nil { - return &ParserComponent{Setups: s, Param: p}, nil + normalizeParserOutputFormats(s) + return &ParserComponent{setups: s}, nil } for k, raw := range params { - if k == "outputs" { + if k == "outputs" || k == "allowed_output_format" { continue } ftCfg, ok := raw.(map[string]any) @@ -152,33 +148,61 @@ func NewParserComponent(params map[string]any) (runtime.Component, error) { s[k] = schema.ParserSetup{} } for fk, fv := range ftCfg { - s[k][fk] = fv + s[k][fk] = cloneParserSetupValue(fv) } } - if rawAllowed, ok := params["allowed_output_format"].(map[string]any); ok { - allowed := make(map[string][]string, len(rawAllowed)) - for fileType, raw := range rawAllowed { - list, ok := raw.([]any) - if !ok { - continue - } - formats := make([]string, 0, len(list)) - for _, item := range list { - if s, ok := item.(string); ok { - formats = append(formats, s) - } - } - allowed[fileType] = formats - } - p.AllowedOutputFormat = allowed - } - pc := &ParserComponent{Setups: s, Param: p} + normalizeParserOutputFormats(s) + pc := &ParserComponent{setups: s} if err := pc.Check(); err != nil { return nil, fmt.Errorf("parser: %w", err) } return pc, nil } +func normalizeParserOutputFormats(setups map[string]schema.ParserSetup) { + // The Go Parser component intentionally exposes JSON only. Keep this + // normalization unconditional so PDF/office legacy Markdown settings + // cannot silently select a second public output path. + for _, setup := range setups { + setup["output_format"] = "json" + } +} + +func cloneParserSetupValue(value any) any { + switch v := value.(type) { + case map[string]any: + cloned := make(map[string]any, len(v)) + for key, nested := range v { + cloned[key] = cloneParserSetupValue(nested) + } + return cloned + case schema.ParserSetup: + cloned := make(schema.ParserSetup, len(v)) + for key, nested := range v { + cloned[key] = cloneParserSetupValue(nested) + } + return cloned + case []any: + cloned := make([]any, len(v)) + for i, nested := range v { + cloned[i] = cloneParserSetupValue(nested) + } + return cloned + case []string: + return append([]string(nil), v...) + case []int: + return append([]int(nil), v...) + case [][]int: + cloned := make([][]int, len(v)) + for i, nested := range v { + cloned[i] = append([]int(nil), nested...) + } + return cloned + default: + return value + } +} + // Check mirrors the applicable subset of Python ParserParam.check() // (rag/flow/parser/parser.py:251-321). Runs at construction time so // a malformed DSL surfaces as a canvas compile failure rather than a @@ -186,8 +210,6 @@ func NewParserComponent(params map[string]any) (runtime.Component, error) { // (Python raises ValueError on the first failure). // // NOT covered here (intentional): -// - output_format whitelist: already enforced at Invoke time by -// resolveOutputFormat (parser_dispatch.go:100-122). // - audio/video vlm.llm_id: Go media_dispatch uses tenant default // models (resolveTenantModelByType), not setup["vlm"]["llm_id"]. // The Python flow check() for vlm.llm_id does not apply — Go @@ -195,7 +217,7 @@ func NewParserComponent(params map[string]any) (runtime.Component, error) { // valid audio/video pipeline (see ingestion_pipeline_audio.json). func (c *ParserComponent) Check() error { // PDF family (parser.py:252-261). - if pdf, ok := c.Setups["pdf"]; ok { + if pdf, ok := c.setups["pdf"]; ok { pm, _ := pdf["parse_method"].(string) if pm == "" { return errors.New("parse method abnormal. does not support empty value") @@ -214,7 +236,7 @@ func (c *ParserComponent) Check() error { } } // image family (parser.py:283-287). - if img, ok := c.Setups["image"]; ok { + if img, ok := c.setups["image"]; ok { pm, _ := img["parse_method"].(string) // OCR mode does not need a VLM language; any other value does. if pm != "ocr" { @@ -252,7 +274,7 @@ func defaultSetups() map[string]schema.ParserSetup { "spreadsheet": { "parse_method": "deepdoc", "flatten_media_to_text": false, - "output_format": "html", + "output_format": "json", "suffix": []string{"xls", "xlsx", "csv"}, }, "doc": { @@ -314,11 +336,11 @@ func defaultSetups() map[string]schema.ParserSetup { "aiff", "au", "midi", "wma", "realaudio", "vqf", "oggvorbis", "ape", }, - "output_format": "text", + "output_format": "json", }, "video": { "suffix": []string{"mp4", "avi", "mkv"}, - "output_format": "text", + "output_format": "json", "prompt": "", }, "epub": { @@ -336,39 +358,54 @@ func defaultSetups() map[string]schema.ParserSetup { // reads the following from the inputs map at Invoke time: // // binary ([]byte, optional) — file bytes from upstream File. -// When absent, Parser resolves -// them from bucket/path or doc_id. +// When absent, Parser resolves them from +// bucket/path or doc_id. +// name (string, optional) — resolved source filename. +// file (map[string]any, optional) — source descriptor; its name is +// used when name is absent. +// file_type (string, optional) — explicit parser routing hint. +// lang (string, optional) — language forwarded to downstream stages. // doc_id (string, optional) — document ID used for naming and, // when binary is absent, storage lookup. func (c *ParserComponent) Inputs() map[string]string { return map[string]string{ - "binary": "Optional file bytes ([]byte). When absent, Parser resolves them from bucket/path or doc_id.", - "doc_id": "Optional document ID (string). Used for downstream correlation and doc_id-driven storage lookup.", - "bucket": "Optional storage bucket override. Used when binary is absent.", - "path": "Optional storage object key override. Used when binary is absent.", + "binary": "Optional file bytes ([]byte). When absent, Parser resolves them from bucket/path or doc_id.", + "name": "Optional resolved source filename. Takes precedence over file.name.", + "file": "Optional source file descriptor (map[string]any). file.name is used when name is absent.", + "file_type": "Optional explicit parser routing hint (string).", + "lang": "Optional language for downstream tokenization (string).", + "doc_id": "Optional document ID (string). Used for downstream correlation and doc_id-driven storage lookup.", + "bucket": "Optional storage bucket override. Used when binary is absent.", + "path": "Optional storage object key override. Used when binary is absent.", } } // Outputs returns the public surface that downstream ingestion // components (Chunker, Tokenizer, Extractor) can wire into. // -// pages []schema.Page — sorted by PageNumber. Deterministic -// merge per plan §8 R8. -// name string — carried over from the upstream file/document +// name string — carried over from the upstream file/document // name (or doc_id when no name is available). -// output_format string — "text" when emitting text pages, -// otherwise the parser-selected wire -// format. -// _ERROR string — populated when the component short- -// circuits with an error message -// (mirrors Python set_output("_ERROR", ...)). +// output_format string — always "json". +// json []map[string]any — canonical structured parser items. +// lang string — language for tokenization. +// file map[string]any — backend-produced file metadata, when present. +// doc_id string — source document ID, when present. +// bucket string — source storage bucket, when present. +// path string — source storage path, when present. +// +// Parser failures are returned as Go errors. The canvas execution wrapper +// preserves that error path and does not convert failures into an _ERROR +// output field. func (c *ParserComponent) Outputs() map[string]string { return map[string]string{ - "pages": "[]schema.Page: parsed pages sorted by PageNumber.", "name": "string: the upstream file/document name (or doc_id when no name is available).", - "output_format": "string: the active output format (\"text\" when emitting text pages).", + "output_format": "string: always \"json\".", + "json": "[]map[string]any: canonical structured parser items.", "lang": "string: the language for tokenization (e.g. English, Dutch, Chinese).", - "_ERROR": "string: set on short-circuit errors.", + "file": "map[string]any: backend-produced file metadata, when present.", + "doc_id": "string: source document ID, when present.", + "bucket": "string: source storage bucket, when present.", + "path": "string: source storage object path, when present.", } } @@ -377,9 +414,9 @@ func (c *ParserComponent) Outputs() map[string]string { // Returns: // // { -// "pages": []schema.Page (sorted by PageNumber), -// "name": string (from inputs["doc_id"]), -// "output_format": "text", +// "name": string (from inputs["name"], file.name, or doc_id), +// "output_format": "json", +// "json": []map[string]any, // "lang": string (from inputs["lang"]; e.g. English, Dutch), // "_created_time": RFC3339Nano (via TrackElapsed), // "_elapsed_time": float64 seconds (via TrackElapsed), @@ -389,13 +426,6 @@ func (c *ParserComponent) Outputs() map[string]string { // backends (e.g. internal/deepdoc/parser/pdf fans out one worker // per page and assembles the results in page order), so this // component does no goroutine fan-out of its own. -// -// DETERMINISTIC MERGE (plan §8 R8): after the page slice is built, -// it is sorted by PageNumber. This guarantees the same input -// produces byte-identical output across runs and is the contract -// that downstream Chunker / Tokenizer rely on for stable chunk -// IDs (chunks that span pages must reference adjacent PageNumbers -// in input order). func (c *ParserComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[string]any) (map[string]any, error) { // 1. Decode the binary input. binary, err := readParserBinary(ctx, db, inputs) @@ -404,6 +434,7 @@ func (c *ParserComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[st } docID, _ := inputs["doc_id"].(string) filename := parserInputName(inputs, docID) + setups := c.setups // Inject run-level metadata from Globals into inputs so media // dispatch branches (audio/image/video) can resolve tenant_id. @@ -424,29 +455,9 @@ func (c *ParserComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[st // "docx", ...). Used by parser.GetParser, whose switch // arms are keyed off the utility constants. // - // - fileTypeFam — the python-side family name ("markdown", - // "docx", ...). Used by setups[fileType] and - // allowed_output_format[fileType] lookups, which are keyed - // off the python family identifiers in schema.ParserParam. - // - // For most families the two forms coincide; the divergence - // exists for Markdown ("md" vs "markdown") and slides - // ("ppt"/"pptx" vs "slides") and is intentional — the python - // ParserParam collapses the slide family into a single key. fileTypeExt := fileTypeFromInputs(inputs) - fileTypeFam := pythonFamilyName(string(fileTypeExt)) - // 2a. Validate the requested output_format against the - // family-specific allowed_output_format whitelist. We do - // this even when no setups entry exists so a misconfigured - // DSL surfaces as _ERROR instead of a silent fallback. - if _, hasSetup := c.Setups[fileTypeFam]; hasSetup { - if _, verr := resolveOutputFormat(fileTypeFam, c.Setups, c.Param.AllowedOutputFormat); verr != nil { - return nil, verr - } - } - - dispatched, handledVision, visionErr := maybeDispatchPDFVision(ctx, db, fileTypeExt, filename, binary, inputs, c.Setups) + dispatched, handledVision, visionErr := maybeDispatchPDFVision(ctx, db, fileTypeExt, filename, binary, inputs, setups) if visionErr != nil { return nil, visionErr } @@ -455,7 +466,7 @@ func (c *ParserComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[st if !handledVision { // Video dispatch: IMAGE2TEXT vision chat. // Mirrors Python's _video(). - dispatched, handledMedia, visionErr = maybeDispatchVideo(ctx, db, fileTypeExt, filename, binary, inputs, c.Setups) + dispatched, handledMedia, visionErr = maybeDispatchVideo(ctx, db, fileTypeExt, filename, binary, inputs, setups) if visionErr != nil { return nil, visionErr } @@ -464,7 +475,7 @@ func (c *ParserComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[st if !handledVision && !handledMedia { // Image/Picture dispatch: OCR + IMAGE2TEXT vision describe. // Mirrors Python's rag/app/picture.py:chunk() image branch. - dispatched, handledImage, visionErr = maybeDispatchImage(ctx, db, fileTypeExt, filename, binary, inputs, c.Setups) + dispatched, handledImage, visionErr = maybeDispatchImage(ctx, db, fileTypeExt, filename, binary, inputs, setups) if visionErr != nil { return nil, visionErr } @@ -473,13 +484,13 @@ func (c *ParserComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[st if !handledVision && !handledMedia && !handledImage { // Audio dispatch: SPEECH2TEXT transcription. // Mirrors Python's rag/app/audio.py:chunk(). - dispatched, handledAudio, visionErr = maybeDispatchAudio(ctx, db, fileTypeExt, filename, binary, inputs, c.Setups) + dispatched, handledAudio, visionErr = maybeDispatchAudio(ctx, db, fileTypeExt, filename, binary, inputs, setups) if visionErr != nil { return nil, visionErr } } if !handledVision && !handledMedia && !handledImage && !handledAudio { - dispatched = dispatchParse(ctx, fileTypeExt, filename, binary, c.Setups) + dispatched = dispatchParse(ctx, fileTypeExt, filename, binary, setups) // Vision figure enhancement: on the JSON output path, // append vision-model descriptions to embedded image and @@ -488,7 +499,7 @@ func (c *ParserComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[st // Errors (including context cancellation) are intentionally // discarded — enhancement is best-effort, matching Python's // try/except pass pattern. - dispatched, _, _ = maybeDispatchVisionEnhancement(ctx, db, fileTypeExt, dispatched, inputs, c.Setups) + dispatched, _, _ = maybeDispatchVisionEnhancement(ctx, db, fileTypeExt, dispatched, inputs, setups) } // Known/supported families must fail loudly when dispatch or // parsing breaks. Only unknown families keep the raw-text fallback. @@ -497,56 +508,11 @@ func (c *ParserComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[st } reportParserWarnings(ctx, dispatched.Warnings) - // 3. Build the legacy `pages` slice. When the dispatch path - // produced a JSON payload, we re-shape it into the page - // layout the chunker side consumes (`{text, doc_type_kwd, - // page_number?}`); when the dispatch produced a string - // payload we emit a single page carrying the rendered text; - // otherwise we slice the binary on ASCII form-feed and - // treat the input as text pages. - var pages [][]byte - var dispatchedPages []schema.Page - switch { - case dispatched.Err == nil && dispatched.OutputFormat == "json": - dispatchedPages = jsonItemsToPages(dispatched.JSON) - pages = pagesFromDispatch(dispatchedPages) - case dispatched.Err == nil && dispatched.OutputFormat != "": - var text string - switch dispatched.OutputFormat { - case "markdown": - text = dispatched.Markdown - case "html": - text = dispatched.HTML - case "text": - text = dispatched.Text - } - pages = [][]byte{[]byte(text)} - default: - pages = splitIntoPages(binary) - if len(pages) == 0 { - pages = [][]byte{nil} - } - } - - // 3b. (pages-based page selection is handled upstream via the - // component setup: ParserConfig[cpnID][filetype]["pages"] is a - // list of page ranges delivered through override_params and - // consumed by the deepdoc/pdf parser. No inputs-level handling - // here.) - - // 4. Build the page slice sequentially. Per-page parallelism now - // lives in the parser backends (e.g. internal/deepdoc/parser/pdf - // fans out one worker per page and assembles in page order), so - // this component only reshapes the parser output. The DETERMINISTIC - // MERGE (plan §8 R8) keeps pages sorted by PageNumber so the - // downstream chunker / tokenizer get stable chunk IDs. - parsed, err := buildPagesFromBytes(ctx, pages, dispatched.DocType) - if err != nil { + if err := ctx.Err(); err != nil { return nil, fmt.Errorf("parser: %w", err) } - sortPagesByNumber(parsed) lang, _ := getString(inputs, "lang") - out := buildParserOutputs(parsed, dispatched, filename, fileTypeExt, lang) + out := buildParserOutputs(ctx, dispatched, filename, binary, lang) // Forward the storage references so a downstream chunker can // re-acquire the source PDF and crop section images on demand, // instead of carrying the binary across the component boundary. @@ -565,58 +531,42 @@ func (c *ParserComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[st // forwards only this explicit output to the next node, so shared // fields must live in Globals. globals.PublishGlobals(ctx, out) - // Debug log: summarize parser output for pipeline debugging. - if dispatched.OutputFormat == "json" { - common.Debug("parser stage output", - zap.String("component", "Parser"), - zap.String("output_format", "json"), - zap.Int("json_items", len(dispatched.JSON)), - ) - } else if dispatched.OutputFormat != "" { - common.Debug("parser stage output", - zap.String("component", "Parser"), - zap.String("output_format", dispatched.OutputFormat), - ) - } + items, _ := out["json"].([]map[string]any) + logParserOutput(dispatched, items) // Progress (_created_time / _elapsed_time stamping, start/done // callbacks) is owned by the canvas framework (realComponentBody), // not by this component, so we return the work result directly. return out, nil } -func reportParserWarnings(ctx context.Context, warnings []string) { - for _, warning := range warnings { - runtime.ReportProgressMessage(ctx, "Parser", "WARNING: "+warning) +func logParserOutput(dispatched parser.ParseResult, items []map[string]any) { + common.Debug("parser stage output", + zap.String("component", "Parser"), + zap.String("normalized_from", resolveParserNormalizationSource(dispatched)), + zap.Int("json_items", len(items)), + ) +} + +func resolveParserNormalizationSource(dispatched parser.ParseResult) string { + if len(dispatched.JSON) > 0 { + return "json" + } + if dispatched.Markdown != "" { + return "markdown" + } + if dispatched.HTML != "" { + return "html" + } + if dispatched.Text != "" { + return "text" } + return "raw" } -// buildPagesFromBytes reshapes already-prepared page bytes into the -// schema.Page layout the downstream chunker consumes. The per-page -// parse (including any parallelism) now lives in the parser backends -// (internal/parser/parser and internal/deepdoc/parser/pdf); this -// component only wraps the bytes into pages and honors context -// cancellation so an abandoned run does not keep reshaping pages. -// -// The function is format-agnostic: it does not resolve parsers or -// inspect file families — it only carries the raw bytes under the -// "text" key with the given doc_type_kwd (defaults to "text" when -// empty), matching the shape downstream readers expect from the -// raw-text fallback and dispatch paths. -func buildPagesFromBytes(ctx context.Context, pages [][]byte, docType string) ([]schema.Page, error) { - if docType == "" { - docType = "text" - } - out := make([]schema.Page, 0, len(pages)) - for _, raw := range pages { - if err := ctx.Err(); err != nil { - return nil, err - } - out = append(out, schema.Page{ - "text": string(raw), - "doc_type_kwd": docType, - }) +func reportParserWarnings(ctx context.Context, warnings []string) { + for _, warning := range warnings { + runtime.ReportProgressMessage(ctx, "Parser", "WARNING: "+warning) } - return out, nil } // --- input helpers --- @@ -695,57 +645,6 @@ func containsFormFeed(b []byte) bool { return false } -// sortPagesByNumber orders pages by their PageNumber key -// ascending. Pages without a PageNumber key (or with a non-int -// value) sort to the END so the deterministic contract is -// "numbered pages first, then unnumbered" — this matches the -// Python component's loop order (it processes pages in input -// order, not in PageNumber order, but the Go merge is -// intentionally stricter so the test can assert exact byte -// equality across runs). -func sortPagesByNumber(pages []schema.Page) { - sort.SliceStable(pages, func(i, j int) bool { - pi, oki := numericPageNumber(pages[i]) - pj, okj := numericPageNumber(pages[j]) - switch { - case oki && okj: - return pi < pj - case oki: - return true // i is numbered, j is not - case okj: - return false - default: - return false // stable - } - }) -} - -func numericPageNumber(p schema.Page) (int, bool) { - if p == nil { - return 0, false - } - v, ok := p["page_number"] - if !ok { - return 0, false - } - switch n := v.(type) { - case int: - return n, true - case int64: - return int(n), true - case float64: - return int(n), true - } - return 0, false -} - -// toAnyPages is a tiny adapter that hands the page slice to -// the output map as `any`. We use it instead of a direct cast -// so the type stays `[]schema.Page` in the Go source and the -// output map value type is `any` — matching the runtime.Component -// contract. -func toAnyPages(pages []schema.Page) any { return pages } - // init registers Parser under CategoryIngestion per plan §4 // Phase 2.2. The factory is a thin closure that decodes the // DSL param map; the static Metadata is derived from diff --git a/internal/ingestion/component/parser_check_test.go b/internal/ingestion/component/parser_check_test.go index 109a59818b9..7213e50f90c 100644 --- a/internal/ingestion/component/parser_check_test.go +++ b/internal/ingestion/component/parser_check_test.go @@ -24,8 +24,7 @@ import ( ) // TestParserComponent_Check covers the construction-time business -// validation that mirrors the applicable subset of Python -// ParserParam.check() (rag/flow/parser/parser.py:251-321). +// validation for parser methods that require language configuration. // // Go does NOT validate audio/video vlm.llm_id because media_dispatch // resolves tenant default models via resolveTenantModelByType, not @@ -131,7 +130,7 @@ func TestParserComponent_Check(t *testing.T) { for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - c := &ParserComponent{Setups: tc.setups, Param: schema.ParserParam{}.Defaults()} + c := &ParserComponent{setups: tc.setups} err := c.Check() if tc.wantErr != "" { if err == nil { diff --git a/internal/ingestion/component/parser_dispatch.go b/internal/ingestion/component/parser_dispatch.go index 69fb1c85102..24daa448205 100644 --- a/internal/ingestion/component/parser_dispatch.go +++ b/internal/ingestion/component/parser_dispatch.go @@ -14,8 +14,8 @@ // limitations under the License. // -// Parser dispatch validates the requested output format, resolves the -// parser backend, and returns the structured ParseWithResult payload. +// Parser dispatch resolves the parser backend and returns the structured +// ParseWithResult payload for component-boundary normalization. // // `parse_method` is carried through file metadata for downstream // consumers, while the actual backend work stays in @@ -26,37 +26,15 @@ package component import ( "context" "fmt" - "maps" "strings" + "ragflow/internal/common" "ragflow/internal/ingestion/component/schema" "ragflow/internal/parser/parser" "ragflow/internal/utility" -) -// parserDispatchResult is the typed outcome of dispatchParse. The -// component's Invoke translates it into the runtime output map. -// -// OutputFormat is the wire format the parser actually emitted. It -// always matches setups[fileType].output_format on success; on a -// format-mismatch failure (the whitelist rejects it) OutputFormat is -// empty and Err is non-nil. -// -// File is the per-parser file metadata and may be nil. -// -// Payload holds exactly one populated field per the ParseResult -// contract (see internal/parser/parser/parse_result.go). -type parserDispatchResult struct { - OutputFormat string - DocType string // doc_type_kwd for media dispatch ("image", "video", "audio") - File map[string]any - JSON []map[string]any - Markdown string - Text string - HTML string - Warnings []string - Err error -} + "go.uber.org/zap" +) type parserSetupConfigurer interface { ConfigureFromSetup(setup map[string]any) @@ -82,90 +60,6 @@ func configureParserFromSetups(p any, fileType utility.FileType, setups map[stri cfg.ConfigureFromSetup(map[string]any(setup)) } -// resolveOutputFormat picks the wire format for this run. The -// Python side asks the setup, then checks the value is in -// allowed_output_format[fileType]. We mirror that exact sequence: -// -// 1. setups[fileType].output_format (or "" when absent), -// 2. if absent and the family has an allowed_output_format entry, -// use the Python per-family default (mirrors ParserParam.__init__ -// setups, e.g. "image" → "json", "pdf" → "json", "spreadsheet" → -// "html"), falling back to allowed[0] only when no explicit default -// is known, -// 3. if absent and the family has no allowed_output_format entry, -// return "" (the component falls back to text-page mode -// without validating). -// -// The whitelist check returns "" + Err when the requested format is -// not in the allowed set; this is the validation Python raises -// via check_empty / check_valid_value, surfaced as an error so the -// component short-circuits with _ERROR rather than emitting a -// payload the downstream chunker cannot consume. -// -// Strict mode: explicit image:text is rejected by the whitelist. -func resolveOutputFormat(family string, setups map[string]schema.ParserSetup, allowed map[string][]string) (string, error) { - setup, ok := setups[family] - if !ok { - // Family not configured — text-page mode; no validation. - return "", nil - } - format, _ := setup["output_format"].(string) - allowedList, ok := allowed[family] - if !ok || len(allowedList) == 0 { - // No whitelist entry — accept what the setup asked for, or - // fall back to "text" for families without a whitelist. - if format == "" { - format = "text" - } - return format, nil - } - if format == "" { - // No explicit format: use the Python per-family default declared - // in ParserParam.__init__ / defaultSetups(). This is not always - // allowed[0] (e.g. spreadsheet default is "html" but allowed[0] - // is "json"; markdown default is "json" but allowed[0] is "text"). - if def, ok := defaultOutputFormatForFamily(family); ok { - return def, nil - } - return allowedList[0], nil - } - for _, candidate := range allowedList { - if strings.EqualFold(candidate, format) { - return format, nil - } - } - return "", fmt.Errorf( - "parser: output_format %q for %q is not in allowed_output_format %v", - format, family, allowedList, - ) -} - -// defaultOutputFormatForFamily returns the per-family default -// output_format used when setups[family] exists but output_format is -// empty. For most families it is the value in defaultSetups() -// (which mirrors rag/flow/parser/parser.py ParserParam.setups). -// Two families diverge intentionally and are overridden here: -// - email: defaultSetups is "json" (Python), but dispatch defaults -// to "text" to match frontend InitialOutputFormatMap, EmailParser -// text fallback, and ingestion_pipeline_email.json. -// - audio: defaultSetups is "text" (Python), but dispatch defaults -// to "json" to match media_dispatch json fallback and Python -// whitelist [json] (audio:text would be rejected if validated). -func defaultOutputFormatForFamily(family string) (string, bool) { - if family == "email" { - return "text", true - } - if family == "audio" { - return "json", true - } - if s, ok := defaultSetups()[family]; ok { - if v, ok := s["output_format"].(string); ok && v != "" { - return v, true - } - } - return "", false -} - // dispatchParse resolves the parser for the given fileType and invokes // its structured ParseWithResult contract. // @@ -182,12 +76,12 @@ func defaultOutputFormatForFamily(family string) (string, bool) { // re-reading setups. lib_type is no longer threaded through: the // Python dispatcher picks a single backend per family and the Go // constructors mirror that. -func dispatchParse(ctx context.Context, fileType utility.FileType, filename string, data []byte, setups map[string]schema.ParserSetup) parserDispatchResult { +func dispatchParse(ctx context.Context, fileType utility.FileType, filename string, data []byte, setups map[string]schema.ParserSetup) parser.ParseResult { if fileType == utility.FileTypeOTHER { // Unknown / unset family. The component treats the bytes // as text pages; splitIntoPages handles it. We return no // result here so the caller routes to that path. - return parserDispatchResult{} + return parser.ParseResult{} } var parseMethod string @@ -199,13 +93,13 @@ func dispatchParse(ctx context.Context, fileType utility.FileType, filename stri p, err := parser.GetParser(fileType) if err != nil { - return parserDispatchResult{Err: fmt.Errorf("parser: resolve %q: %w", fileType, err)} + return parser.ParseResult{Err: fmt.Errorf("parser: resolve %q: %w", fileType, err)} } configureParserFromSetups(p, fileType, setups) res := p.ParseWithResult(ctx, filename, data) if res.Err != nil { - return parserDispatchResult{Err: fmt.Errorf("parser: %q: %w", fileType, res.Err)} + return parser.ParseResult{Err: fmt.Errorf("parser: %q: %w", fileType, res.Err)} } // Carry the configured parse_method on the file metadata so // downstream consumers can read which provider ran. @@ -215,15 +109,7 @@ func dispatchParse(ctx context.Context, fileType utility.FileType, filename stri } res.File["parse_method"] = parseMethod } - return parserDispatchResult{ - OutputFormat: res.OutputFormat, - File: res.File, - JSON: res.JSON, - Markdown: res.Markdown, - Text: res.Text, - HTML: res.HTML, - Warnings: res.Warnings, - } + return res } // fileTypeFromInputs derives the parser-library extension form @@ -238,9 +124,9 @@ func dispatchParse(ctx context.Context, fileType utility.FileType, filename stri // or the python family name ("markdown"); both are normalized // to the extension form via the pythonFamilyName / familyToExt // lookup tables below. -// 2. inputs["file"].name — fall back to the filename so a caller -// that only supplies the path is still routed correctly. -// 3. inputs["name"] — last-resort filename. +// 2. inputs["name"] — the resolved source filename. +// 3. inputs["file"].name — fallback for callers that only supply a +// file descriptor. // 4. utility.FileTypeOTHER — text-page mode. // // The function never errors; unknown / absent filenames degrade to @@ -270,14 +156,14 @@ func fileTypeFromInputs(inputs map[string]any) utility.FileType { return ft } } + if name, ok := inputs["name"].(string); ok && name != "" { + return utility.GetFileType(name) + } if m, ok := inputs["file"].(map[string]any); ok { if name, ok := m["name"].(string); ok && name != "" { return utility.GetFileType(name) } } - if name, ok := inputs["name"].(string); ok && name != "" { - return utility.GetFileType(name) - } return utility.FileTypeOTHER } @@ -321,7 +207,7 @@ func familyToExt(family string) utility.FileType { } // pythonFamilyName normalises a free-form file-type hint to the -// python family identifier used by schema.ParserParam.Setups. +// Python family identifier used by ParserComponent setups. // Returns "" when the hint is unknown. func pythonFamilyName(raw string) string { switch raw { @@ -374,101 +260,79 @@ func ParserFileFamily(ext string) string { return pythonFamilyName(ext) } -// jsonItemsToPages reshapes a parsed JSON payload into the -// schema.Page layout the chunker side consumes. Each JSON item -// becomes one page carrying `text`, `doc_type_kwd`, and any -// ck_type / image / positions fields the parser attached. The page -// number is assigned sequentially so the deterministic-merge -// contract in plan §8 R8 holds. -func jsonItemsToPages(items []map[string]any) []schema.Page { - out := make([]schema.Page, 0, len(items)) - for i, it := range items { - page := schema.Page{} - maps.Copy(page, it) - // page_number anchors the deterministic-merge sort; the - // parser-supplied number (if any) takes precedence so - // PDF / DOCX outputs that already carry `page_number` - // survive the round-trip. - if _, ok := page["page_number"]; !ok { - page["page_number"] = i - } - if _, ok := page["doc_type_kwd"]; !ok { - page["doc_type_kwd"] = "text" - } - out = append(out, page) - } - return out -} - -// pagesFromDispatch extracts the per-page bytes from a parsed -// schema.Page slice so the page builder can reshape them into the -// schema.Page layout the chunker consumes. Pages without a `text` -// field emit an empty buffer (treated as a zero-length page). -func pagesFromDispatch(pages []schema.Page) [][]byte { - out := make([][]byte, 0, len(pages)) - for _, p := range pages { - var buf []byte - if s, ok := p["text"].(string); ok { - buf = []byte(s) - } - out = append(out, buf) - } - return out -} - // buildParserOutputs assembles the runtime output map from the -// merged pages slice AND the dispatch result (when the dispatch -// succeeded). The output shape: +// dispatch result (when the dispatch succeeded) or raw binary fallback. +// The output shape: // -// - pages []schema.Page — sorted by PageNumber // - name string — from the upstream file/document name // (or doc_id when no filename is available) -// - output_format string — the dispatch's OutputFormat, -// or "text" for the raw-text -// fallback -// - json | Markdown | text | html — the dispatched payload on -// the matching family key (only -// populated on a structured -// dispatch) +// - output_format string — always "json" +// - json []map[string]any — normalized parser items // - file map[string]any — the parser-enriched file // metadata, when present -// -// This mirrors the Python Parser component's `set_output()` calls -// at rag/flow/parser/parser.py:_invoke — the downstream chunker -// / tokenizer / extractor components read the matching family -// key, with "pages" as the universal fallback shape. -func buildParserOutputs(parsed []schema.Page, dispatched parserDispatchResult, name string, fileType utility.FileType, lang string) map[string]any { +func buildParserOutputs(ctx context.Context, dispatched parser.ParseResult, name string, rawBinary []byte, lang string) map[string]any { out := map[string]any{ - "pages": toAnyPages(parsed), - "name": name, + "name": name, } if lang != "" { out["lang"] = lang } if dispatched.Err == nil && dispatched.OutputFormat != "" { - out["output_format"] = dispatched.OutputFormat - switch dispatched.OutputFormat { - case "json": - out["json"] = dispatched.JSON - case "markdown": - out["markdown"] = dispatched.Markdown - case "html": - out["html"] = dispatched.HTML - case "text": - out["text"] = dispatched.Text - } + out["output_format"] = "json" + out["json"] = normalizeParserJSON(ctx, name, dispatched) if dispatched.File != nil { out["file"] = dispatched.File } return out } - // Raw-text fallback path: emit output_format = "text" so a - // chunker branching on the format key still sees a sane value. - out["output_format"] = "text" - _ = fileType // reserved for a future "raw_text per-family" extension + // Raw-text fallback path: emit one JSON item per page. + rawPages := splitIntoPages(rawBinary) + if len(rawPages) == 0 { + rawPages = [][]byte{nil} + } + fallbackItems := make([]map[string]any, 0, len(rawPages)) + for _, pageBytes := range rawPages { + txt := string(pageBytes) + fallbackItems = append(fallbackItems, parser.NewTextJSONItem(txt)) + } + out["output_format"] = "json" + out["json"] = fallbackItems return out } +func normalizeParserJSON(ctx context.Context, filename string, dispatched parser.ParseResult) []map[string]any { + if len(dispatched.JSON) > 0 { + return dispatched.JSON + } + if dispatched.Markdown != "" { + return parseMarkdownToJSONItems(ctx, filename, dispatched.Markdown) + } + if dispatched.HTML != "" { + res := parser.NewHTMLParser().ParseWithResult(ctx, filename, []byte(dispatched.HTML)) + if res.Err == nil && len(res.JSON) > 0 { + return res.JSON + } + if res.Err != nil { + warnParserNormalizationFallback(filename, "html", res.Err) + } else { + warnParserNormalizationFallback(filename, "html", fmt.Errorf("parser returned no JSON items")) + } + return []map[string]any{parser.NewTextJSONItem(dispatched.HTML)} + } + if dispatched.Text != "" { + return []map[string]any{parser.NewTextJSONItem(dispatched.Text)} + } + return []map[string]any{} +} + +func warnParserNormalizationFallback(filename, source string, err error) { + common.Warn("parser normalization fell back to text", + zap.String("filename", filename), + zap.String("normalized_from", source), + zap.Error(err), + ) +} + func parserInputName(inputs map[string]any, docID string) string { if inputs != nil { if name, ok := inputs["name"].(string); ok && name != "" { diff --git a/internal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.go b/internal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.go index 043a8a88c6f..d6bf465d11c 100644 --- a/internal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.go +++ b/internal/ingestion/component/parser_dispatch_pdf_vision_cgo_test.go @@ -11,7 +11,6 @@ import ( "testing" modelModule "ragflow/internal/entity/models" - "ragflow/internal/ingestion/component/schema" "gorm.io/gorm" ) @@ -61,11 +60,10 @@ func TestDispatch_PDFVisionJSON_RealPDFFixture(t *testing.T) { t.Fatalf("ReadFile(%s): %v", path, err) } - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "CustomVLM" setups["pdf"]["output_format"] = "json" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": data, diff --git a/internal/ingestion/component/parser_dispatch_test.go b/internal/ingestion/component/parser_dispatch_test.go index 16375ae71b1..ef20c6a6c4e 100644 --- a/internal/ingestion/component/parser_dispatch_test.go +++ b/internal/ingestion/component/parser_dispatch_test.go @@ -18,10 +18,9 @@ // // - FileTypeOTHER + missing setups → text-page mode. // - FileTypeMarkdown → JSON payload family on the matching output -// key, with the pages slice preserved. -// - FileTypePDF + setups["pdf"].output_format set to a value not -// in allowed_output_format["pdf"] → component errors with the -// format-mismatch message (matches the Python check() behavior). +// key. +// - Historical output_format values, including PDF Markdown, are accepted +// and normalized to the single JSON payload. package component @@ -33,6 +32,7 @@ import ( "encoding/json" "fmt" "io" + "net" "net/http" "net/http/httptest" "os" @@ -47,9 +47,11 @@ import ( doctype "ragflow/internal/deepdoc/parser/type" "ragflow/internal/entity" "ragflow/internal/entity/models" - "ragflow/internal/ingestion/component/schema" + "ragflow/internal/parser/parser" "ragflow/internal/utility" + "go.uber.org/zap" + "go.uber.org/zap/zaptest/observer" "gorm.io/gorm" ) @@ -75,14 +77,178 @@ func (c *captureSetupConfigurer) ConfigureFromSetup(setup map[string]any) { c.setup = setup } -// TestDispatch_OutputFormatValidation_Allowed is the happy-path -// pin: a Markdown file with output_format=json passes the -// allowed_output_format check and runs the structured dispatch. -func TestDispatch_OutputFormatValidation_Allowed(t *testing.T) { - param := schema.ParserParam{}.Defaults() +func requireJSONText(t *testing.T, out map[string]any, want string) { + t.Helper() + if got := out["output_format"]; got != "json" { + t.Fatalf("output_format = %v, want json", got) + } + items, ok := out["json"].([]map[string]any) + if !ok || len(items) == 0 { + t.Fatalf("json = %T/%v, want non-empty structured items", out["json"], out["json"]) + } + for _, item := range items { + if text, _ := item["text"].(string); strings.Contains(text, want) { + return + } + } + t.Fatalf("json payload does not contain %q: %#v", want, items) +} + +func TestBuildParserOutputsNormalizesTextFormatsToJSON(t *testing.T) { + tests := []struct { + name string + dispatched parser.ParseResult + wantText string + }{ + { + name: "markdown", + dispatched: parser.ParseResult{ + OutputFormat: "markdown", + Markdown: "# Title\n\nBody", + }, + wantText: "Title", + }, + { + name: "html", + dispatched: parser.ParseResult{ + OutputFormat: "html", + HTML: "

Title

Body

", + }, + wantText: "Title", + }, + { + name: "text", + dispatched: parser.ParseResult{ + OutputFormat: "text", + Text: "plain body", + }, + wantText: "plain body", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + out := buildParserOutputs(t.Context(), tt.dispatched, "sample."+tt.name, nil, "") + + requireJSONText(t, out, tt.wantText) + if tt.name == "markdown" { + items, ok := out["json"].([]map[string]any) + if !ok { + t.Fatalf("json = %T, want []map[string]any", out["json"]) + } + if len(items) != 2 { + t.Fatalf("markdown json item count = %d, want 2: %#v", len(items), items) + } + if got := items[0]["ck_type"]; got != "heading" { + t.Errorf("markdown item[0].ck_type = %v, want heading", got) + } + if got := items[0]["text"]; got != "Title" { + t.Errorf("markdown item[0].text = %v, want Title", got) + } + if got := items[1]["text"]; got != "Body" { + t.Errorf("markdown item[1].text = %v, want Body", got) + } + } + for _, key := range []string{"markdown", "html", "text"} { + if _, ok := out[key]; ok { + t.Errorf("output contains obsolete %q payload: %#v", key, out[key]) + } + } + }) + } +} + +func TestBuildParserOutputsFallsBackWhenJSONIsEmpty(t *testing.T) { + out := buildParserOutputs(t.Context(), parser.ParseResult{ + OutputFormat: "json", + JSON: []map[string]any{}, + Markdown: "# Recovered title", + }, "sample.md", nil, "") + + requireJSONText(t, out, "Recovered title") +} + +func TestParseMarkdownToJSONItemsDoesNotResolveRemoteImages(t *testing.T) { + originalResolver := net.DefaultResolver + dnsLookup := make(chan struct{}, 1) + net.DefaultResolver = &net.Resolver{ + PreferGo: true, + StrictErrors: true, + Dial: func(context.Context, string, string) (net.Conn, error) { + select { + case dnsLookup <- struct{}{}: + default: + } + return nil, fmt.Errorf("unexpected DNS lookup") + }, + } + t.Cleanup(func() { net.DefaultResolver = originalResolver }) + + items := parseMarkdownToJSONItems(t.Context(), "ocr.md", "![remote](https://images.example.invalid/figure.png)") + if len(items) != 1 { + t.Fatalf("items = %#v, want one Markdown image block", items) + } + select { + case <-dnsLookup: + t.Fatal("Markdown-to-JSON normalization performed a remote image DNS lookup") + default: + } +} + +func TestLogParserOutputReportsNormalizationSource(t *testing.T) { + core, logs := observer.New(zap.DebugLevel) + originalLogger := common.Logger + common.Logger = zap.New(core) + t.Cleanup(func() { common.Logger = originalLogger }) + + logParserOutput(parser.ParseResult{ + OutputFormat: "markdown", + Markdown: "# Title\n\nBody", + }, []map[string]any{{"text": "Title"}, {"text": "Body"}}) + + entries := logs.FilterMessage("parser stage output").All() + if len(entries) != 1 { + t.Fatalf("parser output log count = %d, want 1", len(entries)) + } + fields := entries[0].ContextMap() + if _, ok := fields["output_format"]; ok { + t.Errorf("output_format must be omitted because it is always json: %v", fields) + } + if got := fields["normalized_from"]; got != "markdown" { + t.Errorf("normalized_from = %v, want markdown", got) + } + if got := fields["json_items"]; got != int64(2) { + t.Errorf("json_items = %v, want 2", got) + } +} + +func TestWarnParserNormalizationFallbackReportsCause(t *testing.T) { + core, logs := observer.New(zap.WarnLevel) + originalLogger := common.Logger + common.Logger = zap.New(core) + t.Cleanup(func() { common.Logger = originalLogger }) + + warnParserNormalizationFallback("broken.md", "markdown", fmt.Errorf("parse failed")) + + entries := logs.FilterMessage("parser normalization fell back to text").All() + if len(entries) != 1 { + t.Fatalf("normalization fallback log count = %d, want 1", len(entries)) + } + fields := entries[0].ContextMap() + if got := fields["filename"]; got != "broken.md" { + t.Errorf("filename = %v, want broken.md", got) + } + if got := fields["normalized_from"]; got != "markdown" { + t.Errorf("normalized_from = %v, want markdown", got) + } + if got := fields["error"]; got != "parse failed" { + t.Errorf("error = %v, want parse failed", got) + } +} + +func TestDispatch_JSONOutput(t *testing.T) { setups := defaultSetups() - // Defaults already include Markdown → {text, json}. - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("# Title\n\nbody\n"), @@ -102,67 +268,42 @@ func TestDispatch_OutputFormatValidation_Allowed(t *testing.T) { if len(jsonItems) == 0 { t.Errorf("json payload empty; want at least 1 item") } - // Pages must still exist for chunker-side consumers. - pages, ok := out["pages"].([]schema.Page) - if !ok || len(pages) == 0 { - t.Errorf("pages slice missing or empty: %T", out["pages"]) - } - if ok && len(pages) > 0 { - if got, _ := pages[0]["text"].(string); !strings.Contains(got, "Title") { - t.Errorf("pages[0].text = %q, want content containing Title", got) - } - } // File metadata is carried through dispatch. if fm, ok := out["file"].(map[string]any); !ok || fm["name"] != "doc.md" { t.Errorf("file metadata missing or wrong: %+v", out["file"]) } } -// TestDispatch_OutputFormatValidation_Rejection pins the -// whitelist enforcement: a request for output_format=html on the -// Markdown family is rejected because Markdown's allowed list is -// {text, json}. The component must surface this as a hard error -// before any fallback so a misconfigured template cannot silently -// degrade. -func TestDispatch_OutputFormatValidation_Rejection(t *testing.T) { - param := schema.ParserParam{}.Defaults() +func TestDispatchNormalizesConfiguredOutputFormatToJSON(t *testing.T) { setups := defaultSetups() - // Override the Markdown setup to ask for an unsupported format. - // The key is "markdown" (the python-side family identifier), - // NOT "md" — utility.FileTypeMarkdown happens to be the string - // "md" but the setup key is the family name. resolveOutputFormat - // looks up setups[string(fileType)], so the fileType passed in - // here must match the setup key. - setups["markdown"] = schema.ParserSetup{"output_format": "html"} - // inputs["file_type"] must also be "markdown" so fileTypeFromInputs - // returns a FileType whose string form matches the setup key. - c := &ParserComponent{Param: param, Setups: setups} + setups["email"]["output_format"] = "text" + c := &ParserComponent{setups: setups} - _, err := c.Invoke(t.Context(), nil, map[string]any{ - "binary": []byte("# Title\n"), - "file_type": "md", + out, err := c.Invoke(t.Context(), nil, map[string]any{ + "binary": []byte("From: sender@example.com\r\nTo: receiver@example.com\r\nSubject: Hello\r\n\r\nBody\r\n"), + "name": "mail.eml", + "file_type": "eml", }) - if err == nil { - t.Fatal("Invoke: want error for unsupported output_format, got nil") + if err != nil { + t.Fatalf("Invoke: %v", err) } - if !strings.Contains(err.Error(), "output_format") { - t.Errorf("error %q must mention output_format", err.Error()) + if got := out["output_format"]; got != "json" { + t.Fatalf("output_format = %v, want json", got) } - if !strings.Contains(err.Error(), "markdown") && !strings.Contains(err.Error(), "md") { - t.Errorf("error %q must mention the family", err.Error()) + if items, ok := out["json"].([]map[string]any); !ok || len(items) == 0 { + t.Fatalf("json = %T/%v, want non-empty structured items", out["json"], out["json"]) } } // TestDispatch_TextPageMode_NoFileType pins the no-dispatch // path. When the upstream inputs supply neither file_type nor // file.name, the component degrades to text-page mode and -// emits output_format=text. This is the documented behavior for +// emits structured JSON items. This is the documented behavior for // canvas-bound invocations that wire the binary directly without // a family hint. func TestDispatch_TextPageMode_NoFileType(t *testing.T) { - param := schema.ParserParam{}.Defaults() setups := defaultSetups() - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("plain content\n"), @@ -171,12 +312,15 @@ func TestDispatch_TextPageMode_NoFileType(t *testing.T) { if err != nil { t.Fatalf("Invoke: %v", err) } - if got, want := out["output_format"], "text"; got != want { - t.Errorf("output_format = %v, want %v (text-page mode)", got, want) + if got, want := out["output_format"], "json"; got != want { + t.Errorf("output_format = %v, want %v (raw-text mode)", got, want) } - pages, ok := out["pages"].([]schema.Page) - if !ok || len(pages) == 0 { - t.Fatalf("pages slice missing or empty: %T", out["pages"]) + jsonItems, ok := out["json"].([]map[string]any) + if !ok || len(jsonItems) == 0 { + t.Fatalf("json items missing or empty: %T", out["json"]) + } + if _, ok := out["text"]; ok { + t.Fatalf("output contains obsolete text payload: %#v", out["text"]) } } @@ -185,9 +329,8 @@ func TestDispatch_TextPageMode_NoFileType(t *testing.T) { // resolution/execution failures must surface as errors instead of // silently degrading to text-page mode. func TestDispatch_SupportedFamilyFailure_HardErrors(t *testing.T) { - param := schema.ParserParam{}.Defaults() setups := defaultSetups() - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} _, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("PDF payload as bytes (not a real PDF — stub test)\n"), @@ -205,8 +348,8 @@ func TestDispatch_SupportedFamilyFailure_HardErrors(t *testing.T) { // rules documented on parser_dispatch.go:fileTypeFromInputs: // // 1. inputs["file_type"] (explicit family hint) -// 2. inputs["file"].name (filename in the file descriptor) -// 3. inputs["name"] (last-resort filename) +// 2. inputs["name"] (the resolved source filename) +// 3. inputs["file"].name (filename in the file descriptor) // 4. FileTypeOTHER (text-page mode) func TestFileTypeFromInputs_ResolutionOrder(t *testing.T) { cases := []struct { @@ -222,6 +365,7 @@ func TestFileTypeFromInputs_ResolutionOrder(t *testing.T) { {"explicit slides (family name)", map[string]any{"file_type": "slides"}, "pptx"}, {"explicit spreadsheet (family name)", map[string]any{"file_type": "spreadsheet"}, "xlsx"}, {"explicit markdown (family form)", map[string]any{"file_type": "markdown"}, "md"}, + {"name wins over conflicting file.name", map[string]any{"name": "report.txt", "file": map[string]any{"name": "report.pdf"}}, "txt"}, {"file.name docx", map[string]any{"file": map[string]any{"name": "report.docx"}}, "docx"}, {"name fallback md", map[string]any{"name": "notes.md"}, "md"}, {"unrelated inputs", map[string]any{"binary": []byte("x"), "doc_id": "abc"}, "other"}, @@ -238,132 +382,7 @@ func TestFileTypeFromInputs_ResolutionOrder(t *testing.T) { } } -// TestResolveOutputFormat_DefaultsAndWhitelist pins the two-layer -// behavior of resolveOutputFormat: it returns the setup's -// output_format when present (or the per-family default when absent, -// e.g. markdown→json, spreadsheet→html), and rejects values not in -// the allowed_output_format list. Explicit image:text is rejected. -func TestResolveOutputFormat_DefaultsAndWhitelist(t *testing.T) { - allowed := map[string][]string{ - "pdf": {"json", "markdown"}, - "markdown": {"text", "json"}, - "image": {"json"}, - "spreadsheet": {"json", "markdown", "html"}, - "email": {"text", "json"}, - "audio": {"text", "json"}, - } - cases := []struct { - name string - setups map[string]schema.ParserSetup - family string - want string - wantErr bool - }{ - { - name: "no setup → empty (text-page mode)", - setups: nil, - family: "pdf", - want: "", - }, - { - name: "setup with output_format=json → json", - setups: map[string]schema.ParserSetup{"pdf": {"output_format": "json"}}, - family: "pdf", - want: "json", - }, - { - name: "setup with output_format=markdown → markdown", - setups: map[string]schema.ParserSetup{"pdf": {"output_format": "markdown"}}, - family: "pdf", - want: "markdown", - }, - { - name: "setup without output_format → per-family default (markdown→json)", - setups: map[string]schema.ParserSetup{"markdown": {}}, - family: "markdown", - want: "json", - }, - { - name: "setup without output_format → per-family default (spreadsheet→html)", - setups: map[string]schema.ParserSetup{"spreadsheet": {}}, - family: "spreadsheet", - want: "html", - }, - { - name: "setup without output_format → per-family default (image→json)", - setups: map[string]schema.ParserSetup{"image": {}}, - family: "image", - want: "json", - }, - { - name: "setup without output_format → per-family default (email→text)", - setups: map[string]schema.ParserSetup{"email": {}}, - family: "email", - want: "text", - }, - { - name: "image explicit text (legacy) → strict reject", - setups: map[string]schema.ParserSetup{"image": {"output_format": "text"}}, - family: "image", - wantErr: true, - }, - { - name: "image explicit TEXT uppercase → strict reject", - setups: map[string]schema.ParserSetup{"image": {"output_format": "TEXT"}}, - family: "image", - wantErr: true, - }, - { - name: "pdf asking for html (not allowed) → reject", - setups: map[string]schema.ParserSetup{"pdf": {"output_format": "html"}}, - family: "pdf", - wantErr: true, - }, - { - name: "setup without output_format → per-family default (audio→json)", - setups: map[string]schema.ParserSetup{"audio": {}}, - family: "audio", - want: "json", - }, - { - name: "setup without output_format → per-family default (pdf→json)", - setups: map[string]schema.ParserSetup{"pdf": {}}, - family: "pdf", - want: "json", - }, - { - name: "family with no whitelist → accept setup value", - setups: map[string]schema.ParserSetup{"video": {"output_format": "json"}}, - family: "video", - want: "json", - }, - { - name: "family with no whitelist empty → default text", - setups: map[string]schema.ParserSetup{"video": {}}, - family: "video", - want: "text", - }, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got, err := resolveOutputFormat(tc.family, tc.setups, allowed) - if tc.wantErr { - if err == nil { - t.Fatalf("want error, got nil (value=%q)", got) - } - return - } - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if got != tc.want { - t.Errorf("got %q, want %q", got, tc.want) - } - }) - } -} - -func TestDefaultSetups_DOCX_OutputFormatMarkdown(t *testing.T) { +func TestDefaultSetups_DOCX_OutputFormatJSON(t *testing.T) { setups := defaultSetups() docx, ok := setups["docx"] if !ok { @@ -377,130 +396,7 @@ func TestDefaultSetups_DOCX_OutputFormatMarkdown(t *testing.T) { t.Errorf("docx.output_format = %q, want %q", got, "json") } } - -// TestDefaultOutputFormatForFamily_Sync verifies the dispatch default -// stays in sync with the allowed whitelist and, except for the two -// intentional overrides (email:text, audio:json), with defaultSetups. -func TestDefaultOutputFormatForFamily_Sync(t *testing.T) { - allowed := schema.ParserParam{}.Defaults().AllowedOutputFormat - overrides := map[string]string{"email": "text", "audio": "json"} - for family, def := range map[string]string{ - "pdf": "json", - "spreadsheet": "html", - "doc": "json", - "docx": "json", - "slides": "json", - "image": "json", - "markdown": "json", - "text&code": "json", - "html": "json", - "epub": "json", - "json": "json", - "email": "text", - "audio": "json", - "video": "text", - } { - got, ok := defaultOutputFormatForFamily(family) - if !ok { - t.Errorf("defaultOutputFormatForFamily(%q) missing", family) - continue - } - if got != def { - t.Errorf("defaultOutputFormatForFamily(%q)=%q, want %q", family, got, def) - } - if list, hasWL := allowed[family]; hasWL && len(list) > 0 { - found := false - for _, c := range list { - if strings.EqualFold(c, got) { - found = true - break - } - } - if !found { - t.Errorf("default %q for %q not in allowed %v", got, family, list) - } - } - if ov, isOverride := overrides[family]; isOverride { - if got != ov { - t.Errorf("override %q got %q want %q", family, got, ov) - } - continue - } - if ds, ok := defaultSetups()[family]; ok { - if want, ok := ds["output_format"].(string); ok && want != got { - t.Errorf("family %q dispatch default %q != defaultSetups %q (should be synced or listed as override)", family, got, want) - } - } - } - if _, ok := defaultOutputFormatForFamily("unknown"); ok { - t.Errorf("unknown family should return !ok") - } -} - -// TestResolveOutputFormat_AudioOutputFormats pins the audio-family -// whitelist against the builtin audio template. The template -// (ingestion_pipeline_audio.json) and the Python default audio setup -// (rag/flow/parser/parser.py) both use output_format="text" — an audio -// transcription is inherently plain text. "text" must therefore pass -// the whitelist, "json" must stay accepted, and a format outside the -// whitelist must still be rejected. -func TestResolveOutputFormat_AudioOutputFormats(t *testing.T) { - allowed := schema.ParserParam{}.Defaults().AllowedOutputFormat - audioAllowed, ok := allowed["audio"] - if !ok { - t.Fatal("allowed_output_format: audio key missing") - } - has := func(want string) bool { - for _, v := range audioAllowed { - if strings.EqualFold(v, want) { - return true - } - } - return false - } - if !has("text") { - t.Errorf("allowed_output_format[audio] = %v, want it to include %q (builtin audio template and Python default use it)", audioAllowed, "text") - } - if !has("json") { - t.Errorf("allowed_output_format[audio] = %v, want it to include %q", audioAllowed, "json") - } - - cases := []struct { - name string - format string - wantErr bool - }{ - {name: "text accepted", format: "text"}, - {name: "json accepted", format: "json"}, - {name: "html rejected", format: "html", wantErr: true}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - setups := map[string]schema.ParserSetup{"audio": {"output_format": tc.format}} - got, err := resolveOutputFormat("audio", setups, allowed) - if tc.wantErr { - if err == nil { - t.Fatalf("want error for audio output_format=%q, got %q", tc.format, got) - } - return - } - if err != nil { - t.Fatalf("audio output_format=%q: unexpected error: %v", tc.format, err) - } - if got != tc.format { - t.Errorf("got %q, want %q", got, tc.format) - } - }) - } -} - -// TestDefaultSetups_Audio_OutputFormatText pins the audio default to -// "text", matching the Python default setup -// (rag/flow/parser/parser.py audio block) and the builtin audio -// template. The default feeds both the whitelist gate and the ASR -// dispatch, so it must not drift to a format the audio pipeline does -// not produce. -func TestDefaultSetups_Audio_OutputFormatText(t *testing.T) { +func TestDefaultSetups_Audio_OutputFormatJSON(t *testing.T) { setups := defaultSetups() audio, ok := setups["audio"] if !ok { @@ -510,8 +406,8 @@ func TestDefaultSetups_Audio_OutputFormatText(t *testing.T) { if !ok { t.Fatal("defaultSetups: audio.output_format missing or not a string") } - if got != "text" { - t.Errorf("audio.output_format = %q, want %q", got, "text") + if got != "json" { + t.Errorf("audio.output_format = %q, want %q", got, "json") } } @@ -527,7 +423,7 @@ func TestConfigureParserFromSetups_UsesPythonFamilySetup(t *testing.T) { } } -func TestDispatch_PDFMarkdown_UsesConfiguredOutputFormat(t *testing.T) { +func TestDispatch_PDFLegacyMarkdownConfigurationEmitsJSON(t *testing.T) { useMockDocAnalyzer(t) path := filepath.Join("..", "..", "..", "test", "benchmark", "test_docs", "Doc1.pdf") @@ -536,10 +432,9 @@ func TestDispatch_PDFMarkdown_UsesConfiguredOutputFormat(t *testing.T) { t.Fatalf("ReadFile(%s): %v", path, err) } - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["output_format"] = "markdown" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": data, @@ -549,15 +444,11 @@ func TestDispatch_PDFMarkdown_UsesConfiguredOutputFormat(t *testing.T) { if err != nil { t.Fatalf("Invoke: %v", err) } - if got, want := out["output_format"], "markdown"; got != want { - t.Fatalf("output_format = %v, want %v", got, want) - } - md, ok := out["markdown"].(string) - if !ok || md == "" { - t.Fatalf("markdown payload missing or empty: %T", out["markdown"]) + if got := out["output_format"]; got != "json" { + t.Fatalf("output_format = %v, want json", got) } - if _, ok = out["json"]; ok { - t.Fatalf("json payload must be absent for markdown output: %+v", out["json"]) + if items, ok := out["json"].([]map[string]any); !ok || len(items) == 0 { + t.Fatalf("json = %T/%v, want non-empty structured items", out["json"], out["json"]) } } @@ -568,11 +459,10 @@ func TestDispatch_PDFPlainText_UsesConfiguredBackend(t *testing.T) { t.Fatalf("ReadFile(%s): %v", path, err) } - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "plain_text" setups["pdf"]["output_format"] = "json" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": data, @@ -592,10 +482,9 @@ func TestDispatch_PDFPlainText_UsesConfiguredBackend(t *testing.T) { } func TestDispatch_PDFUnsupportedParseMethod_HardErrors(t *testing.T) { - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "CustomVLM" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} _, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -662,11 +551,10 @@ func TestDispatch_PDFVisionJSON_UsesTenantAwareModel(t *testing.T) { return &models.ChatResponse{Answer: &answer}, nil } - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "CustomVLM" setups["pdf"]["output_format"] = "json" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -728,11 +616,10 @@ func TestDispatch_PDFVisionJSON_PreservesEmptyPages(t *testing.T) { return &models.ChatResponse{Answer: &answer}, nil } - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "CustomVLM" setups["pdf"]["output_format"] = "json" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -778,11 +665,10 @@ func TestDispatch_PDFMinerUMarkdown_UsesConfiguredBackend(t *testing.T) { return &mineruTestDriver{}, "mineru-model", &models.APIConfig{ApiKey: &apiKey, BaseURL: &baseURL}, 0, nil } - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "mineru" setups["pdf"]["output_format"] = "markdown" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -793,12 +679,57 @@ func TestDispatch_PDFMinerUMarkdown_UsesConfiguredBackend(t *testing.T) { if err != nil { t.Fatalf("Invoke: %v", err) } - if got, want := out["output_format"], "markdown"; got != want { + if got := out["output_format"]; got != "json" { + t.Fatalf("output_format = %v, want json", got) + } + requireJSONText(t, out, "Title") +} + +func TestDispatch_PDFMinerUJSON_ParsesMarkdownToStructuredItems(t *testing.T) { + withSSRFBypass(t) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost && r.URL.Path == "/file_parse" { + buf := new(bytes.Buffer) + zw := zip.NewWriter(buf) + f, _ := zw.Create("content_list.json") + _, _ = f.Write([]byte(`[{"type":"text","text":"# Title\n\nBody paragraph\n"}]`)) + _ = zw.Close() + w.Header().Set("Content-Type", "application/zip") + _, _ = w.Write(buf.Bytes()) + return + } + http.NotFound(w, r) + })) + defer server.Close() + + origResolver := resolveTenantModelByType + defer func() { resolveTenantModelByType = origResolver }() + baseURL := server.URL + apiKey := "" + resolveTenantModelByType = func(ctx context.Context, db *gorm.DB, tenantID string, modelType entity.ModelType) (models.ModelDriver, string, *models.APIConfig, int, error) { + return &mineruTestDriver{}, "mineru-model", &models.APIConfig{ApiKey: &apiKey, BaseURL: &baseURL}, 0, nil + } + + setups := defaultSetups() + setups["pdf"]["parse_method"] = "mineru" + setups["pdf"]["output_format"] = "json" + c := &ParserComponent{setups: setups} + + out, err := c.Invoke(t.Context(), nil, map[string]any{ + "binary": []byte("%PDF-1.4"), + "file_type": "pdf", + "name": "sample.pdf", + "tenant_id": "test-tenant", + }) + if err != nil { + t.Fatalf("Invoke: %v", err) + } + if got, want := out["output_format"], "json"; got != want { t.Fatalf("output_format = %v, want %v", got, want) } - md, ok := out["markdown"].(string) - if !ok || !strings.Contains(md, "Title") { - t.Fatalf("markdown payload = %#v, want Title content", out["markdown"]) + items, ok := out["json"].([]map[string]any) + if !ok || len(items) == 0 { + t.Fatalf("json payload = %#v, want non-empty structured items", out["json"]) } } @@ -854,9 +785,7 @@ func TestDispatch_PDFMonkeyOCRv2Markdown_UsesNativeParseEndpoint(t *testing.T) { if err != nil { t.Fatalf("Invoke: %v", err) } - if out["output_format"] != "markdown" || out["markdown"] != "MonkeyOCRv2 title" { - t.Fatalf("output=%#v", out) - } + requireJSONText(t, out, "MonkeyOCRv2 title") } // mineruTestDriver is a minimal ModelDriver mock whose Name() returns "mineru". @@ -940,11 +869,10 @@ func TestDispatch_PDFPaddleOCRMarkdown_UsesTenantModel(t *testing.T) { return &paddleocrTestDriver{}, "PaddleOCR-VL", &models.APIConfig{ApiKey: &apiKey, BaseURL: &baseURL}, 0, nil } - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "PaddleOCR" setups["pdf"]["output_format"] = "markdown" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -955,13 +883,10 @@ func TestDispatch_PDFPaddleOCRMarkdown_UsesTenantModel(t *testing.T) { if err != nil { t.Fatalf("Invoke: %v", err) } - if got, want := out["output_format"], "markdown"; got != want { - t.Fatalf("output_format = %v, want %v", got, want) - } - md, ok := out["markdown"].(string) - if !ok || !strings.Contains(md, "Paddle Title") { - t.Fatalf("markdown payload = %#v, want Paddle Title content", out["markdown"]) + if got := out["output_format"]; got != "json" { + t.Fatalf("output_format = %v, want json", got) } + requireJSONText(t, out, "Paddle Title") } // TestDispatch_PDFPaddleOCRMarkdown_UsesAPIKeyPayload pins the cloud @@ -1008,11 +933,10 @@ func TestDispatch_PDFPaddleOCRMarkdown_UsesAPIKeyPayload(t *testing.T) { return &paddleocrTestDriver{}, "PaddleOCR-VL", &models.APIConfig{ApiKey: &apiKey, BaseURL: &emptyBaseURL}, 0, nil } - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "PaddleOCR" setups["pdf"]["output_format"] = "markdown" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -1023,10 +947,7 @@ func TestDispatch_PDFPaddleOCRMarkdown_UsesAPIKeyPayload(t *testing.T) { if err != nil { t.Fatalf("Invoke: %v", err) } - md, ok := out["markdown"].(string) - if !ok || !strings.Contains(md, "Unwrapped Title") { - t.Fatalf("markdown payload = %#v, want Unwrapped Title content", out["markdown"]) - } + requireJSONText(t, out, "Unwrapped Title") } func TestDispatch_PDFPaddleOCR_NoTenantModel_HardErrors(t *testing.T) { @@ -1037,11 +958,10 @@ func TestDispatch_PDFPaddleOCR_NoTenantModel_HardErrors(t *testing.T) { return nil, "", nil, 0, fmt.Errorf("no active PaddleOCR OCR model") } - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "paddleocr" setups["pdf"]["output_format"] = "markdown" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} _, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -1101,11 +1021,10 @@ func TestDispatch_PDFPaddleOCR_BareModelUUID_UsesExactModel(t *testing.T) { return &paddleocrTestDriver{}, "PaddleOCR-VL", &models.APIConfig{ApiKey: &apiKey, BaseURL: &baseURL}, nil } - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["layout_recognizer"] = modelID setups["pdf"]["output_format"] = "markdown" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -1116,13 +1035,10 @@ func TestDispatch_PDFPaddleOCR_BareModelUUID_UsesExactModel(t *testing.T) { if err != nil { t.Fatalf("Invoke: %v", err) } - if got, want := out["output_format"], "markdown"; got != want { - t.Fatalf("output_format = %v, want %v", got, want) - } - md, ok := out["markdown"].(string) - if !ok || !strings.Contains(md, "Cloud Paddle Title") { - t.Fatalf("markdown payload = %#v, want Cloud Paddle Title content", out["markdown"]) + if got := out["output_format"]; got != "json" { + t.Fatalf("output_format = %v, want json", got) } + requireJSONText(t, out, "Cloud Paddle Title") } // TestDispatch_PDFPaddleOCR_BareModelUUID_InParseMethod pins the routing of a @@ -1169,11 +1085,10 @@ func TestDispatch_PDFPaddleOCR_BareModelUUID_InParseMethod(t *testing.T) { return &paddleocrTestDriver{}, "PaddleOCR-VL", &models.APIConfig{ApiKey: &apiKey, BaseURL: &baseURL}, nil } - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = modelID setups["pdf"]["output_format"] = "markdown" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -1184,13 +1099,10 @@ func TestDispatch_PDFPaddleOCR_BareModelUUID_InParseMethod(t *testing.T) { if err != nil { t.Fatalf("Invoke: %v", err) } - if got, want := out["output_format"], "markdown"; got != want { - t.Fatalf("output_format = %v, want %v", got, want) - } - md, ok := out["markdown"].(string) - if !ok || !strings.Contains(md, "Cloud Paddle Title") { - t.Fatalf("markdown payload = %#v, want Cloud Paddle Title content", out["markdown"]) + if got := out["output_format"]; got != "json" { + t.Fatalf("output_format = %v, want json", got) } + requireJSONText(t, out, "Cloud Paddle Title") } // paddleocrTestDriver is a minimal ModelDriver mock whose Name() returns "paddleocr". @@ -1345,13 +1257,12 @@ func TestDispatch_PDFDoclingMarkdown_UsesConfiguredBackend(t *testing.T) { })) defer server.Close() - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "Docling" setups["pdf"]["output_format"] = "markdown" setups["pdf"]["docling_server_url"] = server.URL setups["pdf"]["docling_api_key"] = "doc-secret" - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -1361,19 +1272,16 @@ func TestDispatch_PDFDoclingMarkdown_UsesConfiguredBackend(t *testing.T) { if err != nil { t.Fatalf("Invoke: %v", err) } - if got, want := out["output_format"], "markdown"; got != want { - t.Fatalf("output_format = %v, want %v", got, want) - } - md, ok := out["markdown"].(string) - if !ok || !strings.Contains(md, "Docling Title") { - t.Fatalf("markdown payload = %#v, want Docling Title content", out["markdown"]) + if got := out["output_format"]; got != "json" { + t.Fatalf("output_format = %v, want json", got) } + requireJSONText(t, out, "Docling Title") if got, want := requestCount, 3; got != want { t.Fatalf("requestCount = %d, want %d", got, want) } } -func TestDispatch_PDFOpenDataLoaderMarkdown_UsesConfiguredBackend(t *testing.T) { +func TestDispatch_PDFOpenDataLoaderLegacyMarkdownEmitsJSON(t *testing.T) { withSSRFBypass(t) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost || r.URL.Path != "/file_parse" { @@ -1385,12 +1293,11 @@ func TestDispatch_PDFOpenDataLoaderMarkdown_UsesConfiguredBackend(t *testing.T) })) defer server.Close() - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "OpenDataLoader" setups["pdf"]["output_format"] = "markdown" setups["pdf"]["opendataloader_apiserver"] = server.URL - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -1400,13 +1307,10 @@ func TestDispatch_PDFOpenDataLoaderMarkdown_UsesConfiguredBackend(t *testing.T) if err != nil { t.Fatalf("Invoke: %v", err) } - md, ok := out["markdown"].(string) - if !ok || !strings.Contains(md, "ODL Title") { - t.Fatalf("markdown payload = %#v, want ODL Title", out["markdown"]) - } + requireJSONText(t, out, "ODL Title") } -func TestDispatch_PDFSoMarkMarkdown_UsesConfiguredBackend(t *testing.T) { +func TestDispatch_PDFSoMarkLegacyMarkdownEmitsJSON(t *testing.T) { withSSRFBypass(t) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { switch r.URL.Path { @@ -1420,12 +1324,11 @@ func TestDispatch_PDFSoMarkMarkdown_UsesConfiguredBackend(t *testing.T) { })) defer server.Close() - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "SoMark" setups["pdf"]["output_format"] = "markdown" setups["pdf"]["somark_base_url"] = server.URL - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -1435,13 +1338,10 @@ func TestDispatch_PDFSoMarkMarkdown_UsesConfiguredBackend(t *testing.T) { if err != nil { t.Fatalf("Invoke: %v", err) } - md, ok := out["markdown"].(string) - if !ok || !strings.Contains(md, "SoMark Title") { - t.Fatalf("markdown payload = %#v, want SoMark Title", out["markdown"]) - } + requireJSONText(t, out, "SoMark Title") } -func TestDispatch_PDFTCADPMarkdown_UsesConfiguredBackend(t *testing.T) { +func TestDispatch_PDFTCADPLegacyMarkdownEmitsJSON(t *testing.T) { withSSRFBypass(t) zipPayload := tcadpZipFixtureForComponent(t) var server *httptest.Server @@ -1457,12 +1357,11 @@ func TestDispatch_PDFTCADPMarkdown_UsesConfiguredBackend(t *testing.T) { })) defer server.Close() - param := schema.ParserParam{}.Defaults() setups := defaultSetups() setups["pdf"]["parse_method"] = "TCADP parser" setups["pdf"]["output_format"] = "markdown" setups["pdf"]["tcadp_apiserver"] = server.URL - c := &ParserComponent{Param: param, Setups: setups} + c := &ParserComponent{setups: setups} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("%PDF-1.4"), @@ -1472,10 +1371,7 @@ func TestDispatch_PDFTCADPMarkdown_UsesConfiguredBackend(t *testing.T) { if err != nil { t.Fatalf("Invoke: %v", err) } - md, ok := out["markdown"].(string) - if !ok || !strings.Contains(md, "Hello TCADP") { - t.Fatalf("markdown payload = %#v, want Hello TCADP", out["markdown"]) - } + requireJSONText(t, out, "Hello TCADP") } func tcadpZipFixtureForComponent(t *testing.T) []byte { @@ -1495,7 +1391,7 @@ func tcadpZipFixtureForComponent(t *testing.T) []byte { // TestPythonFamilyName_FileTypeConstants pins the contract that every // utility.FileType semantic constant resolves to the setups key used by -// defaultSetups / AllowedOutputFormat. Before the fix, FileTypeVISUAL mapped +// defaultSetups. Before the fix, FileTypeVISUAL mapped // to "picture" (mismatching the "image" setups key) and FileTypeAURAL matched // no case at all (returning ""), so output_format validation and // configureParserFromSetups were silently skipped for image/audio files. @@ -1527,16 +1423,11 @@ func TestPythonFamilyName_FileTypeConstants(t *testing.T) { if got != c.want { t.Errorf("pythonFamilyName(%q) = %q, want %q", c.ft, got, c.want) } - // Every mapped family must have a matching setups key and - // allowed_output_format entry, otherwise output_format validation - // is silently skipped. + // Every mapped family must have a matching setup so its parser receives + // the canonical output format and family-specific configuration. if _, ok := defaultSetups()[got]; !ok { t.Errorf("pythonFamilyName(%q) → %q has no defaultSetups entry", c.ft, got) } - allowed := schema.ParserParam{}.Defaults().AllowedOutputFormat - if _, ok := allowed[got]; !ok { - t.Errorf("pythonFamilyName(%q) → %q has no allowed_output_format entry", c.ft, got) - } } } diff --git a/internal/ingestion/component/parser_test.go b/internal/ingestion/component/parser_test.go index 0d2900cc107..aecbd754e0f 100644 --- a/internal/ingestion/component/parser_test.go +++ b/internal/ingestion/component/parser_test.go @@ -18,14 +18,12 @@ package component import ( "encoding/json" - "reflect" "strings" "testing" "github.com/xuri/excelize/v2" "ragflow/internal/agent/runtime" "ragflow/internal/entity" - "ragflow/internal/ingestion/component/schema" ) func TestReportParserWarningsAsProgressMessages(t *testing.T) { @@ -79,13 +77,50 @@ func TestParserComponent_InputsOutputs_NonEmpty(t *testing.T) { if len(out) == 0 { t.Errorf("Outputs() returned empty map") } - // The contract from the file header: at least "binary" in, - // "pages" out. Anything else is informational. - if _, ok := in["binary"]; !ok { - t.Errorf("Inputs() missing key %q", "binary") + // The component catalog must expose every caller-provided input that + // Invoke reads before dispatching. + for _, key := range []string{"binary", "name", "file", "file_type", "lang", "doc_id", "bucket", "path"} { + if _, ok := in[key]; !ok { + t.Errorf("Inputs() missing runtime input key %q", key) + } + } + if _, ok := out["output_format"]; !ok { + t.Errorf("Outputs() missing key %q", "output_format") } - if _, ok := out["pages"]; !ok { - t.Errorf("Outputs() missing key %q", "pages") + if _, ok := out["json"]; !ok { + t.Errorf("Outputs() missing key %q", "json") + } + for _, key := range []string{"name", "lang", "file", "doc_id", "bucket", "path"} { + if _, ok := out[key]; !ok { + t.Errorf("Outputs() missing runtime output key %q", key) + } + } + if _, ok := out["_ERROR"]; ok { + t.Error("Outputs() must not advertise _ERROR; Parser failures return Go errors") + } +} + +func TestNewParserComponentNormalizesOutputFormatToJSON(t *testing.T) { + component, err := NewParserComponent(map[string]any{ + "pdf": map[string]any{"output_format": "markdown"}, + "spreadsheet": map[string]any{"output_format": "html"}, + "email": map[string]any{"output_format": "text"}, + "allowed_output_format": map[string]any{ + "pdf": []any{"json", "markdown"}, + }, + }) + if err != nil { + t.Fatalf("NewParserComponent: %v", err) + } + + parserComponent := component.(*ParserComponent) + for _, family := range []string{"pdf", "spreadsheet", "email"} { + if got := parserComponent.setups[family]["output_format"]; got != "json" { + t.Errorf("%s output_format = %v, want json", family, got) + } + } + if _, ok := parserComponent.setups["allowed_output_format"]; ok { + t.Error("allowed_output_format must not be treated as a parser setup") } } @@ -96,22 +131,25 @@ func TestParserComponent_InputsOutputs_NonEmpty(t *testing.T) { // owned by the canvas framework, not by this component, so they are // not asserted here. func TestParserComponent_Invoke_TextInput(t *testing.T) { - c := &ParserComponent{Param: schema.ParserParam{}.Defaults()} + c := &ParserComponent{} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": "hello world", }) if err != nil { t.Fatalf("Invoke: %v", err) } - pages, ok := out["pages"].([]schema.Page) - if !ok { - t.Fatalf("pages: got %T, want []schema.Page", out["pages"]) + if got, want := out["output_format"], "json"; got != want { + t.Errorf("output_format = %v, want %v", got, want) } - if len(pages) != 1 { - t.Fatalf("pages len = %d, want 1", len(pages)) + jsonItems, ok := out["json"].([]map[string]any) + if !ok || len(jsonItems) != 1 { + t.Fatalf("json: got %T (len %d), want 1 item", out["json"], len(jsonItems)) } - if got := pages[0]["text"]; got != "hello world" { - t.Errorf("pages[0][text] = %q, want %q", got, "hello world") + if got := jsonItems[0]["text"]; got != "hello world" { + t.Errorf("json[0][text] = %q, want %q", got, "hello world") + } + if got := jsonItems[0]["doc_type_kwd"]; got != "text" { + t.Errorf("json[0][doc_type_kwd] = %q, want %q", got, "text") } } @@ -125,7 +163,7 @@ func TestParserComponent_EmptyXLSXDoesNotBecomeRawText(t *testing.T) { t.Fatalf("Close: %v", err) } - c := &ParserComponent{Param: schema.ParserParam{}.Defaults(), Setups: defaultSetups()} + c := &ParserComponent{setups: defaultSetups()} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": data.Bytes(), "file_type": "xlsx", @@ -141,55 +179,45 @@ func TestParserComponent_EmptyXLSXDoesNotBecomeRawText(t *testing.T) { if len(items) != 0 { t.Fatalf("empty XLSX JSON = %v, want no raw-binary items", items) } - pages, ok := out["pages"].([]schema.Page) - if !ok { - t.Fatalf("pages = %T, want []schema.Page", out["pages"]) - } - if len(pages) != 0 { - t.Fatalf("empty XLSX pages = %v, want none", pages) - } } // TestParserComponent_Invoke_PageRangeFilter asserts that // form-feed boundaries are honored: "A\fB\fC" yields three -// pages, in input order, with text intact. +// items, in input order, with text intact. func TestParserComponent_Invoke_PageRangeFilter(t *testing.T) { - c := &ParserComponent{Param: schema.ParserParam{}.Defaults()} + c := &ParserComponent{} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": "pageA\fpageB\fpageC", }) if err != nil { t.Fatalf("Invoke: %v", err) } - pages, ok := out["pages"].([]schema.Page) + jsonItems, ok := out["json"].([]map[string]any) if !ok { - t.Fatalf("pages: got %T, want []schema.Page", out["pages"]) + t.Fatalf("json: got %T, want []map[string]any", out["json"]) } - if len(pages) != 3 { - t.Fatalf("pages len = %d, want 3", len(pages)) + if len(jsonItems) != 3 { + t.Fatalf("json len = %d, want 3", len(jsonItems)) } want := []string{"pageA", "pageB", "pageC"} - for i, p := range pages { - if got := p["text"]; got != want[i] { - t.Errorf("pages[%d][text] = %q, want %q", i, got, want[i]) + for i, it := range jsonItems { + if got := it["text"]; got != want[i] { + t.Errorf("json[%d][text] = %q, want %q", i, got, want[i]) } } } -// TestParserComponent_Invoke_DeterministicMerge is the -// golden-file test for plan §8 R8 (DETERMINISTIC MERGE). +// TestParserComponent_Invoke_DeterministicMerge verifies stable output order. // // We invoke the component 5 times with identical input and // assert byte-for-byte equality of the JSON-encoded output. // The test is expected to pass under `go test -count=10 -race` // — that flag is run separately in the verification block. // -// Text-page mode has no page_number key, so the input order is -// the output order; the deterministic sort keeps that order -// stable across runs, which is the contract the downstream -// chunker relies on for stable chunk IDs. +// Text-page mode preserves input order, which downstream chunkers rely on for +// stable chunk IDs. func TestParserComponent_Invoke_DeterministicMerge(t *testing.T) { - c := &ParserComponent{Param: schema.ParserParam{}.Defaults()} + c := &ParserComponent{} // 8 form-feed-separated pages. input := "p1\fp2\fp3\fp4\fp5\fp6\fp7\fp8" @@ -200,7 +228,7 @@ func TestParserComponent_Invoke_DeterministicMerge(t *testing.T) { if err != nil { t.Fatalf("Invoke (first): %v", err) } - canonical, err := json.Marshal(first["pages"]) + canonical, err := json.Marshal(first["json"]) if err != nil { t.Fatalf("Marshal canonical: %v", err) } @@ -213,7 +241,7 @@ func TestParserComponent_Invoke_DeterministicMerge(t *testing.T) { if err != nil { t.Fatalf("Invoke (run %d): %v", i, err) } - encoded, err := json.Marshal(got["pages"]) + encoded, err := json.Marshal(got["json"]) if err != nil { t.Fatalf("Marshal run %d: %v", i, err) } @@ -224,10 +252,8 @@ func TestParserComponent_Invoke_DeterministicMerge(t *testing.T) { } } -// TestParserComponent_New_Defaults constructs a Parser from a -// nil param map and verifies the static Param is the -// Defaults() value (i.e., NewParserComponent does not mutate -// the schema default). +// TestParserComponent_New_Defaults constructs a Parser from a nil param map +// and verifies every parser family uses the canonical JSON output format. func TestParserComponent_New_Defaults(t *testing.T) { c, err := NewParserComponent(nil) if err != nil { @@ -237,9 +263,10 @@ func TestParserComponent_New_Defaults(t *testing.T) { if !ok { t.Fatalf("NewParserComponent returned %T, want *ParserComponent", c) } - defaults := schema.ParserParam{}.Defaults() - if !reflect.DeepEqual(pc.Param, defaults) { - t.Errorf("Param differs from Defaults:\n got=%+v\nwant=%+v", pc.Param, defaults) + for family, setup := range pc.setups { + if got := setup["output_format"]; got != "json" { + t.Errorf("%s output_format = %v, want json", family, got) + } } } @@ -259,7 +286,7 @@ func TestParserComponent_New_Overrides(t *testing.T) { if !ok { t.Fatalf("NewParserComponent returned %T", c) } - setup, ok := pc.Setups["text&code"] + setup, ok := pc.setups["text&code"] if !ok { t.Fatalf("Setups[text&code] missing after override") } @@ -267,15 +294,38 @@ func TestParserComponent_New_Overrides(t *testing.T) { t.Errorf("Setups[text&code][chunk_token_size] = %v, want 256", setup["chunk_token_size"]) } // Defaults must still be present for other file types. - if _, ok := pc.Setups["pdf"]; !ok { + if _, ok := pc.setups["pdf"]; !ok { t.Errorf("Setups[pdf] missing; override should not erase defaults") } } +func TestParserComponent_NewOwnsNestedSetup(t *testing.T) { + vlm := map[string]any{"llm_id": "original"} + c, err := NewParserComponent(map[string]any{ + "pdf": map[string]any{"vlm": vlm}, + }) + if err != nil { + t.Fatalf("NewParserComponent: %v", err) + } + pc, ok := c.(*ParserComponent) + if !ok { + t.Fatalf("NewParserComponent returned %T, want *ParserComponent", c) + } + + vlm["llm_id"] = "mutated" + gotVLM, ok := pc.setups["pdf"]["vlm"].(map[string]any) + if !ok { + t.Fatalf("pdf.vlm = %T, want map[string]any", pc.setups["pdf"]["vlm"]) + } + if got := gotVLM["llm_id"]; got != "original" { + t.Errorf("pdf.vlm.llm_id = %v after caller mutation, want original", got) + } +} + // TestParserComponent_Invoke_DocIDCarried asserts the optional // doc_id input flows through to the "name" output. func TestParserComponent_Invoke_DocIDCarried(t *testing.T) { - c := &ParserComponent{Param: schema.ParserParam{}.Defaults()} + c := &ParserComponent{} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": "x", "doc_id": "doc-123", @@ -311,17 +361,17 @@ func TestParserComponent_Invoke_ResolvesBinaryFromDocID(t *testing.T) { t.Fatalf("seed doc: %v", err) } - c := &ParserComponent{Param: schema.ParserParam{}.Defaults()} + c := &ParserComponent{} out, err := c.Invoke(ctx, db, map[string]any{"doc_id": "doc-parser"}) if err != nil { t.Fatalf("Invoke: %v", err) } - pages, ok := out["pages"].([]schema.Page) - if !ok || len(pages) != 2 { - t.Fatalf("pages = %T/%v, want 2 schema.Page entries", out["pages"], out["pages"]) + jsonItems, ok := out["json"].([]map[string]any) + if !ok || len(jsonItems) != 2 { + t.Fatalf("json = %T/%v, want 2 items", out["json"], out["json"]) } - if pages[0]["text"] != "alpha" || pages[1]["text"] != "beta" { - t.Fatalf("pages = %+v, want [alpha beta]", pages) + if jsonItems[0]["text"] != "alpha" || jsonItems[1]["text"] != "beta" { + t.Fatalf("json = %+v, want [alpha beta]", jsonItems) } if got, _ := out["name"].(string); got != "doc-parser" { t.Fatalf("name = %q, want %q", got, "doc-parser") @@ -335,7 +385,7 @@ func TestParserComponent_Invoke_ResolvesBinaryFromBucketPath(t *testing.T) { t.Fatalf("seed storage: %v", err) } - c := &ParserComponent{Param: schema.ParserParam{}.Defaults()} + c := &ParserComponent{} out, err := c.Invoke(ctx, nil, map[string]any{ "bucket": "bucket-1", "path": "docs/explicit.txt", @@ -343,12 +393,12 @@ func TestParserComponent_Invoke_ResolvesBinaryFromBucketPath(t *testing.T) { if err != nil { t.Fatalf("Invoke: %v", err) } - pages, ok := out["pages"].([]schema.Page) - if !ok || len(pages) != 1 { - t.Fatalf("pages = %T/%v, want 1 schema.Page entry", out["pages"], out["pages"]) + jsonItems, ok := out["json"].([]map[string]any) + if !ok || len(jsonItems) != 1 { + t.Fatalf("json = %T/%v, want 1 item", out["json"], out["json"]) } - if got := pages[0]["text"]; got != "bucket content" { - t.Fatalf("pages[0][text] = %q, want %q", got, "bucket content") + if got := jsonItems[0]["text"]; got != "bucket content" { + t.Fatalf("json[0][text] = %q, want %q", got, "bucket content") } } @@ -358,7 +408,7 @@ func TestParserComponent_Invoke_ResolvesBinaryFromBucketPath(t *testing.T) { // look like this if a caller mistakenly handed a base64 string // without decoding it). func TestParserComponent_Invoke_RejectsInvalidUTF8(t *testing.T) { - c := &ParserComponent{Param: schema.ParserParam{}.Defaults()} + c := &ParserComponent{} _, err := c.Invoke(t.Context(), nil, map[string]any{ // 0xFF alone is not valid UTF-8 start byte. "binary": string([]byte{0xFF, 0xFE, 0xFD}), @@ -375,49 +425,21 @@ func TestParserComponent_Invoke_RejectsInvalidUTF8(t *testing.T) { // caller's normal form ([]byte) — the alternative to a UTF-8 // string. func TestParserComponent_Invoke_AcceptsBytes(t *testing.T) { - c := &ParserComponent{Param: schema.ParserParam{}.Defaults()} + c := &ParserComponent{} out, err := c.Invoke(t.Context(), nil, map[string]any{ "binary": []byte("alpha\fbeta"), }) if err != nil { t.Fatalf("Invoke: %v", err) } - pages, ok := out["pages"].([]schema.Page) + jsonItems, ok := out["json"].([]map[string]any) if !ok { - t.Fatalf("pages: got %T", out["pages"]) + t.Fatalf("json: got %T", out["json"]) } - if len(pages) != 2 { - t.Fatalf("pages len = %d, want 2", len(pages)) + if len(jsonItems) != 2 { + t.Fatalf("json len = %d, want 2", len(jsonItems)) } - if pages[0]["text"] != "alpha" || pages[1]["text"] != "beta" { - t.Errorf("pages = %+v, want [alpha beta]", pages) - } -} - -// TestBuildPagesFromBytes_FormatAgnostic pins the page-builder -// contract: buildPagesFromBytes does not resolve parsers or inspect -// file families. It only wraps already-prepared page bytes into -// schema.Page items. -func TestBuildPagesFromBytes_FormatAgnostic(t *testing.T) { - got, err := buildPagesFromBytes(t.Context(), [][]byte{ - []byte("first page from dispatch"), - []byte("second page from html dispatch
"), - }, "") - if err != nil { - t.Fatalf("buildPagesFromBytes: %v", err) - } - if len(got) != 2 { - t.Fatalf("len(got) = %d, want 2", len(got)) - } - if got[0]["text"] != "first page from dispatch" { - t.Fatalf("got[0][text] = %v, want first page from dispatch", got[0]["text"]) - } - if got[1]["text"] != "second page from html dispatch
" { - t.Fatalf("got[1][text] = %v, want HTML payload preserved verbatim", got[1]["text"]) - } - for i := range got { - if got[i]["doc_type_kwd"] != "text" { - t.Fatalf("got[%d][doc_type_kwd] = %v, want text", i, got[i]["doc_type_kwd"]) - } + if jsonItems[0]["text"] != "alpha" || jsonItems[1]["text"] != "beta" { + t.Errorf("json = %+v, want [alpha beta]", jsonItems) } } diff --git a/internal/ingestion/component/pdf_vision_dispatch.go b/internal/ingestion/component/pdf_vision_dispatch.go index 40265d9451d..b18a5e2d155 100644 --- a/internal/ingestion/component/pdf_vision_dispatch.go +++ b/internal/ingestion/component/pdf_vision_dispatch.go @@ -24,6 +24,7 @@ import ( "ragflow/internal/entity" modelModule "ragflow/internal/entity/models" "ragflow/internal/ingestion/component/schema" + "ragflow/internal/parser/parser" "ragflow/internal/utility" "go.uber.org/zap" @@ -68,13 +69,13 @@ func maybeDispatchPDFVision( binary []byte, inputs map[string]any, setups map[string]schema.ParserSetup, -) (parserDispatchResult, bool, error) { +) (parser.ParseResult, bool, error) { if fileType != utility.FileTypePDF { - return parserDispatchResult{}, false, nil + return parser.ParseResult{}, false, nil } setup, ok := setups["pdf"] if !ok { - return parserDispatchResult{}, false, nil + return parser.ParseResult{}, false, nil } method := getStringOr(setup, "parse_method", "") @@ -113,12 +114,12 @@ func maybeDispatchPDFVision( zap.String("layout_recognizer", layout), zap.String("tenant_id", tenantID)) if tenantID == "" { - return parserDispatchResult{}, true, + return parser.ParseResult{}, true, fmt.Errorf("parser: MinerU requires tenant_id") } res, err := dispatchMinerUPDF(ctx, db, filename, binary, tenantID, setup) if err != nil { - return parserDispatchResult{}, true, err + return parser.ParseResult{}, true, err } return res, true, nil } @@ -150,7 +151,7 @@ func maybeDispatchPDFVision( } if isPaddleOCRMatch || isPaddleOCRByUUID { if tenantID == "" { - return parserDispatchResult{}, true, + return parser.ParseResult{}, true, fmt.Errorf("parser: PaddleOCR requires tenant_id") } // Only a resolved UUID may be passed to the model resolver; a string @@ -162,27 +163,27 @@ func maybeDispatchPDFVision( } res, err := dispatchPaddleOCRPdf(ctx, db, filename, binary, tenantID, setup, dispatchModelID) if err != nil { - return parserDispatchResult{}, true, err + return parser.ParseResult{}, true, err } return res, true, nil } modelID, useVision := resolvePDFVisionModelID(setup) if !useVision { - return parserDispatchResult{}, false, nil + return parser.ParseResult{}, false, nil } if tenantID == "" { - return parserDispatchResult{}, true, fmt.Errorf( + return parser.ParseResult{}, true, fmt.Errorf( `parser: pdf parse_method %q requires tenant_id to resolve VLM model`, modelID) } - res, err := dispatchPDFVision(ctx, db, filename, binary, tenantID, modelID, setup) + res, err := dispatchPDFVision(ctx, db, filename, binary, tenantID, modelID) if err != nil { - return parserDispatchResult{}, true, err + return parser.ParseResult{}, true, err } return res, true, nil } -func dispatchMonkeyOCRv2PDF(ctx context.Context, db *gorm.DB, filename string, binary []byte, tenantID string, setup schema.ParserSetup, modelRef string) (parserDispatchResult, error) { +func dispatchMonkeyOCRv2PDF(ctx context.Context, db *gorm.DB, filename string, binary []byte, tenantID string, setup schema.ParserSetup, modelRef string) (parser.ParseResult, error) { baseURL := strings.TrimRight(getStringOr(setup, "monkeyocrv2_server_url", os.Getenv(common.EnvMonkeyOCRv2ServerURL)), "/") timeout := monkeyOCRv2RequestTimeout(setup, nil) if tenantID != "" { @@ -196,7 +197,7 @@ func dispatchMonkeyOCRv2PDF(ctx context.Context, db *gorm.DB, filename string, b } if err == nil { if !strings.EqualFold(driver.Name(), "monkeyocrv2") { - return parserDispatchResult{}, fmt.Errorf("parser: MonkeyOCRv2 requires a MonkeyOCRv2 OCR model; found %q", driver.Name()) + return parser.ParseResult{}, fmt.Errorf("parser: MonkeyOCRv2 requires a MonkeyOCRv2 OCR model; found %q", driver.Name()) } if apiConfig != nil && apiConfig.BaseURL != nil && strings.TrimSpace(*apiConfig.BaseURL) != "" { baseURL = strings.TrimRight(*apiConfig.BaseURL, "/") @@ -205,21 +206,53 @@ func dispatchMonkeyOCRv2PDF(ctx context.Context, db *gorm.DB, filename string, b } timeout = monkeyOCRv2RequestTimeout(setup, apiConfig) } else if baseURL == "" { - return parserDispatchResult{}, fmt.Errorf("parser: MonkeyOCRv2 model: %w", err) + return parser.ParseResult{}, fmt.Errorf("parser: MonkeyOCRv2 model: %w", err) } } if baseURL == "" { - return parserDispatchResult{}, fmt.Errorf("parser: MonkeyOCRv2 requires monkeyocrv2_server_url or MONKEYOCRV2_SERVER_URL") + return parser.ParseResult{}, fmt.Errorf("parser: MonkeyOCRv2 requires monkeyocrv2_server_url or MONKEYOCRV2_SERVER_URL") } zipBytes, err := monkeyOCRv2ParseRequest(ctx, baseURL+"/parse", filename, binary, timeout) if err != nil { - return parserDispatchResult{}, err + return parser.ParseResult{}, err } sections, err := monkeyOCRv2ExtractSections(zipBytes) if err != nil { - return parserDispatchResult{}, err + return parser.ParseResult{}, err + } + md := strings.Join(sections, "\n\n") + return buildMarkdownOCRDispatchResult(md), nil +} + +func parseMarkdownToJSONItems(ctx context.Context, filename, mdText string) []map[string]any { + mp, err := parser.NewMarkdownParser(parser.GoMarkdown) + if err != nil { + warnParserNormalizationFallback(filename, "markdown", err) + return []map[string]any{parser.NewTextJSONItem(mdText)} + } + // OCR Markdown is an untrusted backend response. Keep normalization + // deterministic and local: embedded data URIs remain available, while + // remote image URLs do not introduce network I/O at the Parser boundary. + mp.FetchRemoteImages = false + res := mp.ParseWithResult(ctx, filename, []byte(mdText)) + if res.Err != nil { + warnParserNormalizationFallback(filename, "markdown", res.Err) + return []map[string]any{parser.NewTextJSONItem(mdText)} + } + if len(res.JSON) == 0 { + warnParserNormalizationFallback(filename, "markdown", fmt.Errorf("parser returned no JSON items")) + return []map[string]any{parser.NewTextJSONItem(mdText)} + } + return res.JSON +} + +func buildMarkdownOCRDispatchResult(md string) parser.ParseResult { + // Keep the backend's Markdown intact here. buildParserOutputs is the + // single normalization boundary for all non-JSON parser responses. + return parser.ParseResult{ + OutputFormat: "markdown", + Markdown: md, } - return parserDispatchResult{OutputFormat: "markdown", Markdown: strings.Join(sections, "\n\n")}, nil } var isMonkeyOCRv2LayoutModelID = defaultIsMonkeyOCRv2LayoutModelID @@ -447,17 +480,17 @@ func getAnyString(object map[string]any, keys ...string) string { func dispatchMinerUPDF( ctx context.Context, db *gorm.DB, - _ string, + filename string, binary []byte, tenantID string, setup schema.ParserSetup, -) (parserDispatchResult, error) { +) (parser.ParseResult, error) { driver, _, apiConfig, _, err := resolveTenantModelByType(ctx, db, tenantID, entity.ModelTypeOCR) if err != nil { - return parserDispatchResult{}, fmt.Errorf("parser: MinerU model: %w", err) + return parser.ParseResult{}, fmt.Errorf("parser: MinerU model: %w", err) } if !isMinerUDriver(driver) { - return parserDispatchResult{}, fmt.Errorf( + return parser.ParseResult{}, fmt.Errorf( "parser: MinerU requires a MinerU OCR model; found %q. Please add a MinerU OCR model to your tenant", driver.Name()) } @@ -478,12 +511,12 @@ func dispatchMinerUPDF( zipBytes, err := mineruStreamParse(apiURL, apiConfig.ApiKey, binary, parseMethod, mineruLang, backend) if err != nil { - return parserDispatchResult{}, fmt.Errorf("parser: MinerU stream: %w", err) + return parser.ParseResult{}, fmt.Errorf("parser: MinerU stream: %w", err) } sections, err := mineruExtractSections(zipBytes) if err != nil { - return parserDispatchResult{}, fmt.Errorf("parser: MinerU extract: %w", err) + return parser.ParseResult{}, fmt.Errorf("parser: MinerU extract: %w", err) } var parts []string @@ -494,17 +527,7 @@ func dispatchMinerUPDF( } md := strings.Join(parts, "\n") - // MinerU always returns rendered markdown text (md), regardless of - // the requested output_format; label the payload as markdown so the - // downstream chunker consumes it instead of a nil JSONResult. - if format := strings.TrimSpace(getStringOr(setup, "output_format", "markdown")); !strings.EqualFold(format, "markdown") { - common.Warn("mineru parser: output_format %q requested but backend only returns markdown; treating result as markdown", - zap.String("output_format", format)) - } - return parserDispatchResult{ - OutputFormat: "markdown", - Markdown: md, - }, nil + return buildMarkdownOCRDispatchResult(md), nil } // resolvePaddleOCRModelForDispatch resolves the OCR model used by the @@ -546,13 +569,13 @@ func dispatchPaddleOCRPdf( tenantID string, setup schema.ParserSetup, modelID string, -) (parserDispatchResult, error) { +) (parser.ParseResult, error) { driver, modelName, apiConfig, err := resolvePaddleOCRModelForDispatch(ctx, db, tenantID, modelID) if err != nil { - return parserDispatchResult{}, fmt.Errorf("parser: PaddleOCR model: %w", err) + return parser.ParseResult{}, fmt.Errorf("parser: PaddleOCR model: %w", err) } if !isPaddleOCRDriver(driver) { - return parserDispatchResult{}, fmt.Errorf( + return parser.ParseResult{}, fmt.Errorf( "parser: PaddleOCR requires a PaddleOCR OCR model; found %q. Please add a PaddleOCR OCR model to your tenant", driver.Name()) } @@ -581,7 +604,7 @@ func dispatchPaddleOCRPdf( baseURL = strings.TrimSpace(common.GetEnv(common.EnvPaddleOCRAPIURL)) } if baseURL == "" { - return parserDispatchResult{}, fmt.Errorf( + return parser.ParseResult{}, fmt.Errorf( "parser: PaddleOCR requires a base url from the tenant PaddleOCR OCR model or PADDLEOCR_BASE_URL") } @@ -611,28 +634,16 @@ func dispatchPaddleOCRPdf( Algorithm: algorithm, }, nil) if err != nil { - return parserDispatchResult{}, fmt.Errorf("parser: PaddleOCR OCRFile: %w", err) + return parser.ParseResult{}, fmt.Errorf("parser: PaddleOCR OCRFile: %w", err) } if resp == nil || resp.Text == nil { - return parserDispatchResult{}, fmt.Errorf("parser: PaddleOCR returned empty text") + return parser.ParseResult{}, fmt.Errorf("parser: PaddleOCR returned empty text") } if strings.TrimSpace(*resp.Text) == "" { - return parserDispatchResult{}, fmt.Errorf("parser: PaddleOCR returned empty text") + return parser.ParseResult{}, fmt.Errorf("parser: PaddleOCR returned empty text") } - // PaddleOCR backends always return rendered markdown text - // (OCRFile.Text), regardless of the requested output_format. The - // payload MUST be labelled markdown so the downstream chunker - // consumes the text; a non-markdown setup value only means this - // backend cannot produce the requested layout format. - if format := strings.TrimSpace(getStringOr(setup, "output_format", "markdown")); !strings.EqualFold(format, "markdown") { - common.Warn("paddleocr parser: output_format %q requested but backend only returns markdown; treating result as markdown", - zap.String("output_format", format)) - } - return parserDispatchResult{ - OutputFormat: "markdown", - Markdown: *resp.Text, - }, nil + return buildMarkdownOCRDispatchResult(*resp.Text), nil } // resolveMinerUBaseURL extracts the resolved base URL from a model driver. @@ -873,28 +884,26 @@ func dispatchPDFVision( binary []byte, tenantID string, modelID string, - setup schema.ParserSetup, -) (parserDispatchResult, error) { +) (parser.ParseResult, error) { renderedPages, err := pdfVisionPageRenderer(binary) if err != nil { - return parserDispatchResult{}, fmt.Errorf("parser: pdf vision render: %w", err) + return parser.ParseResult{}, fmt.Errorf("parser: pdf vision render: %w", err) } driver, resolvedModelName, apiConfig, err := pdfVisionModelResolver(ctx, db, tenantID, modelID) if err != nil { - return parserDispatchResult{}, fmt.Errorf("parser: pdf vision model %q: %w", modelID, err) + return parser.ParseResult{}, fmt.Errorf("parser: pdf vision model %q: %w", modelID, err) } promptTemplate, err := pdfVisionPromptLoader("vision_llm_describe_prompt") if err != nil { - return parserDispatchResult{}, fmt.Errorf("parser: load vision prompt: %w", err) + return parser.ParseResult{}, fmt.Errorf("parser: load vision prompt: %w", err) } items := make([]map[string]any, 0, len(renderedPages)) - markdownParts := make([]string, 0, len(renderedPages)) for _, page := range renderedPages { prompt := renderPDFVisionPrompt(promptTemplate, page.PageNumber) resp, err := pdfVisionChatInvoker(ctx, driver, resolvedModelName, buildPDFVisionMessages(prompt, page.ImageURL), apiConfig) if err != nil { - return parserDispatchResult{}, fmt.Errorf("parser: pdf vision page %d: %w", page.PageNumber, err) + return parser.ParseResult{}, fmt.Errorf("parser: pdf vision page %d: %w", page.PageNumber, err) } text := extractVisionAnswer(resp) positions := [][]any{{page.PageNumber, 0.0, page.WidthPts, 0.0, page.HeightPts}} @@ -905,37 +914,19 @@ func dispatchPDFVision( "_pdf_positions": positions, "positions": positions, }) - if text != "" { - markdownParts = append(markdownParts, text) - } } - outputFormat := "json" - if v, ok := setup["output_format"].(string); ok && strings.TrimSpace(v) != "" { - outputFormat = strings.ToLower(strings.TrimSpace(v)) - } fileMeta := map[string]any{ "name": filename, "page_count": len(renderedPages), "outline": []map[string]any{}, "parse_method": modelID, } - switch outputFormat { - case "json": - return parserDispatchResult{ - OutputFormat: "json", - File: fileMeta, - JSON: items, - }, nil - case "markdown": - return parserDispatchResult{ - OutputFormat: "markdown", - File: fileMeta, - Markdown: strings.TrimSpace(strings.Join(markdownParts, "\n\n")), - }, nil - default: - return parserDispatchResult{}, fmt.Errorf("parser: unsupported PDF output_format %q for vision parse_method %q", outputFormat, modelID) - } + return parser.ParseResult{ + OutputFormat: "json", + File: fileMeta, + JSON: items, + }, nil } func buildPDFVisionMessages(prompt string, imageURL string) []modelModule.Message { diff --git a/internal/ingestion/component/pdf_vision_dispatch_test.go b/internal/ingestion/component/pdf_vision_dispatch_test.go index 78d2cfacd8f..899b3c166b5 100644 --- a/internal/ingestion/component/pdf_vision_dispatch_test.go +++ b/internal/ingestion/component/pdf_vision_dispatch_test.go @@ -106,9 +106,30 @@ func TestDispatchMonkeyOCRv2PDFPostsNativeParseRequest(t *testing.T) { if err != nil { t.Fatal(err) } - if result.OutputFormat != "markdown" || result.Markdown != "hello" { + if result.OutputFormat != "markdown" || result.Markdown != "hello" || result.JSON != nil { t.Fatalf("result=%+v", result) } + + resultMD, err := dispatchMonkeyOCRv2PDF(context.Background(), nil, "sample.pdf", []byte("pdf"), "", schema.ParserSetup{"monkeyocrv2_server_url": server.URL, "output_format": "markdown"}, "") + if err != nil { + t.Fatal(err) + } + if resultMD.OutputFormat != "markdown" || resultMD.Markdown != "hello" { + t.Fatalf("resultMD=%+v", resultMD) + } +} + +func TestBuildMarkdownOCRDispatchResultDefersJSONNormalization(t *testing.T) { + result := buildMarkdownOCRDispatchResult("# Heading") + if result.OutputFormat != "markdown" { + t.Fatalf("OutputFormat = %q, want markdown", result.OutputFormat) + } + if result.Markdown != "# Heading" { + t.Fatalf("Markdown = %q, want original OCR markdown", result.Markdown) + } + if result.JSON != nil { + t.Fatalf("JSON = %#v, want nil until buildParserOutputs normalization", result.JSON) + } } type monkeyOCRv2FakeDriver struct { @@ -160,14 +181,10 @@ func (d *paddleOCRFakeDriver) OCRFile(_ context.Context, _ *string, _ []byte, _ return &modelModule.OCRFileResponse{Text: &d.text}, nil } -// TestDispatchPaddleOCRPdfLabelsPayloadAsMarkdown guards against the -// format-mismatch bug: PaddleOCR backends always return markdown text via -// OCRFile.Text, so the dispatch result MUST be labelled OutputFormat -// "markdown" regardless of what setup["output_format"] says (the pdf default -// is "json"). If the setup value leaked into OutputFormat, buildParserOutputs -// would emit a nil "json" payload and the downstream TokenChunker would -// consume an empty JSONResult -> "completed with 0 chunks". -func TestDispatchPaddleOCRPdfLabelsPayloadAsMarkdown(t *testing.T) { +// TestDispatchPaddleOCRPdfPreservesMarkdownForCentralNormalization verifies +// that PaddleOCR dispatch returns backend Markdown for the shared Parser +// output normalizer, regardless of the normalized component setup format. +func TestDispatchPaddleOCRPdfPreservesMarkdownForCentralNormalization(t *testing.T) { orig := resolvePaddleOCRModelForDispatch t.Cleanup(func() { resolvePaddleOCRModelForDispatch = orig }) @@ -177,8 +194,7 @@ func TestDispatchPaddleOCRPdfLabelsPayloadAsMarkdown(t *testing.T) { return &paddleOCRFakeDriver{text: md}, "ocr-model", &modelModule.APIConfig{BaseURL: &baseURL}, nil } - // The real run had output_format=json in the pdf setup; the payload must - // still be labelled markdown because that is what the backend produced. + // 1. output_format="json": preserve Markdown for central normalization. res, err := dispatchPaddleOCRPdf(t.Context(), dao.DB, "test.pdf", []byte("%PDF-1.4"), "tenant", schema.ParserSetup{"output_format": "json"}, "some-uuid") if err != nil { t.Fatalf("dispatchPaddleOCRPdf: %v", err) @@ -186,20 +202,41 @@ func TestDispatchPaddleOCRPdfLabelsPayloadAsMarkdown(t *testing.T) { if res.OutputFormat != "markdown" { t.Errorf("OutputFormat = %q, want markdown", res.OutputFormat) } + if res.JSON != nil { + t.Fatalf("res.JSON = %#v, want nil before central normalization", res.JSON) + } if res.Markdown != md { t.Errorf("Markdown = %q, want %q", res.Markdown, md) } - // Default setup (no output_format key) must behave identically. - res, err = dispatchPaddleOCRPdf(t.Context(), dao.DB, "test.pdf", []byte("%PDF-1.4"), "tenant", nil, "some-uuid") + // 2. output_format="markdown": the backend payload is unchanged. + resMD, err := dispatchPaddleOCRPdf(t.Context(), dao.DB, "test.pdf", []byte("%PDF-1.4"), "tenant", schema.ParserSetup{"output_format": "markdown"}, "some-uuid") + if err != nil { + t.Fatalf("dispatchPaddleOCRPdf (markdown): %v", err) + } + if resMD.OutputFormat != "markdown" { + t.Errorf("OutputFormat = %q, want markdown", resMD.OutputFormat) + } + if resMD.Markdown != md { + t.Errorf("Markdown = %q, want %q", resMD.Markdown, md) + } + if resMD.JSON != nil { + t.Errorf("resMD.JSON = %#v, want nil before central normalization", resMD.JSON) + } + + // 3. Default setup (no output_format key) follows the same central path. + resDef, err := dispatchPaddleOCRPdf(t.Context(), dao.DB, "test.pdf", []byte("%PDF-1.4"), "tenant", nil, "some-uuid") if err != nil { t.Fatalf("dispatchPaddleOCRPdf (default setup): %v", err) } - if res.OutputFormat != "markdown" { - t.Errorf("OutputFormat = %q, want markdown", res.OutputFormat) + if resDef.OutputFormat != "markdown" { + t.Errorf("OutputFormat = %q, want markdown", resDef.OutputFormat) } - if res.Markdown != md { - t.Errorf("Markdown = %q, want %q", res.Markdown, md) + if resDef.JSON != nil { + t.Fatalf("resDef.JSON = %#v, want nil before central normalization", resDef.JSON) + } + if resDef.Markdown != md { + t.Errorf("Markdown = %q, want %q", resDef.Markdown, md) } } diff --git a/internal/ingestion/component/schema/parser.go b/internal/ingestion/component/schema/parser.go index 5f6e91d1fce..da429fa7174 100644 --- a/internal/ingestion/component/schema/parser.go +++ b/internal/ingestion/component/schema/parser.go @@ -16,121 +16,34 @@ package schema -// ParserFromUpstream is the upstream payload consumed by the Parser -// component. It mirrors rag/flow/parser/schema.py:ParserFromUpstream -// (Pydantic BaseModel with populate_by_name, extra="forbid"). -// -// created_time: float | None (alias _created_time) -// elapsed_time: float | None (alias _elapsed_time) -// name: str (required) -// file: dict | None -// abstract: bool = False -// author: bool = False -type ParserFromUpstream struct { - CreatedTime *float64 `json:"_created_time,omitempty"` - ElapsedTime *float64 `json:"_elapsed_time,omitempty"` - - Name string `json:"name"` - - // File is the optional upstream file descriptor. Python allows None - // when the parser is invoked via a canvas-bound doc_id path. - File map[string]any `json:"file,omitempty"` - - Abstract bool `json:"abstract,omitempty"` - Author bool `json:"author,omitempty"` -} - -// Validate enforces the only required field in ParserFromUpstream: Name. -// Returns nil when Name is non-empty. -func (p *ParserFromUpstream) Validate() error { - if p.Name == "" { - return errRequiredField{Field: "name"} - } - return nil -} - -// Page is one parsed document section. The Parser component does not emit -// a typed page model — Python code passes around `dict` literals with -// shape `{text, layout_type, doc_type_kwd, positions?, image?, ...}`. To -// keep the wire schema typed without overcommitting to a parser-specific -// shape, Page is left as a generic map and provided for forward -// documentation; downstream chunker code operates on the same dict shape. -type Page map[string]any - -// ParserSetup is the per-filetype configuration block stored on -// ParserParam.setups[fileType]. The keys are heterogeneous (e.g., +// ParserSetup is a per-filetype parser configuration block. The keys are heterogeneous (e.g., // `parse_method`, `lang`, `output_format`, `suffix`, `fields`, `vlm`), // so a free-form map best mirrors the Python dict literal. type ParserSetup map[string]any -// ParserParam is the static configuration for the Parser component. -type ParserParam struct { - AllowedOutputFormat map[string][]string `json:"allowed_output_format"` -} - -// Defaults returns a ParserParam populated with the Python defaults — -// the full setups table copied verbatim from -// rag/flow/parser/parser.py:ParserParam.__init__ and the corresponding -// allowed_output_format map. -func (ParserParam) Defaults() ParserParam { - return ParserParam{ - AllowedOutputFormat: map[string][]string{ - "pdf": {"json", "markdown"}, - "spreadsheet": {"json", "markdown", "html"}, - "doc": {"json", "markdown"}, - "docx": {"json", "markdown"}, - "slides": {"json"}, - "image": {"json"}, - "email": {"text", "json"}, - "markdown": {"text", "json"}, - "text&code": {"text", "json"}, - "html": {"text", "json"}, - "audio": {"text", "json"}, - "video": {}, - "epub": {"text", "json"}, - "json": {"json"}, - }, - } -} - -// Validate returns nil. ParserParam's field set is fully defaulted by -// Defaults(); the component's own `check()` method performs business -// validation (e.g., "parse_method" must be one of the allowed set), and -// that runs in the component implementation. -func (ParserParam) Validate() error { return nil } - // ParserOutputs is the result of invoking the Parser component. The -// Python component calls `self.set_output(...)` with a mix of -// string-typed, list-typed, and dict-typed values. The wire schema -// below is the typed surface consumed by downstream components. -// -// Mirrors what Parser sets at rag/flow/parser/parser.py:_invoke. The -// parser writes to EITHER ("json" | "markdown" | "text" | "html") and -// always sets "output_format" + "file" + "_ERROR". +// wire format is "json", with structured JSON items as the only payload. type ParserOutputs struct { - // OutputFormat is the active output format for this run - // (one of "json", "markdown", "text", "html"). The downstream - // Tokenizer branches on this field. - OutputFormat string `json:"output_format,omitempty"` - - // JSON holds the list of structured sections when output_format == "json". - JSON []map[string]any `json:"json,omitempty"` + // Name is the resolved source filename. + Name string `json:"name"` - // Markdown holds the rendered Markdown when output_format == "markdown". - Markdown string `json:"markdown,omitempty"` + // OutputFormat is always "json". Downstream components consume structured JSON items. + OutputFormat string `json:"output_format,omitempty"` - // Text holds the rendered plain text when output_format == "text". - Text string `json:"text,omitempty"` + // JSON holds the list of structured sections (primary payload). + JSON []map[string]any `json:"json"` - // HTML holds the rendered HTML when output_format == "html". - HTML string `json:"html,omitempty"` + // Lang is the language used by downstream tokenization and model calls. + Lang string `json:"lang,omitempty"` - // File is the upstream file descriptor with parser-derived metadata - // (e.g., outlines) merged in. Mirrors the Python `set_output("file", ...)` - // at parser.py:609, 791, 828. + // File is backend-produced file metadata (for example page_count, + // outline, format, or sheets). When present, it replaces rather than + // merges with the upstream file descriptor. File map[string]any `json:"file,omitempty"` - // Error is set when the component short-circuits with an error - // message (Python: set_output("_ERROR", ...)). - Error string `json:"_ERROR,omitempty"` + // DocID, Bucket, and Path let downstream chunkers reacquire the source PDF + // for preview cropping without carrying its binary in the payload. + DocID string `json:"doc_id,omitempty"` + Bucket string `json:"bucket,omitempty"` + Path string `json:"path,omitempty"` } diff --git a/internal/ingestion/component/schema/schema_test.go b/internal/ingestion/component/schema/schema_test.go index 609b496c1cf..0943c23a73c 100644 --- a/internal/ingestion/component/schema/schema_test.go +++ b/internal/ingestion/component/schema/schema_test.go @@ -120,98 +120,64 @@ func TestFileOutputsJSONRoundTrip(t *testing.T) { // Parser // --------------------------------------------------------------------------- -func TestParserFromUpstreamValidate(t *testing.T) { - // Name is required. - if err := (&ParserFromUpstream{}).Validate(); err == nil { - t.Fatal("expected Validate to fail when Name is empty") - } - if err := (&ParserFromUpstream{Name: "doc.pdf"}).Validate(); err != nil { - t.Fatalf("Validate with Name unexpectedly failed: %v", err) - } -} - -func TestParserParamDefaults(t *testing.T) { - p := ParserParam{}.Defaults() - if err := p.Validate(); err != nil { - t.Fatalf("default ParserParam failed Validate: %v", err) - } - if got := p.AllowedOutputFormat["pdf"]; len(got) != 2 || got[0] != "json" || got[1] != "markdown" { - t.Errorf("default pdf allowed_output_format = %v, want [json markdown]", got) +func TestParserOutputsJSONRoundTrip(t *testing.T) { + original := ParserOutputs{ + Name: "input.pdf", + OutputFormat: "json", + JSON: []map[string]any{{"text": "hello", "doc_type_kwd": "text"}}, + Lang: "English", + File: map[string]any{"name": "input.pdf", "page_count": float64(1)}, + DocID: "doc-1", + Bucket: "bucket-1", + Path: "tenant/doc-1.pdf", } -} - -func TestParserParamJSONRoundTrip(t *testing.T) { - original := ParserParam{}.Defaults() data, err := json.Marshal(original) if err != nil { t.Fatalf("marshal: %v", err) } - if !strings.Contains(string(data), `"allowed_output_format"`) { - t.Errorf("expected allowed_output_format in JSON, got %s", data) + if !strings.Contains(string(data), `"output_format":"json"`) { + t.Errorf("expected output_format in JSON, got %s", data) } - var decoded ParserParam - if err = json.Unmarshal(data, &decoded); err != nil { + var decoded ParserOutputs + if err := json.Unmarshal(data, &decoded); err != nil { t.Fatalf("unmarshal: %v", err) } - if got := decoded.AllowedOutputFormat["pdf"]; len(got) != 2 || got[0] != "json" || got[1] != "markdown" { - t.Errorf("round-trip lost pdf allowed_output_format: got %v", got) - } -} - -func TestParserFromUpstreamJSONRoundTrip(t *testing.T) { - original := ParserFromUpstream{ - Name: "input.pdf", - Abstract: true, - Author: false, - } - data, err := json.Marshal(original) - if err != nil { - t.Fatalf("marshal: %v", err) + if decoded.OutputFormat != "json" { + t.Errorf("OutputFormat round-trip mismatch: got %q", decoded.OutputFormat) } - // abstract=true should be emitted; author=false has omitempty so it's - // dropped (zero-value bool with omitempty). We test the - // non-zero path. - if !strings.Contains(string(data), `"abstract":true`) { - t.Errorf("expected abstract=true in JSON, got %s", data) + if len(decoded.JSON) != 1 { + t.Errorf("JSON round-trip mismatch: got %d", len(decoded.JSON)) } - var decoded ParserFromUpstream - if err := json.Unmarshal(data, &decoded); err != nil { - t.Fatalf("unmarshal: %v", err) + if decoded.Name != original.Name || decoded.Lang != original.Lang { + t.Errorf("parser identity round-trip mismatch: got name=%q lang=%q", decoded.Name, decoded.Lang) } - if decoded.Name != original.Name { - t.Errorf("Name round-trip mismatch: got %q", decoded.Name) + if decoded.DocID != original.DocID || decoded.Bucket != original.Bucket || decoded.Path != original.Path { + t.Errorf("parser storage round-trip mismatch: got doc_id=%q bucket=%q path=%q", decoded.DocID, decoded.Bucket, decoded.Path) } - if !decoded.Abstract { - t.Errorf("Abstract round-trip mismatch: got %v", decoded.Abstract) - } - // author field is omitempty, so JSON round-trip should leave it false - // (default value) on both sides. - if decoded.Author { - t.Errorf("Author should be false, got true") + if decoded.File["name"] != "input.pdf" { + t.Errorf("parser file metadata round-trip mismatch: got %#v", decoded.File) } } -func TestParserOutputsJSONRoundTrip(t *testing.T) { +func TestParserOutputsJSONRoundTripPreservesEmptyItems(t *testing.T) { original := ParserOutputs{ + Name: "empty.txt", OutputFormat: "json", - JSON: []map[string]any{{"text": "hello", "doc_type_kwd": "text"}}, + JSON: []map[string]any{}, } data, err := json.Marshal(original) if err != nil { t.Fatalf("marshal: %v", err) } - if !strings.Contains(string(data), `"output_format":"json"`) { - t.Errorf("expected output_format in JSON, got %s", data) + if !strings.Contains(string(data), `"json":[]`) { + t.Fatalf("empty JSON payload omitted: %s", data) } var decoded ParserOutputs if err := json.Unmarshal(data, &decoded); err != nil { t.Fatalf("unmarshal: %v", err) } - if decoded.OutputFormat != "json" { - t.Errorf("OutputFormat round-trip mismatch: got %q", decoded.OutputFormat) - } - if len(decoded.JSON) != 1 { - t.Errorf("JSON round-trip mismatch: got %d", len(decoded.JSON)) + if decoded.JSON == nil || len(decoded.JSON) != 0 { + t.Fatalf("empty JSON payload round-trip mismatch: %#v", decoded.JSON) } } diff --git a/internal/ingestion/component/vision_enhancement.go b/internal/ingestion/component/vision_enhancement.go index dc2f81308c7..4823c97bb84 100644 --- a/internal/ingestion/component/vision_enhancement.go +++ b/internal/ingestion/component/vision_enhancement.go @@ -38,6 +38,7 @@ import ( "ragflow/internal/entity" modelModule "ragflow/internal/entity/models" "ragflow/internal/ingestion/component/schema" + "ragflow/internal/parser/parser" "ragflow/internal/utility" "gorm.io/gorm" @@ -162,10 +163,10 @@ func maybeDispatchVisionEnhancement( ctx context.Context, db *gorm.DB, fileType utility.FileType, - dispatched parserDispatchResult, + dispatched parser.ParseResult, inputs map[string]any, setups map[string]schema.ParserSetup, -) (parserDispatchResult, bool, error) { +) (parser.ParseResult, bool, error) { // 0. FileType allowlist guard. if !isVisionEnhancementAllowed(fileType) { return dispatched, false, nil diff --git a/internal/ingestion/component/vision_enhancement_test.go b/internal/ingestion/component/vision_enhancement_test.go index 84b107f0cd2..8d18b536ba8 100644 --- a/internal/ingestion/component/vision_enhancement_test.go +++ b/internal/ingestion/component/vision_enhancement_test.go @@ -31,6 +31,7 @@ import ( "ragflow/internal/entity" modelModule "ragflow/internal/entity/models" "ragflow/internal/ingestion/component/schema" + "ragflow/internal/parser/parser" "ragflow/internal/utility" "gorm.io/gorm" @@ -124,9 +125,8 @@ func TestVisionEnhancement_EnhancesJSONImagesAndTables(t *testing.T) { return "describe the figure in " + language, nil }) - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "json", - DocType: string(tc.fileType), JSON: []map[string]any{ {"text": "Intro paragraph", "image": nil, "doc_type_kwd": "text"}, {"text": "", "image": "aGVsbG8taW1hZ2U=", "doc_type_kwd": "image"}, @@ -186,9 +186,8 @@ func TestVisionEnhancement_MarkdownOutputUntouched(t *testing.T) { nil, ) - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "markdown", - DocType: "docx", Markdown: "![Image](data:image/png;base64,abc)", File: map[string]any{"figures": []map[string]any{{"image": "abc", "marker": "x"}}}, } @@ -214,9 +213,8 @@ func TestVisionEnhancement_MarkdownOutputUntouched(t *testing.T) { } func TestVisionEnhancement_NonAllowedFileTypeSkipped(t *testing.T) { - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "json", - DocType: "other", JSON: []map[string]any{ {"text": "", "image": "aGVsbG8=", "doc_type_kwd": "image"}, }, @@ -240,9 +238,8 @@ func TestVisionEnhancement_NonAllowedFileTypeSkipped(t *testing.T) { } func TestVisionEnhancement_EmptyOrNoTenantSkipped(t *testing.T) { - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "json", - DocType: "docx", JSON: []map[string]any{ {"text": "", "image": "aGVsbG8=", "doc_type_kwd": "image"}, }, @@ -267,7 +264,7 @@ func TestVisionEnhancement_EmptyOrNoTenantSkipped(t *testing.T) { // returned unchanged — enhancement must not touch items when dispatched.Err != nil. func TestVisionEnhancement_DispatchedErrSkipped(t *testing.T) { parseErr := errors.New("parse failed") - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ Err: parseErr, OutputFormat: "json", JSON: []map[string]any{ @@ -305,7 +302,7 @@ func TestVisionEnhancement_ContextCancellation(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) cancel() // pre-cancel - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "json", JSON: []map[string]any{ {"text": "", "image": "aGVsbG8=", "doc_type_kwd": "image"}, @@ -343,7 +340,7 @@ func TestVisionEnhancement_NonStringImageFieldFiltered(t *testing.T) { fakePrompt, ) - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "json", JSON: []map[string]any{ // non-string image field — filtered by target collector @@ -390,7 +387,7 @@ func TestVisionEnhancement_MoreThanConcurrencyItems(t *testing.T) { "doc_type_kwd": "image", } } - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "json", JSON: items, } @@ -427,7 +424,7 @@ func TestVisionEnhancement_PlainTextResponseNotTruncated(t *testing.T) { fakePrompt, ) - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "json", JSON: []map[string]any{ {"text": "", "image": "aGVsbG8=", "doc_type_kwd": "image"}, @@ -465,7 +462,7 @@ func TestVisionEnhancement_PromptBuilderErrorSkipped(t *testing.T) { }, ) - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "json", JSON: []map[string]any{ {"text": "", "image": "aGVsbG8=", "doc_type_kwd": "image"}, @@ -503,7 +500,7 @@ func TestVisionEnhancement_ModelResolveFailureSkipped(t *testing.T) { fakePrompt, ) - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "json", JSON: []map[string]any{ {"text": "", "image": "aGVsbG8=", "doc_type_kwd": "image"}, @@ -553,7 +550,7 @@ func TestVisionEnhancement_CancellationStopsSchedulingWithManyItems(t *testing.T "doc_type_kwd": "image", } } - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "json", JSON: items, } @@ -765,7 +762,7 @@ func TestVisionEnhancement_PerCallModelPreferred(t *testing.T) { setups := map[string]schema.ParserSetup{ "pdf": {"vlm": map[string]any{"llm_id": "custom-vlm@provider"}}, } - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "json", JSON: []map[string]any{ {"text": "", "image": "aGVsbG8=", "doc_type_kwd": "image"}, @@ -808,7 +805,7 @@ func TestVisionEnhancement_InvalidImageDataSkipped(t *testing.T) { fakePrompt, ) - dispatched := parserDispatchResult{ + dispatched := parser.ParseResult{ OutputFormat: "json", JSON: []map[string]any{ {"text": "keep", "image": "!!!not-base64!!!", "doc_type_kwd": "image"}, diff --git a/internal/parser/parser/charset_test.go b/internal/parser/parser/charset_test.go index cacd43c7961..7f50d792e4f 100644 --- a/internal/parser/parser/charset_test.go +++ b/internal/parser/parser/charset_test.go @@ -162,12 +162,16 @@ func TestCSVParser_GBK(t *testing.T) { if res.Err != nil { t.Fatalf("CSVParser.ParseWithResult failed: %v", res.Err) } - if strings.ContainsRune(res.HTML, '\ufffd') { - t.Errorf("CSV HTML output contains replacement runes: %s", res.HTML) + if len(res.JSON) == 0 { + t.Fatalf("CSVParser returned no JSON items") + } + tableHTML, _ := res.JSON[0]["text"].(string) + if strings.ContainsRune(tableHTML, '\ufffd') { + t.Errorf("CSV HTML output contains replacement runes: %s", tableHTML) } for _, want := range []string{"笔记本电脑", "电子", "特价销售,送鼠标", "无线耳机"} { - if !strings.Contains(res.HTML, want) { - t.Errorf("CSV HTML missing expected substring %q; got: %s", want, res.HTML) + if !strings.Contains(tableHTML, want) { + t.Errorf("CSV HTML missing expected substring %q; got: %s", want, tableHTML) } } if enc, _ := res.File["encoding"].(string); enc != "gb18030" && enc != "gbk" && enc != "gb2312" { diff --git a/internal/parser/parser/csv_parser.go b/internal/parser/parser/csv_parser.go index 57d62087315..64a3d206d62 100644 --- a/internal/parser/parser/csv_parser.go +++ b/internal/parser/parser/csv_parser.go @@ -14,8 +14,7 @@ // limitations under the License. // -// CSVParser renders CSV data as HTML tables, matching the spreadsheet -// family output_format == "html" convention from ParserParam.Defaults(). +// CSVParser renders CSV data as HTML table text in structured JSON table items. // // Mirrors Python's deepdoc/parser/excel_parser.py:RAGFlowExcelParser.html(): // - CSV data is rendered as an HTML with , so it has to be parsed in a table context. + name: "row without a table wrapper", + html: "", + want: [][2]string{{"q", "a"}}, + }, + { + name: "rows without a table wrapper", + html: "", + want: [][2]string{{"q", "a"}, {"q2", "a2"}}, + }, + { + name: "rows wrapped in tbody only", + html: "", + want: [][2]string{{"q", "a"}}, + }, + { + // Deliberately narrow: cells without a row are not a pair, matching + // the previous behaviour instead of inventing a row for them. + name: "cells without a row yield nothing", + html: "", + want: nil, + }, + { + name: "empty cell is skipped when picking the pair", + html: "
"Data". @@ -40,7 +39,7 @@ import ( const csvDefaultChunkRows = defaultTableChunkRows const csvSheetName = "Data" -// CSVParser reads RFC-4180 CSV data and emits HTML payloads. +// CSVParser reads RFC-4180 CSV data and emits structured table JSON items. type CSVParser struct { ParseMethod string OutputFormat string @@ -128,14 +127,17 @@ func (p *CSVParser) ParseWithResult(ctx context.Context, filename string, data [ decoded, encName := DecodeToUTF8(data, "text/csv") text := string(decoded) if strings.TrimSpace(text) == "" { + emptyHTML := "
" + csvSheetName + "
" return ParseResult{ - OutputFormat: "html", + OutputFormat: spreadsheetOutputFormat, File: map[string]any{ "name": filename, "size": len(data), "encoding": encName, + "format": "csv", + "sheets": 1, }, - HTML: "
" + csvSheetName + "
", + JSON: []map[string]any{NewTableJSONItem(emptyHTML, csvSheetName, [][]float64{{1, 1, 1, 1, 1}})}, } } @@ -157,13 +159,26 @@ func (p *CSVParser) ParseWithResult(ctx context.Context, filename string, data [ chunkRows = csvDefaultChunkRows } + chunks := recordsToHTMLTableChunkList(records, chunkRows, csvSheetName, 1) + items := make([]map[string]any, 0, len(chunks)) + for _, ch := range chunks { + items = append(items, NewTableJSONItem(ch.HTML, csvSheetName, [][]float64{{ + 1, + float64(ch.RowStart), + float64(ch.RowEnd), + float64(ch.ColStart), + float64(ch.ColEnd), + }})) + } return ParseResult{ - OutputFormat: "html", + OutputFormat: spreadsheetOutputFormat, File: map[string]any{ "name": filename, "size": len(data), "encoding": encName, + "format": "csv", + "sheets": 1, }, - HTML: recordsToHTMLTableChunks(records, chunkRows, csvSheetName), + JSON: items, } } diff --git a/internal/parser/parser/csv_parser_test.go b/internal/parser/parser/csv_parser_test.go new file mode 100644 index 00000000000..a8504ba47b3 --- /dev/null +++ b/internal/parser/parser/csv_parser_test.go @@ -0,0 +1,124 @@ +package parser + +import ( + "context" + "strings" + "testing" +) + +func TestCSVParser_BasicHTMLAndJSON(t *testing.T) { + csvData := []byte("Name,Age,City\nAlice,30,New York\nBob,25,San Francisco\n") + p := NewCSVParser() + + res := p.ParseWithResult(context.Background(), "test.csv", csvData) + if res.Err != nil { + t.Fatalf("ParseWithResult failed: %v", res.Err) + } + + // Default output format is "json" + if res.OutputFormat != "json" { + t.Fatalf("res.OutputFormat = %q, want %q", res.OutputFormat, "json") + } + + if len(res.JSON) != 1 { + t.Fatalf("len(res.JSON) = %d, want 1", len(res.JSON)) + } + + item := res.JSON[0] + if text, ok := item["text"].(string); !ok || !strings.Contains(text, "") { + t.Fatal("item text should contain rendered
") + } + if item["doc_type_kwd"] != "table" { + t.Errorf("item doc_type_kwd = %v, want 'table'", item["doc_type_kwd"]) + } + if item["ck_type"] != "table" { + t.Errorf("item ck_type = %v, want 'table'", item["ck_type"]) + } + if item["sheet"] != "Data" { + t.Errorf("item sheet = %v, want 'Data'", item["sheet"]) + } + positions, ok := item["positions"].([][]float64) + if !ok || len(positions) == 0 { + t.Fatalf("item positions invalid: %v", item["positions"]) + } + pos := positions[0] + // [sheet, rowStart, rowEnd, colStart, colEnd] + if len(pos) != 5 || pos[0] != 1 || pos[1] != 2 || pos[2] != 3 || pos[3] != 1 || pos[4] != 3 { + t.Errorf("unexpected positions: %v", pos) + } +} + +func TestCSVParser_ConfigureOutputFormatJSON(t *testing.T) { + csvData := []byte("col1,col2\nval1,val2\n") + p := NewCSVParser() + p.ConfigureFromSetup(map[string]any{ + "output_format": "json", + }) + + res := p.ParseWithResult(context.Background(), "test.csv", csvData) + if res.Err != nil { + t.Fatalf("ParseWithResult failed: %v", res.Err) + } + + if res.OutputFormat != "json" { + t.Fatalf("res.OutputFormat = %q, want 'json'", res.OutputFormat) + } + if len(res.JSON) != 1 { + t.Fatalf("len(res.JSON) = %d, want 1", len(res.JSON)) + } + if text, ok := res.JSON[0]["text"].(string); !ok || !strings.Contains(text, "
") { + t.Fatal("item text should contain rendered
") + } +} + +func TestCSVParser_EmptyContent(t *testing.T) { + p := NewCSVParser() + p.ConfigureFromSetup(map[string]any{ + "output_format": "json", + }) + + res := p.ParseWithResult(context.Background(), "empty.csv", []byte(" \n\n ")) + if res.Err != nil { + t.Fatalf("ParseWithResult failed: %v", res.Err) + } + + if res.OutputFormat != "json" { + t.Fatalf("res.OutputFormat = %q, want 'json'", res.OutputFormat) + } + if len(res.JSON) != 1 { + t.Fatalf("len(res.JSON) = %d, want 1", len(res.JSON)) + } + item := res.JSON[0] + if item["doc_type_kwd"] != "table" { + t.Errorf("item doc_type_kwd = %v, want 'table'", item["doc_type_kwd"]) + } +} + +func TestCSVParser_Chunking(t *testing.T) { + // Header + 4 data rows, chunk size = 2 + csvData := []byte("Header\nr1\nr2\nr3\nr4\n") + p := NewCSVParser() + p.ChunkRows = 2 + + res := p.ParseWithResult(context.Background(), "chunked.csv", csvData) + if res.Err != nil { + t.Fatalf("ParseWithResult failed: %v", res.Err) + } + + // 4 data rows with chunk_rows=2 => 2 chunks + if len(res.JSON) != 2 { + t.Fatalf("len(res.JSON) = %d, want 2", len(res.JSON)) + } + + pos1 := res.JSON[0]["positions"].([][]float64)[0] + pos2 := res.JSON[1]["positions"].([][]float64)[0] + + // chunk 1: rows 2..3 + if pos1[1] != 2 || pos1[2] != 3 { + t.Errorf("chunk 1 row range: [%v, %v], want [2, 3]", pos1[1], pos1[2]) + } + // chunk 2: rows 4..5 + if pos2[1] != 4 || pos2[2] != 5 { + t.Errorf("chunk 2 row range: [%v, %v], want [4, 5]", pos2[1], pos2[2]) + } +} diff --git a/internal/parser/parser/doc_parser.go b/internal/parser/parser/doc_parser.go index d4df6fa880f..8bc8c4cdaaa 100644 --- a/internal/parser/parser/doc_parser.go +++ b/internal/parser/parser/doc_parser.go @@ -26,27 +26,31 @@ import ( officeOxide "github.com/yfedoseev/office_oxide/go" ) -type DOCParser struct{} +type DOCParser struct { + OutputFormat string +} func NewDOCParser() *DOCParser { - return &DOCParser{} + return &DOCParser{ + OutputFormat: "json", + } } func (p *DOCParser) String() string { return "DOCParser" } -// ParseWithResult extracts text for the DOC family. The Go side uses -// office_oxide, which supports legacy .doc. We prefer the structured IR -// (flattened to plain text) and fall back to ToMarkdown, then to PlainText. -// -// office_oxide recovers table structure from legacy .doc through the IR -// (office_oxide/go v0.1.9, #116); list structure depends on whether the .doc -// reader surfaces list elements. Paragraph and heading (heuristically -// detected) lines are always present. When the IR carries table/list -// structure it is preferred so that content unique to the IR view is never -// shadowed by a longer but flatter view. OutputFormat stays "text" to keep -// the downstream contract unchanged. +func (p *DOCParser) ConfigureFromSetup(setup map[string]any) { + if p == nil || setup == nil { + return + } + if v, ok := setup["output_format"].(string); ok && v != "" { + p.OutputFormat = v + } +} + +// ParseWithResult extracts text for the DOC family and converts it to the +// requested output format (defaulting to "json" to match Python's default). func (p *DOCParser) ParseWithResult(ctx context.Context, filename string, data []byte) ParseResult { doc, err := officeOxide.OpenFromBytes(data, "doc") if err != nil { @@ -54,16 +58,38 @@ func (p *DOCParser) ParseWithResult(ctx context.Context, filename string, data [ } defer doc.Close() - text, err := extractDocText(doc) + text, mdText, err := extractDocText(doc) if err != nil { return ParseResult{Err: fmt.Errorf("doc extract: %w", err)} } - return ParseResult{ - OutputFormat: "text", + outFmt := p.OutputFormat + if outFmt == "" { + outFmt = "json" + } + + markdownPayload := text + if strings.TrimSpace(mdText) != "" { + markdownPayload = mdText + } + + res := ParseResult{ + OutputFormat: outFmt, File: map[string]any{"name": filename, "format": "doc"}, Text: text, + Markdown: markdownPayload, } + + if strings.EqualFold(outFmt, "markdown") { + return res + } + if strings.EqualFold(outFmt, "text") { + return res + } + + res.OutputFormat = "json" + res.JSON = []map[string]any{NewTextJSONItem(text)} + return res } // extractDocText returns the best-effort plain text for a legacy .doc @@ -81,7 +107,7 @@ func (p *DOCParser) ParseWithResult(ctx context.Context, filename string, data [ // is chosen so a sparser view never shadows a more complete one. A failure at // every stage degrades to the PlainText error, preserving the original "no // text at all" failure semantics. -func extractDocText(doc *officeOxide.Document) (string, error) { +func extractDocText(doc *officeOxide.Document) (string, string, error) { var irJSON, irText, mdText, plainText string if j, err := doc.ToIRJSON(); err == nil { irJSON = j @@ -95,9 +121,9 @@ func extractDocText(doc *officeOxide.Document) (string, error) { } else if strings.TrimSpace(irText) == "" && strings.TrimSpace(mdText) == "" { // Every view failed (or produced nothing): keep the original // "no text at all" failure semantics. - return "", err + return "", "", err } - return selectDocTextView(irJSON, irText, mdText, plainText), nil + return selectDocTextView(irJSON, irText, mdText, plainText), mdText, nil } // selectDocTextView chooses the best plain-text rendering from office_oxide's diff --git a/internal/parser/parser/doc_parser_synth_test.go b/internal/parser/parser/doc_parser_synth_test.go index 65c6056c017..8c7d1bafed5 100644 --- a/internal/parser/parser/doc_parser_synth_test.go +++ b/internal/parser/parser/doc_parser_synth_test.go @@ -146,8 +146,11 @@ func TestDOCParser_SyntheticDocRoundTrip(t *testing.T) { if pr.Err != nil { t.Fatalf("ParseWithResult error: %v", pr.Err) } - if pr.OutputFormat != "text" { - t.Fatalf("OutputFormat = %q, want %q", pr.OutputFormat, "text") + if pr.OutputFormat != "json" { + t.Fatalf("OutputFormat = %q, want %q", pr.OutputFormat, "json") + } + if len(pr.JSON) != 1 { + t.Fatalf("ParseWithResult returned %d JSON items, want 1", len(pr.JSON)) } if pr.Text == "" { t.Fatal("ParseWithResult returned empty text — synthetic .doc was not parsed") @@ -157,4 +160,15 @@ func TestDOCParser_SyntheticDocRoundTrip(t *testing.T) { t.Errorf("parsed text missing %q; got:\n%s", want, pr.Text) } } + if got, _ := pr.JSON[0]["text"].(string); got != pr.Text { + t.Errorf("JSON text = %q, want complete parser text %q", got, pr.Text) + } + + // Also verify that explicit output_format="text" in setup is respected + pText := NewDOCParser() + pText.ConfigureFromSetup(map[string]any{"output_format": "text"}) + prText := pText.ParseWithResult(context.Background(), "synthetic.doc", data) + if prText.OutputFormat != "text" { + t.Errorf("configured text OutputFormat = %q, want text", prText.OutputFormat) + } } diff --git a/internal/parser/parser/email_parser.go b/internal/parser/parser/email_parser.go index 99829273ef7..825b6be2348 100644 --- a/internal/parser/parser/email_parser.go +++ b/internal/parser/parser/email_parser.go @@ -47,7 +47,9 @@ type EmailParser struct { } func NewEmailParser() *EmailParser { - return &EmailParser{} + return &EmailParser{ + outputFormat: "json", + } } func (p *EmailParser) ConfigureFromSetup(setup map[string]any) { @@ -110,12 +112,16 @@ func (p *EmailParser) parseEmail(ctx context.Context, filename string, data []by } content = msg } else { - content = parseEML(bytes.NewReader(data), p.fields) + var err error + content, err = parseEMLWithError(bytes.NewReader(data), p.fields) + if err != nil { + return ParseResult{Err: fmt.Errorf("email: .eml: %w", err)} + } } outputFormat := p.outputFormat if outputFormat == "" { - outputFormat = "text" + outputFormat = "json" } // Re-chunk attachments so their content becomes retrievable within the @@ -125,27 +131,13 @@ func (p *EmailParser) parseEmail(ctx context.Context, filename string, data []by // never breaks the whole email. extraItems, attachmentText := p.rechunkEmailAttachments(ctx, content, depth) - // attachments has been consumed by rechunkEmailAttachments (which - // re-parses each attachment by extension to make its content - // retrievable). It is otherwise dead weight: jsonItemsToPages copies - // every key into a schema.Page, but buildPagesFromBytes keeps only - // text+doc_type_kwd, so carrying the full attachment payloads through to - // the chunker would only bloat the intermediate pages before being - // discarded. Drop it from the result content. + // Attachments have been consumed by rechunkEmailAttachments, which + // re-parses each one by extension into a searchable item. Keeping their + // raw payloads in the parent item would only bloat the parser result. delete(content, "attachments") - if outputFormat == "json" { - content["doc_type_kwd"] = "text" - items := []map[string]any{content} - items = append(items, extraItems...) - return ParseResult{ - OutputFormat: "json", - File: map[string]any{"name": filename}, - JSON: items, - } - } - - // Text output: flatten fields into a single string. + // Text representation: flatten fields into a single string for explicit + // text output and callers that need a display representation. var sb strings.Builder for k, v := range content { // The metadata map (every non-basic header: Received chains, @@ -193,11 +185,46 @@ func (p *EmailParser) parseEmail(ctx context.Context, filename string, data []by sb.WriteString(attachmentText) sb.WriteString("\n") } + text := sb.String() + + if outputFormat == "text" { + return ParseResult{ + OutputFormat: "text", + File: map[string]any{"name": filename}, + Text: text, + } + } + + content["doc_type_kwd"] = "text" + items := []map[string]any{content} + if headerText := searchableEmailHeaders(content); headerText != "" { + items = append(items, NewTextJSONItem(headerText)) + } + items = append(items, extraItems...) return ParseResult{ - OutputFormat: "text", + OutputFormat: "json", File: map[string]any{"name": filename}, - Text: sb.String(), + JSON: items, + Text: text, + } +} + +// searchableEmailHeaders returns the user-facing headers as a separate JSON +// text item. The main email item keeps its structured fields and body; the +// chunker indexes only item text, so headers need their own text item. +func searchableEmailHeaders(content map[string]any) string { + var sb strings.Builder + for _, key := range []string{"from", "to", "cc", "bcc", "date", "subject"} { + value, ok := content[key].(string) + if !ok || value == "" { + continue + } + sb.WriteString(key) + sb.WriteString(":") + sb.WriteString(value) + sb.WriteString("\n") } + return sb.String() } // -- field set helpers -- @@ -236,14 +263,13 @@ func decodeHeaderWord(val string) string { // -- .eml parsing (RFC 5322 with multipart support) -- -func parseEML(r io.Reader, fields []string) map[string]any { +func parseEMLWithError(r io.Reader, fields []string) (map[string]any, error) { target := targetFieldsSet(fields) content := map[string]any{} msg, err := mail.ReadMessage(r) if err != nil { - content["error"] = fmt.Sprintf("email: parse error: %v", err) - return content + return nil, err } // Headers. net/mail does not decode RFC 2047 encoded-words, so decode @@ -299,7 +325,7 @@ func parseEML(r io.Reader, fields []string) map[string]any { } } - return content + return content, nil } // readMailBody reads the body of an email message, handling diff --git a/internal/parser/parser/email_parser_test.go b/internal/parser/parser/email_parser_test.go index 3aa93711aa7..acc1d07e4cf 100644 --- a/internal/parser/parser/email_parser_test.go +++ b/internal/parser/parser/email_parser_test.go @@ -20,6 +20,7 @@ import ( "bytes" "context" "encoding/base64" + "io" "mime/multipart" "net/textproto" "os" @@ -28,6 +29,15 @@ import ( "time" ) +func mustParseEML(t *testing.T, reader io.Reader, fields []string) map[string]any { + t.Helper() + content, err := parseEMLWithError(reader, fields) + if err != nil { + t.Fatalf("parseEMLWithError: %v", err) + } + return content +} + func TestEmailParser_EmlJSON(t *testing.T) { ctx := t.Context() raw := strings.Join([]string{ @@ -55,8 +65,8 @@ func TestEmailParser_EmlJSON(t *testing.T) { if result.OutputFormat != "json" { t.Fatalf("expected output_format json, got %q", result.OutputFormat) } - if len(result.JSON) != 1 { - t.Fatalf("expected 1 JSON item, got %d", len(result.JSON)) + if len(result.JSON) != 2 { + t.Fatalf("expected body and header JSON items, got %d", len(result.JSON)) } item := result.JSON[0] @@ -82,6 +92,31 @@ func TestEmailParser_EmlJSON(t *testing.T) { if v, ok := item["doc_type_kwd"].(string); !ok || v != "text" { t.Errorf("doc_type_kwd: got %q", v) } + + header := result.JSON[1] + headerText, ok := header["text"].(string) + if !ok { + t.Fatalf("header item text missing: %#v", header) + } + for _, want := range []string{"from:sender@example.com", "to:recipient@example.com", "subject:Test Email"} { + if !strings.Contains(headerText, want) { + t.Errorf("header item missing %q: %q", want, headerText) + } + } + if strings.Contains(headerText, "This is the body of the test email.") { + t.Errorf("header item must not duplicate body text: %q", headerText) + } + if v, ok := header["doc_type_kwd"].(string); !ok || v != "text" { + t.Errorf("header doc_type_kwd: got %q", v) + } +} + +func TestEmailParser_InvalidEMLReturnsError(t *testing.T) { + p := NewEmailParser() + result := p.ParseWithResult(t.Context(), "broken.eml", []byte("not a valid RFC 5322 header")) + if result.Err == nil { + t.Fatalf("expected malformed EML error, got result %#v", result) + } } func TestEmailParser_EmlText(t *testing.T) { @@ -233,8 +268,8 @@ func TestEmailParser_MsgSupported(t *testing.T) { if result.Err != nil { t.Fatalf("unexpected error: %v", result.Err) } - if len(result.JSON) != 1 { - t.Fatalf("expected 1 JSON item, got %d", len(result.JSON)) + if len(result.JSON) != 2 { + t.Fatalf("expected body and header JSON items, got %d", len(result.JSON)) } item := result.JSON[0] @@ -349,7 +384,7 @@ func TestEmailParser_MsgTextOutputExcludesMetadata(t *testing.T) { t.Fatalf("read fixture: %v", err) } - p := NewEmailParser() // text output; default fields + p := NewEmailParser() // json output; default fields p.ConfigureFromSetup(map[string]any{ "fields": []string{"from", "to", "cc", "bcc", "date", "subject", "body", "attachments", "metadata"}, }) @@ -357,8 +392,11 @@ func TestEmailParser_MsgTextOutputExcludesMetadata(t *testing.T) { if result.Err != nil { t.Fatalf("unexpected error: %v", result.Err) } - if result.OutputFormat != "text" { - t.Fatalf("output format = %q, want text", result.OutputFormat) + if result.OutputFormat != "json" { + t.Fatalf("output format = %q, want json", result.OutputFormat) + } + if len(result.JSON) == 0 { + t.Fatalf("expected non-empty JSON items") } if !strings.Contains(result.Text, "subject:asdf") { @@ -421,7 +459,7 @@ func TestEmailParser_Base64Attachment(t *testing.T) { t.Error("attachments must be dropped from the final ParseResult") } // ...and verify the .eml branch still decodes the base64 attachment. - eml := parseEML(bytes.NewReader([]byte(raw)), []string{"from", "body", "attachments"}) + eml := mustParseEML(t, bytes.NewReader([]byte(raw)), []string{"from", "body", "attachments"}) atts, ok := eml["attachments"].([]map[string]any) if !ok { t.Fatalf("attachments missing or wrong type: %T", eml["attachments"]) @@ -507,7 +545,7 @@ func TestEmailParser_Base64AttachmentInMixedMultipart(t *testing.T) { t.Error("attachments must be dropped from the final ParseResult") } // ...and verify the .eml branch still decodes the base64 attachment. - eml := parseEML(bytes.NewReader([]byte(raw)), []string{"from", "body", "attachments"}) + eml := mustParseEML(t, bytes.NewReader([]byte(raw)), []string{"from", "body", "attachments"}) atts, ok := eml["attachments"].([]map[string]any) if !ok || len(atts) != 1 { t.Fatalf("expected 1 attachment, got %d", len(atts)) @@ -933,7 +971,7 @@ func TestEmailParser_AttachmentsWithoutBody(t *testing.T) { t.Error("attachments must be dropped from the final ParseResult") } // ...and verify the .eml branch still extracts them even without body. - eml := parseEML(bytes.NewReader([]byte(raw)), []string{"from", "attachments"}) + eml := mustParseEML(t, bytes.NewReader([]byte(raw)), []string{"from", "attachments"}) atts, ok := eml["attachments"].([]map[string]any) if !ok { t.Fatalf("attachments missing or wrong type: %T", eml["attachments"]) @@ -1254,7 +1292,7 @@ func TestParseEML_GB2312EncodedSubject(t *testing.T) { "body", }, "\r\n") - content := parseEML(strings.NewReader(raw), []string{"subject"}) + content := mustParseEML(t, strings.NewReader(raw), []string{"subject"}) if content["subject"] != "中文" { t.Errorf("subject = %q, want 中文", content["subject"]) } diff --git a/internal/parser/parser/markdown_parser.go b/internal/parser/parser/markdown_parser.go index 680db0a5c16..bb3dce85be4 100644 --- a/internal/parser/parser/markdown_parser.go +++ b/internal/parser/parser/markdown_parser.go @@ -51,13 +51,18 @@ type MarkdownParser struct { OutputFormat string VLM map[string]any FlattenMediaToText bool + // FetchRemoteImages controls whether HTTP(S) Markdown images are + // downloaded. NewMarkdownParser enables it for direct Markdown parsing; + // callers normalizing untrusted backend responses may disable it. + FetchRemoteImages bool } func NewMarkdownParser(libType string) (*MarkdownParser, error) { switch libType { case GoMarkdown: return &MarkdownParser{ - libType: GoMarkdown, + libType: GoMarkdown, + FetchRemoteImages: true, }, nil default: return nil, fmt.Errorf("unsupported Markdown library type: %s", libType) @@ -103,7 +108,7 @@ func (p *MarkdownParser) ParseWithResult(ctx context.Context, filename string, d doc := markdownNew().Parse([]byte(rendered)) var items []map[string]any - walkMarkdownBlocksWithImages(doc, &items, p.FlattenMediaToText) + walkMarkdownBlocksWithImages(doc, &items, p.FlattenMediaToText, p.FetchRemoteImages) if items == nil { items = []map[string]any{{"text": "", "doc_type_kwd": "text"}} } @@ -275,7 +280,7 @@ func markdownTableCells(line string) []string { // doc_type_kwd:"table" to keep the table whole and attach table context // to neighbouring chunks (chunker/token.go). Non-table HTML blocks // (
,
", + want: [][2]string{{"q", "a"}}, + }, + { + name: "noscript and template contribute no text", + html: "" + + "
qa
", + want: [][2]string{{"q", "a"}}, + }, + { + // The counterpart of the two cases above: elements whose content + // *is* rendered keep their text, so the skip list stays narrow. + name: "rendered descendants keep their text", + html: "" + + "
qabold
", + want: [][2]string{{"qnotes", "abold"}}, + }, + { + // A template's content goes into the ordinary child list, so its + // placeholder rows would otherwise be read as rows of the table. + name: "template rows are not table rows", + html: "" + + "
qa
", + want: [][2]string{{"q", "a"}}, + }, + { + // Foreign content reuses HTML tag names: an
carries no + // table semantics. + name: "svg rows are not table rows", + html: "
" + + "
VQVA
qa
", + want: [][2]string{{"q", "a"}}, + }, + { + // A template's rows are markup, not rows: the script's content is + // raw text to the parser, so only the real row becomes a pair. + // Found on a real page, where the unrendered template would + // otherwise contribute placeholder pairs. + name: "markup inside a script is not a row", + html: "" + + "
qa
", + want: [][2]string{{"q", "a"}}, + }, + { + name: "commented-out markup is not a pair", + html: "
qa
", + want: [][2]string{{"q", "a"}}, + }, + { + name: "commented-out cell is not a cell", + html: "
qa
", + want: [][2]string{{"q", "a"}}, + }, + { + // The nested table's text is folded into the cell holding it, and + // its own rows are not reported as rows of the enclosing table. + name: "nested table", + html: "
inx
a
", + want: [][2]string{{"inx", "a"}}, + }, + { + // A bare row fragment: the HTML5 "in body" mode would discard the + //
qa
qa
q2a2
qa
qa
qa
", + want: [][2]string{{"q", "a"}}, + }, + { + name: "unbalanced row yields nothing", + html: "
q only
", + want: nil, + }, + { + // The CSV contract (Python qa.py:365) is exactly two fields. + name: "three columns are rejected in strict mode", + html: "
qaextra
", + strict: true, + want: nil, + }, + { + name: "three columns keep the first two in lax mode", + html: "
qaextra
", + strict: false, + want: [][2]string{{"q", "a"}}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + pairs := extractQATable(tc.html, tc.strict) + got := make([][2]string, 0, len(pairs)) + for _, p := range pairs { + got = append(got, [2]string{p.Question, p.Answer}) + } + if len(got) != len(tc.want) { + t.Fatalf("pairs = %v, want %v", got, tc.want) + } + for i := range got { + if got[i] != tc.want[i] { + t.Errorf("pair %d = %q, want %q", i, got[i], tc.want[i]) + } + } + }) + } +} + +// BenchmarkExtractQATable makes the cost of the extraction reproducible: +// +// go test -run '^$' -bench BenchmarkExtractQATable -benchmem ./internal/ingestion/component/chunker/ +// +// The cells carry the two shapes that the previous tag-level scan handled +// worst — an embedded newline and an entity — so the numbers reflect the +// markup table items actually carry. +func BenchmarkExtractQATable(b *testing.B) { + for _, rows := range []int{10, 256, 1000} { + markup := benchmarkTable(rows) + b.Run(fmt.Sprintf("%d_rows", rows), func(b *testing.B) { + b.SetBytes(int64(len(markup))) + for i := 0; i < b.N; i++ { + extractQATable(markup, false) + } + }) + } +} + +// benchmarkTable renders a two-column table of the given size, one row per +// Q&A pair, with newlines and entities inside the cells. +func benchmarkTable(rows int) string { + var sb strings.Builder + sb.WriteString("" + + "") + for i := 0; i < rows; i++ { + fmt.Fprintf(&sb, + ""+ + "", i, i) + } + sb.WriteString("
Sheet1
questionanswer
question %d, which spans\na second lineanswer %d, with an entity & and more text
") + return sb.String() +} diff --git a/internal/ingestion/component/chunker/xlsx_qa_regression_test.go b/internal/ingestion/component/chunker/xlsx_qa_regression_test.go index 342170853c5..4700710f2c4 100644 --- a/internal/ingestion/component/chunker/xlsx_qa_regression_test.go +++ b/internal/ingestion/component/chunker/xlsx_qa_regression_test.go @@ -3,35 +3,44 @@ package chunker import ( "bytes" "context" + "strings" "testing" "github.com/xuri/excelize/v2" + "ragflow/internal/parser/parser" ) -func TestXLSXQARegression(t *testing.T) { +// xlsxWorkbook renders rows into an in-memory workbook so the tests run +// against the real spreadsheet parser instead of hand-written markup. +func xlsxWorkbook(t *testing.T, rows [][]string) []byte { + t.Helper() f := excelize.NewFile() sh := f.GetSheetName(0) - for i, r := range [][]string{ - {"question", "answer"}, - {"What is RAGFlow?", "A RAG engine."}, - {"Where are the docs?", "On the website."}, - } { + for i, r := range rows { for j, c := range r { cell, _ := excelize.CoordinatesToCellName(j+1, i+1) - _ = f.SetCellValue(sh, cell, c) + if err := f.SetCellValue(sh, cell, c); err != nil { + t.Fatal(err) + } } } var buf bytes.Buffer if err := f.Write(&buf); err != nil { t.Fatal(err) } + return buf.Bytes() +} +// qaChunksFromXLSX drives a workbook through the real XLSX parser and then +// the QA chunker, returning the chunks the pipeline would emit. +func qaChunksFromXLSX(t *testing.T, data []byte) []map[string]any { + t.Helper() p, err := parser.NewXLSXParser("") if err != nil { t.Fatal(err) } - res := p.ParseWithResult(context.Background(), "qa.xlsx", buf.Bytes()) + res := p.ParseWithResult(context.Background(), "qa.xlsx", data) if res.Err != nil { t.Fatal(res.Err) } @@ -53,8 +62,46 @@ func TestXLSXQARegression(t *testing.T) { t.Fatal(err) } chunks, _ := out["chunks"].([]map[string]any) - t.Logf("format=%q QA chunks=%d", res.OutputFormat, len(chunks)) + return chunks +} + +// TestXLSXQARegression is the end-to-end smoke test: every row of the sheet +// becomes one chunk. The chunker has no header concept, so the first row is +// a Q&A pair like any other. +func TestXLSXQARegression(t *testing.T) { + chunks := qaChunksFromXLSX(t, xlsxWorkbook(t, [][]string{ + {"question", "answer"}, + {"What is RAGFlow?", "A RAG engine."}, + {"Where are the docs?", "On the website."}, + })) + t.Logf("QA chunks=%d", len(chunks)) + if len(chunks) != 3 { + t.Fatalf("expected 3 chunks, got %d", len(chunks)) + } +} + +// A spreadsheet cell keeps the newline its author typed (Alt+Enter) and the +// parser renders it into the
HTML verbatim, so a QA pair whose +// question or answer spans lines must survive extraction intact. These rows +// used to disappear from the chunk list without a trace. +func TestXLSXQAMultilineCells(t *testing.T) { + const multilineQ = "请问全国碳排放权交易市场纳入配额管理的重点排放单\n位名录,是否会公布?" + const multilineA = "需要公布。根据《碳排放权交易管理办法(试行)》。" + const multilineAnswer = "跨行的答案\n第二行\n第三行" + + chunks := qaChunksFromXLSX(t, xlsxWorkbook(t, [][]string{ + {"question", "answer"}, + {multilineQ, multilineA}, + {"跨行的问句\n第二行", multilineAnswer}, + })) + t.Logf("QA chunks=%d", len(chunks)) if len(chunks) != 3 { t.Fatalf("expected 3 chunks, got %d", len(chunks)) } + texts := strings.Join(chunkTexts(chunks), "\n") + for _, want := range []string{multilineQ, multilineA, multilineAnswer} { + if !strings.Contains(texts, want) { + t.Errorf("chunk text lost the newline-bearing cell %q", want) + } + } } From 1f5d33333a3ff67fda2aa302c843699e994453e3 Mon Sep 17 00:00:00 2001 From: Yingfeng Date: Fri, 11 Sep 2026 22:37:33 +0800 Subject: [PATCH 122/568] Add claim/evidence to tree/pageindex compilation pipeline (#19267) --- api/apps/auth/README.md | 2 +- api/apps/restful_apis/chunk_api.py | 179 ++-- .../utils/compilation_template_validation.py | 5 + api/apps/services/dataset_api_service.py | 626 +++++--------- api/apps/services/structure_graph_common.py | 174 ++++ .../compilation_templates/page_index.yaml | 84 +- .../init_data/compilation_templates/tree.yaml | 44 + internal/handler/dataset_artifact.go | 59 ++ .../knowledge_compiler/common/deps.go | 7 + .../component/knowledge_compiler/common/id.go | 12 + .../knowledge_compiler/common/indextext.go | 107 +++ .../common/indextext_test.go | 90 ++ .../component/knowledge_compiler/component.go | 38 +- .../knowledge_compiler/component_test.go | 15 +- .../fixtures/structure_wiki_baseline.json | 2 +- .../knowledge_compiler/golden_test.go | 5 +- .../knowledge_compiler/structure/compile.go | 95 ++- .../knowledge_compiler/structure/evidence.go | 224 +++++ .../structure/evidence_test.go | 157 ++++ .../knowledge_compiler/structure/graph.go | 175 +++- .../knowledge_compiler/structure/prompt.go | 102 ++- .../structure/prompt_test.go | 91 ++ .../knowledge_compiler/structure/structure.go | 164 ++-- .../structure/structure_test.go | 18 +- .../knowledge_compiler/tree/claims.go | 677 +++++++++++++++ .../knowledge_compiler/tree/claims_test.go | 406 +++++++++ .../tree/duplicate_titles.go | 195 +++++ .../tree/duplicate_titles_test.go | 154 ++++ .../knowledge_compiler/tree/graph.go | 183 ++-- .../knowledge_compiler/tree/raptor.go | 187 +++- .../knowledge_compiler/tree/raptor_test.go | 2 +- .../ingestion/knowledge_compile/consumer.go | 57 +- .../knowledge_compile/nav_dispatch_test.go | 58 +- .../task/knowledge_compiler_wiring.go | 15 +- internal/ingestion/task/pipeline_executor.go | 41 +- .../ingestion/task/pipeline_executor_test.go | 45 +- .../advanced_rag/harness/tool_navigation.go | 24 +- .../harness/tool_navigation_test.go | 6 - internal/router/router.go | 2 + internal/service/dataset_artifact_service.go | 182 +++- internal/service/dataset_structure_graph.go | 42 +- rag/advanced_rag/agentic_rag_graph.py | 431 +++++++++- rag/advanced_rag/harness/action_session.py | 171 +++- .../harness/tools/compiled_expansion.py | 315 +++++++ rag/advanced_rag/harness/tools/navigation.py | 671 ++++++++++++++- rag/advanced_rag/knowlege_compile/_common.py | 15 + rag/advanced_rag/knowlege_compile/raptor.py | 395 ++++++++- .../knowlege_compile/structure.py | 807 ++++++++++++++++-- rag/flow/compiler/compiler.py | 20 +- rag/llm/chat_model.py | 12 + .../chunk_post_processor.py | 117 ++- .../task_executor_refactor/raptor_service.py | 254 ++---- .../task_executor_refactor/task_handler.py | 20 - .../services/test_dataset_api_service_nav.py | 293 +------ .../test_dataset_navigation_search.py | 5 +- .../{adapters.ts => adapters.tsx} | 45 +- .../structure-graph/claim-badge.tsx | 13 + .../representation-renderer.tsx | 14 + web/src/components/ui/tree-view.tsx | 13 +- web/src/hooks/use-document-request.ts | 56 +- .../database/compilation-template.ts | 1 + .../interfaces/database/document-structure.ts | 26 + .../request/compilation-template.ts | 1 + web/src/locales/en.ts | 11 + web/src/locales/ja.ts | 8 + web/src/locales/tr.ts | 8 + web/src/locales/zh.ts | 13 +- .../components/document-view-switch/index.tsx | 17 +- .../components/knowledge-chunk/index.tsx | 80 +- .../representation/components/claim-list.tsx | 237 +++++ web/src/pages/chunk/representation/index.tsx | 142 ++- .../components/tree-template-fields.tsx | 12 + .../compilation-templates/edit-next/schema.ts | 12 +- .../compilation-templates/edit-next/utils.ts | 2 + .../services/document-structure-service.ts | 15 + web/src/utils/api.ts | 2 + 76 files changed, 7518 insertions(+), 1487 deletions(-) create mode 100644 internal/ingestion/component/knowledge_compiler/common/indextext.go create mode 100644 internal/ingestion/component/knowledge_compiler/common/indextext_test.go create mode 100644 internal/ingestion/component/knowledge_compiler/structure/evidence.go create mode 100644 internal/ingestion/component/knowledge_compiler/structure/evidence_test.go create mode 100644 internal/ingestion/component/knowledge_compiler/structure/prompt_test.go create mode 100644 internal/ingestion/component/knowledge_compiler/tree/claims.go create mode 100644 internal/ingestion/component/knowledge_compiler/tree/claims_test.go create mode 100644 internal/ingestion/component/knowledge_compiler/tree/duplicate_titles.go create mode 100644 internal/ingestion/component/knowledge_compiler/tree/duplicate_titles_test.go rename web/src/components/structure-graph/{adapters.ts => adapters.tsx} (81%) create mode 100644 web/src/components/structure-graph/claim-badge.tsx create mode 100644 web/src/pages/chunk/representation/components/claim-list.tsx diff --git a/api/apps/auth/README.md b/api/apps/auth/README.md index 37df4e83919..bff359d93f6 100644 --- a/api/apps/auth/README.md +++ b/api/apps/auth/README.md @@ -1,6 +1,6 @@ # Auth -The Auth module provides implementations of OAuth2 and OpenID Connect (OIDC) authentication for integration with third-party identity providers. +The Auth module provides implementations of OAuth2 and OpenID Connect (OIDC) authentication for integration with third-party identity providers. **Features** diff --git a/api/apps/restful_apis/chunk_api.py b/api/apps/restful_apis/chunk_api.py index a1473082386..60f512767ef 100644 --- a/api/apps/restful_apis/chunk_api.py +++ b/api/apps/restful_apis/chunk_api.py @@ -786,43 +786,6 @@ def _response(templates: list[dict]) -> dict: except Exception as e: return server_error_response(e) - # RAPTOR summary graph is stored as a standalone blob rather than raw - # knowledge_graph_kwd entity/relation rows, so include its arrays explicitly. - raptor_entities: list[dict] = [] - raptor_relations: list[dict] = [] - try: - res_raptor = await thread_pool_exec( - settings.docStoreConn.search, - ["content_with_weight", "compile_kwd"], - [], - {"doc_id": [document_id], "compile_kwd": ["raptor_graph"]}, - [], - OrderByExpr(), - 0, - 16, - index_name, - [dataset_id], - ) - raptor_rows = settings.docStoreConn.get_fields(res_raptor, ["content_with_weight", "compile_kwd"]) or {} - except Exception: - logging.exception("structure graph: RAPTOR blob load failed for doc=%s", document_id) - raptor_rows = {} - for row in raptor_rows.values(): - try: - graph = json.loads(row.get("content_with_weight") or "{}") - except Exception: - continue - if not isinstance(graph, dict): - continue - r_entities = graph.get("entities") or [] - r_relations = graph.get("relations") or [] - if isinstance(r_entities, list): - raptor_entities.extend(r_entities) - if isinstance(r_relations, list): - raptor_relations.extend(r_relations) - total_entities += len(raptor_entities) - total_relations += len(raptor_relations) - def _row_template_id(row: dict) -> str | None: raw = row.get("compilation_template_ids") if isinstance(raw, list): @@ -911,9 +874,14 @@ def _resolve_bucket(row: dict) -> tuple[dict, dict]: return get_result(data=_response([bucket])) # ── normal mode: per-template subgraph sampling from the raw rows ── - # Discover buckets from the authoritative entity/relation rows. The - # structure compiler no longer emits a synthetic ``graph`` row, and a - # paged metadata-only scan avoids loading payloads or truncating large docs. + # Discover buckets from the authoritative per-doc entity/relation rows, + # WITHOUT loading the (potentially huge) content_with_weight. The compact + # graph blob is gone from the storage model: tree compilation now writes + # the same per-row shape as page_index, so buckets are discovered from the + # rows themselves. The scan is paged (metadata-only) to avoid truncating + # large docs — a doc carries one row per entity/relation, not one per + # template. Each bucket's entities/relations are then fetched with + # subgraph sampling. meta_fields = ["id", "compile_kwd", "compilation_template_ids", "compilation_template_kind_kwd"] meta_rows: dict = {} page_size = 1000 @@ -963,15 +931,8 @@ def _resolve_bucket(row: dict) -> tuple[dict, dict]: continue grouped[bid] = {**meta, "entities": entities, "relations": relations} - # RAPTOR was loaded above so its full counts are also available to keyword - # responses; append it only in normal mode, matching the existing behavior. - if raptor_entities or raptor_relations: - rb = grouped.setdefault("raptor", {"template_id": "raptor", "template_name": "RAPTOR Summary", "kind": "raptor", "entities": [], "relations": []}) - rb["entities"].extend(raptor_entities) - rb["relations"].extend(raptor_relations) - # Order: configured templates first (in the user's chosen order), - # then any discovered / legacy / raptor buckets after. + # then any discovered / legacy buckets after. ordered_ids: list[str] = [] for tid in configured_ids: if tid in grouped and tid not in ordered_ids: @@ -981,6 +942,27 @@ def _resolve_bucket(row: dict) -> tuple[dict, dict]: ordered_ids.append(bucket_id) page_index_groups = [group for group in grouped.values() if _compilation_template_kind(group.get("kind")) in {"page_index", "pageindex"}] + for group in page_index_groups: + # Headings at every level carry a claim badge, not just leaves: the UI + # opens a node's claims from any level, and a heading's own chunk span + # covers its whole subtree. Failures are logged and the tree renders + # without badges. + try: + await sgc.attach_claim_counts( + group.get("entities") or [], + group.get("relations") or [], + index_name, + dataset_id, + document_id, + _compilation_template_kind(group.get("kind")), + leaves_only=False, + ) + except Exception: + logging.exception( + "structure graph: page_index claim count attach failed for doc=%s template=%s", + document_id, + group.get("template_id"), + ) if page_index_groups: # PageIndex nodes should follow the document's chunk order. Use the # current chunk query order directly. Do not derive the order @@ -1028,6 +1010,98 @@ def entity_position(entity: dict, fallback: int): return get_result(data=_response(templates_out)) +async def _template_compile_kwd(template_id: str) -> str: + """The ``compile_kwd`` rows of this template were stamped with. + + Compiled rows carry the template's ``kind`` (page_index, tree, timeline…), + so any query that pins ``compile_kwd`` has to read it from the template + rather than assume one. Best-effort: ``None`` means "don't filter on it", + which is safe because the template id scopes the query anyway. + + Deliberately defined ABOVE the route it serves: slotting a helper between a + decorator stack and its function steals the registration, and the route + then calls the helper with the path parameters instead. + """ + from api.db.services.compilation_template_service import ( + CompilationTemplateService, + ) + + try: + rows = await thread_pool_exec(CompilationTemplateService.query, id=template_id) + except Exception: # pragma: no cover - lookup is best-effort + return "" + if not rows: + return "" + first = rows[0] + cfg = first.get("config") if isinstance(first, dict) else None + if isinstance(cfg, str): + try: + cfg = json.loads(cfg) + except (TypeError, ValueError): + cfg = None + if isinstance(cfg, dict) and cfg.get("kind"): + return _compilation_template_kind(cfg.get("kind")) + kind = first.get("kind") if isinstance(first, dict) else None + return _compilation_template_kind(kind) + + +@manager.route("/datasets//documents//structure/claims", methods=["GET"]) # noqa: F821 +@login_required +@add_tenant_id_to_kwargs +async def get_document_structure_claims(tenant_id, dataset_id, document_id): + """Page through a document's claim/evidence rows (entity_type_kwd="claim"). + + Tree artifacts keep claims out of the node list, so the UI fetches them per + leaf cluster on demand. Query args: + + chunk_ids: comma-separated source chunk ids — a leaf cluster's + members; without it the endpoint pages the whole document + template_id: compilation template scoping (optional) + offset/limit: paging, limit capped at 100 + """ + if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id): + return get_error_data_result(message=f"You don't own the dataset {dataset_id}.") + dataset_tenant_id = _get_dataset_tenant_id(dataset_id) + if not dataset_tenant_id: + return get_error_data_result(message=f"You don't own the dataset {dataset_id}.") + docs = DocumentService.query(id=document_id, kb_id=dataset_id) + if not docs: + return get_error_data_result(message=f"you don't own the document {document_id}") + + chunk_ids = [c.strip() for c in (request.args.get("chunk_ids") or "").split(",") if c.strip()] + template_id = (request.args.get("template_id") or "").strip() or None + try: + offset = max(int(request.args.get("offset") or 0), 0) + limit = min(max(int(request.args.get("limit") or 20), 1), 100) + except ValueError: + return get_error_data_result(message="offset/limit must be integers") + + # The rows' ``compile_kwd`` is the template's own kind. It used to be + # pinned to "tree" here, so a page_index document (compile_kwd="page_index") + # matched no rows at all and every node reported zero claims. + compile_kwd = None + if template_id: + compile_kwd = await _template_compile_kwd(template_id) or None + + from rag.nlp import search + + index_name = search.index_name(dataset_tenant_id) + try: + claims, total = await sgc.list_claim_rows( + index_name, + dataset_id, + document_id, + compile_kwd=compile_kwd, + compilation_template_id=template_id, + chunk_ids=chunk_ids or None, + offset=offset, + limit=limit, + ) + except Exception as e: + return server_error_response(e) + return get_result(data={"claims": claims, "total": total, "offset": offset, "limit": limit}) + + @manager.route("/datasets//documents//structure/graph", methods=["DELETE"]) # noqa: F821 @login_required @add_tenant_id_to_kwargs @@ -1036,11 +1110,10 @@ async def delete_document_structure_graph(tenant_id, dataset_id, document_id): Request body:: - {"template_id": "