RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(agent): reset execution path for new sessions (#18532)
Loongc15241c3a922
diff --git a/agent/canvas.py b/agent/canvas.pyindex 904d901a7f..78bd132901 100644--- a/agent/canvas.py+++ b/agent/canvas.py@@ -175,9 +175,7 @@ class Graph:obj = cpn.get("obj")if obj and hasattr(obj, "tools"):for tool in obj.tools.values():- session = tool if isinstance(tool, MCPToolCallSession) else (- tool.session if isinstance(tool, MCPToolBinding) else None- )+ session = tool if isinstance(tool, MCPToolCallSession) else (tool.session if isinstance(tool, MCPToolBinding) else None)if isinstance(session, MCPToolCallSession) and id(session) not in seen:seen.add(id(session))try:@@ -392,10 +390,12 @@ class Canvas(Graph):self.dsl["memory"] = self.memoryreturn super().__str__()- def clear_history(self):+ def start_new_session(self):+ """Discard replica state that must not leak into a fresh session."""self.history = []- if isinstance(self.globals.get("sys.history"), list):- self.globals["sys.history"] = []+ self.globals["sys.history"] = []+ self.path = []+ _logger.debug("Canvas conversation history and execution path reset for a new session")def reset(self, mem=False):super().reset()diff --git a/api/apps/restful_apis/agent_api.py b/api/apps/restful_apis/agent_api.pyindex 703961d101..05bb57d19a 100644--- a/api/apps/restful_apis/agent_api.py+++ b/api/apps/restful_apis/agent_api.py@@ -1599,8 +1599,8 @@ async def agent_chat_completion(tenant_id, agent_id=None):code=RetCode.OPERATING_ERROR,)- # Keep the original workflow execution path, but assign a session_id so the- # response shape stays closer to the older agent completion contract.+ # Load the caller's runtime replica as the workflow template. Session-owned+ # history and execution state are reset after Canvas instantiation below.query = req.get("query", "") or req.get("question", "")files = req.get("files", [])inputs = req.get("inputs", {})@@ -1691,7 +1691,7 @@ async def agent_chat_completion(tenant_id, agent_id=None):from agent.canvas import Canvascanvas = Canvas(dsl_str, str(tenant_id), task_id=session_id, canvas_id=agent_id, custom_header=custom_header)- canvas.clear_history()+ canvas.start_new_session()except Exception as exc:return server_error_response(exc)turn_id = get_uuid()diff --git a/internal/agent/dsl/reset.go b/internal/agent/dsl/reset.goindex 382869f777..7704dd1328 100644--- a/internal/agent/dsl/reset.go+++ b/internal/agent/dsl/reset.go@@ -44,6 +44,28 @@package dsl+// ResetForNewSession returns a defensive copy of dsl with only+// conversation-owned state cleared. A fresh session must not inherit the+// runtime replica's conversation history or execution path, while reusable+// state such as memory, retrieval results, environment variables, and graph+// structure is preserved.+func ResetForNewSession(dsl map[string]any) map[string]any {+ if dsl == nil {+ return map[string]any{}+ }+ out := deepCopyMap(dsl)+ out["history"] = []any{}+ out["path"] = []any{}++ globals, _ := out["globals"].(map[string]any)+ if globals == nil {+ globals = map[string]any{}+ out["globals"] = globals+ }+ globals["sys.history"] = []any{}+ return out+}+// ResetForCanvas returns a defensive copy of dsl with all per-run// state cleared, ready to be persisted back into user_canvas.dsl.//diff --git a/internal/agent/dsl/reset_test.go b/internal/agent/dsl/reset_test.goindex 8304a96bc0..1b9bc2726b 100644--- a/internal/agent/dsl/reset_test.go+++ b/internal/agent/dsl/reset_test.go@@ -21,6 +21,55 @@ import ("testing")+func TestResetForNewSession_ClearsOnlySessionOwnedState(t *testing.T) {+ in := map[string]any{+ "history": []any{"old turn"},+ "path": []any{"begin", "fillup"},+ "memory": []any{"reusable memory"},+ "retrieval": []any{"reusable retrieval"},+ "globals": map[string]any{+ "sys.history": []any{"old rendered turn"},+ "sys.files": []any{"keep.pdf"},+ "env.topic": "keep",+ },+ }++ got := ResetForNewSession(in)++ for _, key := range []string{"history", "path"} {+ if value, ok := got[key].([]any); !ok || len(value) != 0 {+ t.Errorf("%s = %#v, want empty []any", key, got[key])+ }+ }+ globals := got["globals"].(map[string]any)+ if history, ok := globals["sys.history"].([]any); !ok || len(history) != 0 {+ t.Errorf("sys.history = %#v, want empty []any", globals["sys.history"])+ }+ if !reflect.DeepEqual(got["memory"], []any{"reusable memory"}) ||+ !reflect.DeepEqual(got["retrieval"], []any{"reusable retrieval"}) ||+ !reflect.DeepEqual(globals["sys.files"], []any{"keep.pdf"}) ||+ globals["env.topic"] != "keep" {+ t.Fatalf("reusable state was changed: %#v", got)+ }++ if !reflect.DeepEqual(in["history"], []any{"old turn"}) ||+ !reflect.DeepEqual(in["path"], []any{"begin", "fillup"}) ||+ !reflect.DeepEqual(in["globals"].(map[string]any)["sys.history"], []any{"old rendered turn"}) {+ t.Fatalf("input DSL was mutated: %#v", in)+ }+}++func TestResetForNewSession_NormalizesMissingGlobals(t *testing.T) {+ got := ResetForNewSession(map[string]any{})+ globals, ok := got["globals"].(map[string]any)+ if !ok {+ t.Fatalf("globals = %#v, want map", got["globals"])+ }+ if history, ok := globals["sys.history"].([]any); !ok || len(history) != 0 {+ t.Fatalf("sys.history = %#v, want empty []any", globals["sys.history"])+ }+}+// TestResetForCanvas_ClearsPerRunState asserts the four top-level// accumulators are reset to fresh empty slices, matching the Python// `self.history = []` / `self.retrieval = []` / `self.memory = []`diff --git a/internal/service/agent.go b/internal/service/agent.goindex f4de04f7ce..8d35a46ece 100644--- a/internal/service/agent.go+++ b/internal/service/agent.go@@ -1675,6 +1675,10 @@ func (s *AgentService) RunAgent(ctx context.Context, userID, canvasID, sessionID// absent conversation row as a first touch regardless of who generated the// id; there is still only one business identity (session_id).if !sessionFound || newSession {+ // The editable/released canvas can be a runtime replica from another+ // conversation. A new session may reuse its graph, memory, and env state,+ // but must never inherit conversation history or an execution path.+ dsl = dslpkg.ResetForNewSession(dsl)if err = s.createAgentRunSession(ctx, sessionID, userID, canvasID, dsl, versionRow, userInput); err != nil {return nil, fmt.Errorf("RunAgent: create session %q: %w: %w", sessionID, err, ErrAgentStorageError)}diff --git a/internal/service/agent_run_e2e_test.go b/internal/service/agent_run_e2e_test.goindex 50cc67b737..1b8808f790 100644--- a/internal/service/agent_run_e2e_test.go+++ b/internal/service/agent_run_e2e_test.go@@ -373,8 +373,11 @@ func TestRunAgent_NewSessionPersistsHistoryForNextTurn(t *testing.T) {t.Cleanup(func() { dao.DB = orig })dsl := map[string]any{- "globals": map[string]any{"sys.history": []any{}},- "history": []any{},+ "globals": map[string]any{+ "sys.history": []any{"user: stale replica turn"},+ "env.topic": "preserved",+ },+ "history": []any{[]any{"user", "stale replica turn"}},"memory": []any{},"components": map[string]any{"begin_0": map[string]any{@@ -386,7 +389,7 @@ func TestRunAgent_NewSessionPersistsHistoryForNextTurn(t *testing.T) {"upstream": []any{"begin_0"},},},- "path": []any{"begin_0", "message_0"},+ "path": []any{"begin_0", "stale_fillup"},}makeCanvasWithDSL(t, "canvas-new-session", "user-1", "tenant-1", "v-new-session", dsl)@@ -410,6 +413,16 @@ func TestRunAgent_NewSessionPersistsHistoryForNextTurn(t *testing.T) {if session.ID == "" {t.Fatal("persisted session has an empty ID")}+ if history, ok := session.DSL["history"].([]any); !ok || len(history) != 2 {+ t.Fatalf("new session inherited replica history: %#v", session.DSL["history"])+ }+ if path, ok := session.DSL["path"].([]any); !ok || len(path) != 0 {+ t.Fatalf("new session inherited replica path: %#v", session.DSL["path"])+ }+ globals, _ := session.DSL["globals"].(map[string]any)+ if globals["env.topic"] != "preserved" {+ t.Fatalf("new session lost reusable env state: %#v", globals["env.topic"])+ }events, err = svc.RunAgent(context.Background(), "user-1", "canvas-new-session", session.ID, "", "1", nil)if err != nil {diff --git a/test/unit_test/agent/test_canvas_session_reset.py b/test/unit_test/agent/test_canvas_session_reset.pynew file mode 100644index 0000000000..1fa5da6622--- /dev/null+++ b/test/unit_test/agent/test_canvas_session_reset.py@@ -0,0 +1,77 @@+import contextvars+import importlib.util+import sys+from pathlib import Path+from types import ModuleType, SimpleNamespace+++def _stub(monkeypatch, name, **attrs):+ """Register a minimal dependency module for isolated Canvas loading."""+ module = ModuleType(name)+ for key, value in attrs.items():+ setattr(module, key, value)+ monkeypatch.setitem(sys.modules, name, module)+++def _load_canvas_module(monkeypatch):+ """Load the real Canvas class without its runtime service dependencies."""+ _stub(monkeypatch, "agent.component", component_class=lambda _name: None)+ _stub(monkeypatch, "agent.component.base", ComponentBase=object)+ _stub(monkeypatch, "agent.dsl_migration", normalize_chunker_dsl=lambda dsl: dsl)+ _stub(monkeypatch, "api.db.joint_services.tenant_model_service", get_tenant_default_model_by_type=lambda *_args: None)+ _stub(monkeypatch, "api.db.services.file_service", FileService=object)+ _stub(monkeypatch, "api.db.services.llm_service", LLMBundle=object)+ _stub(monkeypatch, "api.db.services.task_service", has_canceled=lambda *_args: False)+ _stub(monkeypatch, "common.constants", LLMType=SimpleNamespace(CHAT="chat"))+ _stub(+ monkeypatch,+ "common.llm_request_context",+ set_llm_request_context=lambda **_kwargs: None,+ reset_llm_request_context=lambda _token: None,+ )+ _stub(monkeypatch, "common.exceptions", TaskCanceledException=Exception)+ _stub(monkeypatch, "common.misc_utils", get_uuid=lambda: "uuid", hash_str2int=lambda value: hash(value))+ _stub(+ monkeypatch,+ "common.token_utils",+ token_usage_sink=contextvars.ContextVar("token_usage_sink", default=None),+ langfuse_run_attrs=contextvars.ContextVar("langfuse_run_attrs", default=None),+ )+ _stub(monkeypatch, "rag.prompts.generator", chunks_format=lambda *_args: [])+ _stub(monkeypatch, "rag.utils.redis_conn", REDIS_CONN=SimpleNamespace())+ _stub(monkeypatch, "rag.utils.tts_cache", synthesize_with_cache=lambda *_args, **_kwargs: None)++ module_path = Path(__file__).resolve().parents[3] / "agent" / "canvas.py"+ spec = importlib.util.spec_from_file_location("test_canvas_session_reset_module", module_path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++def test_start_new_session_discards_inherited_execution_state(monkeypatch):+ """A fresh session starts at Begin instead of resuming a replica's path."""+ module = _load_canvas_module(monkeypatch)+ canvas = module.Canvas.__new__(module.Canvas)+ canvas.history = [{"role": "user", "content": "previous session"}]+ canvas.globals = {"sys.history": [{"role": "user"}]}+ canvas.path = ["begin", "fillup"]++ canvas.start_new_session()++ assert canvas.history == []+ assert canvas.globals["sys.history"] == []+ assert canvas.path == []+++def test_start_new_session_normalizes_invalid_system_history(monkeypatch):+ """A fresh session never inherits a malformed system-history value."""+ module = _load_canvas_module(monkeypatch)+ canvas = module.Canvas.__new__(module.Canvas)+ canvas.history = []+ canvas.globals = {"sys.history": None}+ canvas.path = ["fillup"]++ canvas.start_new_session()++ assert canvas.globals["sys.history"] == []+ assert canvas.path == []