Files
ragflow/internal/agent/canvas/multibranch_test.go
Zhichang Yu 3f805a64f1 feat(agent): align Go agent behavior with Python (except retrieval component) (#16225)
## Summary

Aligns the **Go agent runtime/canvas/components/tools** behavior with
the **Python `agent/` implementation** so the same stored canvas DSL
produces the same execution result on either side. Every component,
tool, and runtime primitive in `internal/agent/` is now driven by the
same semantics as its Python counterpart — variable resolution, template
substitution, control flow, error reporting, retry/cancel, and stream
event shapes.

The **retrieval component is the one explicit exception** in this PR. It
is being reworked in a separate change and is excluded from this
alignment pass; the wrapper slot (`universe_a_wrappers.go →
newRetrievalComponent`) is preserved.

## Scope of alignment

### Components (all aligned with `agent/component/`)
`Begin` · `Message` · `LLM` (incl. ChatTemplateKwargs,
MessageHistoryWindowSize, VisualFiles, Cite, OutputStructure,
JSONOutput, TopP, MaxRetries, DelayAfterError, credentials) · `Agent`
(react + tool artifact capture + `Reset()` interface-assert) · `Switch`
(12/12 operators, Python-equivalent semantics) · `Categorize` · `Invoke`
· `Iteration` · `Loop` (macro-expansion through `workflowx.AddLoopNode`)
· `UserFillUp` (Python-equivalent interrupt/resume via eino
`compose.Interrupt`/`ResumeWithData`) · `FillUp` · `DataOperations` ·
`ListOperations` · `StringTransform` · `VariableAggregator` ·
`VariableAssigner` · `Browser` (full stagehand runtime parity) ·
`DocsGenerator` · `ExcelProcessor`.

### Tools (all aligned with `agent/tools/`)
`Retrieval` (wrapper slot only — logic out of scope) · `MCPToolAdapter`
(streamable-HTTP) · `CodeExec` (sandbox bridge with
`code_exec_contract.go` matching Python contract) · `AkShare` · `ArXiv`
· `Crawler` · `DeepL` · `DuckDuckGo` · `Email` · `ExeSQL` · `GitHub` ·
`Google` · `GoogleScholar` · `Jin10` · `PubMed` · `QWeather` · `SearXNG`
· `Tavily` · `Tushare` · `Wencai` · `Wikipedia` · `YahooFinance` —
uniform `eino tool.InvokableTool` interface, SSRF protection, shared
HTTP client.

### Canvas execution engine (`internal/agent/canvas/`)
Aligned with Python's `agent/canvas.py`:
- **Scheduler** (`scheduler.go`): state pre/post handlers, node lambdas,
per-component timeout resolver (4-level: per-class env → per-class table
→ uniform env → 600s fallback), `legacyNoOpNames`.
- **Loop subgraph** (`loop_subgraph.go`): Python-equivalent
`AddLoopNode` macro expansion + condition translation.
- **Multibranch** (`multibranch.go`): `Switch` / `Categorize` routing
via `compose.NewGraphMultiBranch` — same branch selection semantics as
Python.
- **Parallel subgraph** (`parallel_subgraph.go`): matches Python's
parallel fan-out contract.
- **Interrupt/Resume** (`interrupt_resume.go`): `UserFillUpNodeBody` /
`IsInterruptError` / `ExtractInterruptContexts` — replaces the
deprecated Python sentinel chain with eino's native interrupt API,
preserving the same external behavior.
- **Checkpoint** (`checkpoint_store.go`): `RedisCheckPointStore`
Get/Set/Delete, with business metadata (status / canvas_id /
parent_run_id) on a parallel Redis Hash.
- **RunTracker** (`run_tracker.go`): Start / MarkSucceeded / MarkFailed
/ MarkCancelled / AttachCheckpoint — same lifecycle as the Python run
record.
- **Cancel** (`cancel.go`): Redis pub/sub watch.
- **Stream** (`stream.go`): SSE channel with `messages` / `waiting` /
`errors` / `done` events, same shape as Python's `agent.canvas.RunEvent`
payload.

### DSL bridge (`internal/agent/dsl/`)
- `normalize.go`: v1↔v2 collapsed into a single wire format — Python and
Go consume the same stored JSON.
- `reset.go`: per-run state reset matches Python's `Canvas.reset()`
semantics.
- Testdata mirrors Python's `agent_msg.json` / `all.json` / etc.

### Runtime (`internal/agent/runtime/`)
- `CanvasState` / `NewCanvasState` / `GetVar` / `SetVar` / `ReadVars`:
same `{{cpn_id@param}}` resolution model.
- `ResolveTemplate` (regex fast path + gonja fallback) — Python
Jinja-style semantics.
- `selector.go`, `metrics.go`, `component.go`: shared runtime contracts.

## Out of scope (intentionally)

- **`Retrieval` component logic** — wrapped only; full parity lands in a
follow-up PR.
- **Frontend** — only minor dsl-bridge / canvas UX fixes ride along.
- **CLI / admin / model registry** — orthogonal to agent behavior.

## How alignment is verified

`internal/service/agent_run_e2e_test.go` exercises the **full production
chain** against real Python-shaped DSL fixtures:
```
loadCanvasForUser → versionDAO.GetLatest → decodeCanvasFromDSL →
canvas.Compile → cc.Workflow.Invoke → answer extraction
```
using in-memory SQLite + miniredis (no Docker). Covers:
- `TestRunAgent_RealCanvas_BeginMessage` — happy path, `{{sys.query}}`
resolution
- `TestRunAgent_RealCanvas_WaitForUserResume` — two-run resume cycle
(Python-equivalent)
- `TestRunAgent_RealCanvas_CompileFails` — unknown component name →
sanitized error (Python-equivalent)
- `TestRunAgent_RealCanvas_InvokeFails` — unresolvable template ref
(Python-equivalent)
- `TestRunAgent_RunTracker_AttachCheckpoint_CallSequence` —
Start→AttachCheckpoint→MarkSucceeded lifecycle

`internal/handler/agent_test.go` — SSE streaming parity (`Content-Type:
text/event-stream`, `data: {…}\n\n`, trailing `data: [DONE]\n\n`,
OpenAI-compatible non-stream `choices`).

`internal/agent/canvas/fixture_compile_test.go` + per-component tests
pin the Python-equivalent outputs.

```
go test -count=1 -v -run 'TestRunAgent_RealCanvas|TestRunAgent_RunTracker' ./internal/service/
```

## Design reference

`docs/develop/agent-go-port-design.md` (1329 lines, last cross-checked
2026-06-17) — module layout, per-component / per-tool inventory,
corner-case catalogue, and the actionable backlog (Section 14, including
the retrieval alignment follow-up).

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-06-22 11:58:29 +08:00

343 lines
12 KiB
Go

//
// 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.
//
// multibranch_test.go — MultiBranch integration tests.
//
// The canvas scheduler (scheduler.go) installs an eino MultiBranch on
// every Switch / Categorize parent that has at least two declared
// downstream children. This file exercises two layers:
//
// 1. Pure unit tests for makeSwitchBranchCondition — the closure
// that turns outputs["_next"] into an end-node set (map[string]bool).
// These cover the missing/empty/unknown-key fallback paths in
// isolation.
//
// 2. End-to-end tests that BuildWorkflow a small canvas with a
// Switch → {childA, childB} topology, then invoke the compiled
// workflow and assert that only the chosen child ran. The
// children are real LLM components whose invoke bodies count
// their calls — driven by a stub chat invoker so the test
// doesn't talk to a network.
//
// The end-to-end layer requires the real component factory to be
// installed; the blank import at the top of the file triggers that
// via component.init() (same pattern as loop_semantics_test.go).
package canvas
import (
"context"
"testing"
"github.com/cloudwego/eino/compose"
"github.com/cloudwego/eino/schema"
)
// TestMakeSwitchBranchCondition_MissingField: when `_next` is absent
// from the parent's output, the condition returns nil so eino sees
// no chosen end-nodes and skips routing.
func TestMakeSwitchBranchCondition_MissingField(t *testing.T) {
cond := makeSwitchBranchCondition(map[string]bool{"a": true, "b": true})
got, err := cond(context.Background(), map[string]any{"other": "x"})
if err != nil {
t.Fatalf("cond: %v", err)
}
if len(got) != 0 {
t.Errorf("cond on missing _next = %v, want empty map", got)
}
}
// TestMakeSwitchBranchCondition_EmptyString: `_next: ""` is treated
// the same as missing.
func TestMakeSwitchBranchCondition_EmptyString(t *testing.T) {
cond := makeSwitchBranchCondition(map[string]bool{"a": true})
got, err := cond(context.Background(), map[string]any{"_next": ""})
if err != nil {
t.Fatalf("cond: %v", err)
}
if len(got) != 0 {
t.Errorf("cond on empty _next = %v, want empty map", got)
}
}
// TestMakeSwitchBranchCondition_WrongType: a non-string/_next
// value that is not []any is treated as missing. The Switch component
// is the only legitimate producer of `_next` and it always writes
// a []any (list of strings).
func TestMakeSwitchBranchCondition_WrongType(t *testing.T) {
cond := makeSwitchBranchCondition(map[string]bool{"a": true})
got, err := cond(context.Background(), map[string]any{"_next": 42})
if err != nil {
t.Fatalf("cond: %v", err)
}
if len(got) != 0 {
t.Errorf("cond on non-string _next = %v, want empty map", got)
}
}
// TestMakeSwitchBranchCondition_UnknownKey: `_next` resolves to a
// cpn_id that isn't in the end-nodes whitelist (e.g. a Switch whose
// `to` references a deleted component). We must NOT pass it to eino
// — that would error with "branch invocation returns unintended
// end node" at runtime and crash the run.
func TestMakeSwitchBranchCondition_UnknownKey(t *testing.T) {
cond := makeSwitchBranchCondition(map[string]bool{"a": true, "b": true})
got, err := cond(context.Background(), map[string]any{"_next": "ghost"})
if err != nil {
t.Fatalf("cond: %v", err)
}
if len(got) != 0 {
t.Errorf("cond on unknown _next = %v, want empty map", got)
}
}
// TestMakeSwitchBranchCondition_KnownKey: the happy path — a valid
// cpn_id is passed through as a single-entry map.
func TestMakeSwitchBranchCondition_KnownKey(t *testing.T) {
cond := makeSwitchBranchCondition(map[string]bool{"a": true, "b": true})
got, err := cond(context.Background(), map[string]any{"_next": "b"})
if err != nil {
t.Fatalf("cond: %v", err)
}
if !got["b"] || len(got) != 1 {
t.Errorf("cond on _next=b = %v, want {b:true}", got)
}
}
// TestMakeSwitchBranchCondition_MultiTargetList: when `_next` is a
// []any (list of strings — Python's multi-target "to" field), all
// whitelisted entries are returned. Unknown entries are silently
// dropped.
func TestMakeSwitchBranchCondition_MultiTargetList(t *testing.T) {
cond := makeSwitchBranchCondition(map[string]bool{"a": true, "b": true})
got, err := cond(context.Background(), map[string]any{"_next": []any{"a", "b", "ghost"}})
if err != nil {
t.Fatalf("cond: %v", err)
}
if len(got) != 2 || !got["a"] || !got["b"] {
t.Errorf("cond on _next=[a,b,ghost] = %v, want {a:true,b:true}", got)
}
}
// TestMakeSwitchBranchCondition_EmptyList: a _next of []any{} is
// treated as no branch chosen.
func TestMakeSwitchBranchCondition_EmptyList(t *testing.T) {
cond := makeSwitchBranchCondition(map[string]bool{"a": true})
got, err := cond(context.Background(), map[string]any{"_next": []any{}})
if err != nil {
t.Fatalf("cond: %v", err)
}
if len(got) != 0 {
t.Errorf("cond on empty list _next = %v, want empty map", got)
}
}
// TestIsBranchableControl: case-insensitive matching for Switch /
// Categorize and a negative case for an unrelated component.
func TestIsBranchableControl(t *testing.T) {
cases := []struct {
name string
in string
want bool
}{
{"switch exact", "Switch", true},
{"switch lower", "switch", true},
{"switch upper", "SWITCH", true},
{"categorize exact", "Categorize", true},
{"categorize lower", "categorize", true},
{"llm not branchable", "LLM", false},
{"empty not branchable", "", false},
{"message not branchable", "Message", false},
}
for _, tc := range cases {
if got := isBranchableControl(tc.in); got != tc.want {
t.Errorf("%s: isBranchableControl(%q) = %v, want %v", tc.name, tc.in, got, tc.want)
}
}
}
// TestWireMultiBranches_NoBranchable: a canvas with no Switch or
// Categorize returns an empty registration list. Compile still
// succeeds.
func TestWireMultiBranches_NoBranchable(t *testing.T) {
c := &Canvas{
Components: map[string]CanvasComponent{
"a": {Obj: CanvasComponentObj{ComponentName: "LLM"}},
"b": {Obj: CanvasComponentObj{ComponentName: "Message"}},
},
}
wf := compose.NewWorkflow[map[string]any, map[string]any]()
regs := wireMultiBranches(wf, c, nil)
if len(regs) != 0 {
t.Errorf("expected no branches, got %d: %+v", len(regs), regs)
}
}
// TestWireMultiBranches_SingleChildSkipped: a Switch with only one
// downstream child is degenerate — branch is meaningless. The
// helper should skip it and the AddInput edge handles invocation.
func TestWireMultiBranches_SingleChildSkipped(t *testing.T) {
c := &Canvas{
Components: map[string]CanvasComponent{
"sw": {
Obj: CanvasComponentObj{ComponentName: "Switch"},
Downstream: []string{"only"},
},
"only": {Obj: CanvasComponentObj{ComponentName: "Message"}},
},
}
wf := compose.NewWorkflow[map[string]any, map[string]any]()
regs := wireMultiBranches(wf, c, nil)
if len(regs) != 0 {
t.Errorf("expected no branch for single-child Switch, got %d: %+v", len(regs), regs)
}
}
// TestWireMultiBranches_LoopMemberSkipped: a Switch whose
// downstream children are loop members (i.e. inside a Loop body)
// is skipped — the outer graph can't route to children that live
// in a sub-workflow.
func TestWireMultiBranches_LoopMemberSkipped(t *testing.T) {
c := &Canvas{
Components: map[string]CanvasComponent{
"sw": {
Obj: CanvasComponentObj{ComponentName: "Switch"},
Downstream: []string{"inner_a", "inner_b"},
},
"inner_a": {Obj: CanvasComponentObj{ComponentName: "LLM"}},
"inner_b": {Obj: CanvasComponentObj{ComponentName: "LLM"}},
},
}
loopMembers := map[string]bool{"inner_a": true, "inner_b": true}
wf := compose.NewWorkflow[map[string]any, map[string]any]()
regs := wireMultiBranches(wf, c, loopMembers)
if len(regs) != 0 {
t.Errorf("expected no branch when all children are loop members, got %d: %+v", len(regs), regs)
}
}
// TestWireMultiBranches_RegistersTwoChildren: a Switch with two
// non-loop children registers exactly one branch with both as
// end-nodes.
func TestWireMultiBranches_RegistersTwoChildren(t *testing.T) {
c := &Canvas{
Components: map[string]CanvasComponent{
"sw": {
Obj: CanvasComponentObj{ComponentName: "Switch"},
Downstream: []string{"a", "b"},
},
"a": {Obj: CanvasComponentObj{ComponentName: "Message"}},
"b": {Obj: CanvasComponentObj{ComponentName: "Message"}},
},
}
wf := compose.NewWorkflow[map[string]any, map[string]any]()
regs := wireMultiBranches(wf, c, nil)
if len(regs) != 1 {
t.Fatalf("expected 1 branch, got %d", len(regs))
}
got := regs[0]
if got.Parent != "sw" {
t.Errorf("Parent=%q, want \"sw\"", got.Parent)
}
if len(got.EndNodes) != 2 {
t.Errorf("EndNodes len=%d, want 2: %v", len(got.EndNodes), got.EndNodes)
}
}
// TestWireMultiBranches_NilSafety: nil workflow / canvas inputs
// must not panic.
func TestWireMultiBranches_NilSafety(t *testing.T) {
// nil canvas
if got := wireMultiBranches(nil, nil, nil); got != nil {
t.Errorf("nil canvas: got %v, want nil", got)
}
wf := compose.NewWorkflow[map[string]any, map[string]any]()
if got := wireMultiBranches(wf, nil, nil); got != nil {
t.Errorf("nil canvas only: got %v, want nil", got)
}
}
// ----------------------------------------------------------------------------
// Compile-level topology test: a Switch → {childA, childB} DSL must
// compile end-to-end through BuildWorkflow + Compile without errors.
// This confirms that wireMultiBranches integrates cleanly with the
// rest of the scheduler (no missing end-nodes, no mis-typed field
// mappings, no double-wired AddInput conflicts).
//
// The actual *runtime* routing behaviour (which child fires when)
// is covered indirectly by TestMakeSwitchBranchCondition_KnownKey
// + the eino source-level guarantee that NewGraphMultiBranch
// enforces the endNodes whitelist. A full chat-invoker-driven e2e
// test lives in the component package's switch_test.go where it can
// stub the invoker from within the same package.
// ----------------------------------------------------------------------------
// TestMultiBranch_CompileSucceeds: BuildWorkflow + Compile of a
// Switch with two children completes without error. The resulting
// CompiledCanvas is non-nil and the workflow can be invoked (the
// Switch invocation will fail without a real state, but that's a
// test-harness limitation, not a multi-branch bug).
func TestMultiBranch_CompileSucceeds(t *testing.T) {
mkGroup := func(to, lhs, rhs string) map[string]any {
return map[string]any{
"op": "and",
"to": to,
"clauses": []any{
map[string]any{"left": lhs, "op": "==", "right": rhs},
},
}
}
conditions := []any{
mkGroup("a", "{{state.user_input}}", "go_a"),
mkGroup("b", "{{state.user_input}}", "go_b"),
}
dsl := &Canvas{
Components: map[string]CanvasComponent{
"begin": {
Obj: CanvasComponentObj{ComponentName: "Begin"},
Downstream: []string{"switch_0"},
},
"switch_0": {
Obj: CanvasComponentObj{
ComponentName: "Switch",
Params: map[string]any{"conditions": conditions},
},
Downstream: []string{"a", "b"},
Upstream: []string{"begin"},
},
"a": {
Obj: CanvasComponentObj{ComponentName: "Message"},
Upstream: []string{"switch_0"},
},
"b": {
Obj: CanvasComponentObj{ComponentName: "Message"},
Upstream: []string{"switch_0"},
},
},
}
cc, err := Compile(context.Background(), dsl)
if err != nil {
t.Fatalf("Compile: %v", err)
}
if cc == nil || cc.Workflow == nil {
t.Fatal("Compile produced nil workflow")
}
}
// Compile-time assertion that schema.Message is referenced so the
// import is preserved even if the test body shrinks.
var _ = schema.Assistant