Skip to content

Refactor: drop dead canvas runtime selector and tokenizer embedding wiring - #16809

Merged
yuzhichang merged 2 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port
Jul 10, 2026
Merged

yuzhichang merged 2 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port

Conversation

@yuzhichang

Copy link
Copy Markdown
Member

Two refactors on the Go port (agent-go-port):

  • Remove the dead per-tenant canvas runtime selector (write-only Redis scaffolding with no runtime callers) and its dependent metrics/admin code.
  • Move the tokenizer embedding-model id from the shared ingestion globals into a Tokenizer-scoped setup, and wire the production embedder resolver in the ingestion task package.

32 files changed, 861 insertions, 1228 deletions.

The runtime.Selector (Redis-backed per-tenant override) was write-only
scaffolding: Selector.Set is only called by the admin endpoint, but
Selector.Select / Default() have no runtime callers, and RuntimePython /
RuntimeAuto have no implementation on the Go-only port.

metrics.go depended on RuntimeMode/Default() and its ObserveRun had no
production caller, so it is removed as well.

Removed: selector.go, metrics.go (+ tests), handler/admin_runtime.go
(+ test), router/admin_routes.go (+ test), and their wiring in
router.go and cmd/ragflow_server.go.

refactor(ingestion): route run-level metadata through CanvasState.Globals

Keep runtime/state.go generic (GetGlobal/SetGlobal only) and move the
ingestion-specific metadata whitelist and seeding helpers into a new
leaf package internal/ingestion/component/globals to avoid the
component<->pipeline test import cycle.

feat(agent): add cpnID-keyed run-level setups override for canvas compile

- Simplify mergeSetups to a shallow top-level merge: an override key
  fully replaces the base entry for the same key (no inner deep-merge).
- Override map is now keyed by cpnID; each component merges only its own
  entry via ctx (ctxKeySetupOverrides) threaded through
  Compile -> BuildWorkflow -> buildNodeBody. Components absent from the
  map are untouched, and the shared *Canvas params are never mutated.
- Fix misleading annotations: setups is a plain map[string]any with no
  file-type key constraint (pdf/docx are only Parser examples).
- Add node-level (buildNodeBody) and canvas-level (Compile) override tests.
…etups

The embedding-model id previously lived in the shared ingestion globals bag as
"model_id", which collided with the chat model id read by the llm/agent/
categorize/browser components. Move it to a Tokenizer-scoped setup
(params["setups"]["embedding_model"]) so it cannot be mistaken for a chat
model id.

- globals: drop model_id from GlobalMetadataKeys.
- tokenizer: read embedding_model from setups at construction; add package-level
  DefaultEmbedderResolver injection seam (component pkg must not import service);
  NewTokenizerComponentWithResolver is now test-only.
- dataflow_service: wire DefaultEmbedderResolver in init() via newEmbedderResolver
  (explicit embedding_model wins, falls back to kb.EmbdID); drop the test-only
  component factory, WithGetEmbeddingModelFunc, and per-executor resolver plumbing.
- tests: replace resolveEmbeddingModel tests with newEmbedderResolver tests.
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jul 10, 2026
@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Canvas execution

Layer / File(s) Summary
Run-level setup overrides
internal/agent/canvas/*, internal/ingestion/pipeline/pipeline.go
Compilation accepts per-component setup overrides, merges them before factory construction, and validates shallow replacement and nil no-op behavior.
Agent server bootstrap
cmd/ragflow_server.go
Startup conditionally enables Redis-backed agent run infrastructure and configures TTS dispatch with a nil-safe fallback.

Ingestion metadata and embedding

Layer / File(s) Summary
Workflow globals
internal/agent/runtime/state.go, internal/ingestion/component/globals/*, internal/ingestion/pipeline/pipeline.go
Run metadata is seeded, published, and resolved through synchronized CanvasState.Globals.
Chunker and component propagation
internal/ingestion/component/chunker/*, internal/ingestion/component/file.go, internal/ingestion/component/parser.go
Chunkers resolve shared names through globals, while file and parser components publish metadata for downstream nodes.
Tokenizer and resolver wiring
internal/ingestion/component/tokenizer.go, internal/ingestion/task/dataflow_service.go, internal/ingestion/task/*_test.go
Embedding selection becomes setup-scoped and uses a global resolver with dataset fallback; task-scoped resolver hooks are removed.

Runtime selector removal

Layer / File(s) Summary
Admin runtime removal
cmd/ragflow_server.go, internal/handler/*, internal/router/*, internal/agent/runtime/*
Redis-backed runtime selection, its admin handler and route registration, and associated tests are removed.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Pipeline
  participant CanvasState
  participant Components
  participant EmbedderResolver
  Pipeline->>CanvasState: seed run metadata
  Components->>CanvasState: publish and read globals
  Components->>EmbedderResolver: resolve tenant, KB, and setup model
  EmbedderResolver-->>Components: return embedder
Loading

Possibly related PRs

Suggested labels: ☯️ refactor, 🧪 test

Suggested reviewers: yingfeng, JinHai-CN

Poem

I’m a rabbit hopping through setup maps,
Globals carry metadata in tidy laps.
Redis routes fade into the night,
Embedders resolve just right.
TTS hums softly—what a flight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main refactor: removing the canvas runtime selector and changing tokenizer embedding wiring.
Description check ✅ Passed The description matches the template’s Summary section and gives a clear, relevant overview of the PR changes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@yuzhichang yuzhichang added the ci Continue Integration label Jul 10, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (3)
internal/ingestion/component/tokenizer.go (1)

767-772: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Delete getStringOr from internal/ingestion/component/tokenizer.go. It has no callers in the repo, so it can be removed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/ingestion/component/tokenizer.go` around lines 767 - 772, Remove the
unused getStringOr function from tokenizer.go, confirming no callers remain and
deleting only this dead helper.

Source: Coding guidelines

internal/agent/canvas/node_body_setup_override_test.go (1)

97-121: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider asserting base params immutability when an override is present.

TestBuildNodeBody_SetupOverridesNilIsNoOp checks immutability for the no-override case, but TestBuildNodeBody_SetupOverrides (which has real base setups) doesn't verify that baseParams["setups"] remains unchanged after the merge. An explicit assertion would close this gap and protect the "per-run override must not leak into the next Run" contract.

🧪 Suggested addition
 	if _, ok := pdf["parse_method"]; ok {
 		t.Errorf("pdf.parse_method should be dropped by shallow merge: %#v", pdf)
 	}
+
+	// Immutability: the original base params must not be mutated.
+	origSetups, _ := baseParams["setups"].(map[string]any)
+	origPdf, _ := origSetups["pdf"].(map[string]any)
+	if origPdf["parse_method"] != "naive" {
+		t.Errorf("original base params setups were mutated: %#v", baseParams["setups"])
+	}
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/agent/canvas/node_body_setup_override_test.go` around lines 97 -
121, Add an explicit immutability assertion to TestBuildNodeBody_SetupOverrides
after the merge, comparing baseParams["setups"] with its original pre-merge
value and verifying the override has not mutated it. Preserve the existing
assertions for the captured merged setups and ensure the test covers that
subsequent runs cannot observe leaked override values.
internal/agent/canvas/compile_setup_override_test.go (1)

99-127: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider asserting the original DSL params are not mutated.

The test verifies the merged result thoroughly but doesn't check that dsl.Components["parser_0"].Obj.Params["setups"] remains unchanged after Compile. Since applySetupOverrides clones params, the original should be untouched, but an explicit assertion would protect against future regressions that break the immutability contract.

🧪 Suggested addition
 	// sink_0: absent from the override → no setups key injected.
 	if _, ok := captured["Sink"]["setups"]; ok {
 		t.Errorf("Sink should not receive a setups key: %#v", captured["Sink"])
 	}
+
+	// Immutability: the original DSL params must not be mutated.
+	origPdf, _ := dsl.Components["parser_0"].Obj.Params["setups"].(map[string]any)["pdf"].(map[string]any)
+	if origPdf["parse_method"] != "naive" {
+		t.Errorf("original DSL setups were mutated: %#v", dsl.Components["parser_0"].Obj.Params["setups"])
+	}
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/agent/canvas/compile_setup_override_test.go` around lines 99 - 127,
Add an assertion in the compile override test after Compile and merged-result
checks to verify dsl.Components["parser_0"].Obj.Params["setups"] still matches
its original pre-Compile value, including preserved base entries and excluding
injected or overridden values. Use the existing applySetupOverrides/Compile test
context to ensure the immutability contract is explicitly covered.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/ingestion/component/chunker/register.go`:
- Around line 72-74: Update the ChunkerOutputs documentation for name,
tenant_id, and kb_id to state that these values are resolved from
CanvasState.Globals by downstream components and are not emitted by the chunker.
Alternatively, remove these fields from ChunkerOutputs if the schema should list
only actual outputs; keep the description consistent with chunkOutputs().

In `@internal/ingestion/pipeline/pipeline.go`:
- Around line 280-287: Update the comment above globals.SeedIngestionGlobals in
the pipeline initialization to remove model_id from the listed seeded metadata,
keeping only keys actually populated by GlobalMetadataKeys and preserving the
explanation of run-level globals.

---

Nitpick comments:
In `@internal/agent/canvas/compile_setup_override_test.go`:
- Around line 99-127: Add an assertion in the compile override test after
Compile and merged-result checks to verify
dsl.Components["parser_0"].Obj.Params["setups"] still matches its original
pre-Compile value, including preserved base entries and excluding injected or
overridden values. Use the existing applySetupOverrides/Compile test context to
ensure the immutability contract is explicitly covered.

In `@internal/agent/canvas/node_body_setup_override_test.go`:
- Around line 97-121: Add an explicit immutability assertion to
TestBuildNodeBody_SetupOverrides after the merge, comparing baseParams["setups"]
with its original pre-merge value and verifying the override has not mutated it.
Preserve the existing assertions for the captured merged setups and ensure the
test covers that subsequent runs cannot observe leaked override values.

In `@internal/ingestion/component/tokenizer.go`:
- Around line 767-772: Remove the unused getStringOr function from tokenizer.go,
confirming no callers remain and deleting only this dead helper.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: af227703-2625-4f7a-8ed0-ecfbbdc521d0

📥 Commits

Reviewing files that changed from the base of the PR and between 7db3982 and 8ff0d00.

📒 Files selected for processing (32)
  • cmd/ragflow_server.go
  • internal/agent/canvas/compile.go
  • internal/agent/canvas/compile_setup_override_test.go
  • internal/agent/canvas/node_body.go
  • internal/agent/canvas/node_body_setup_override_test.go
  • internal/agent/runtime/metrics.go
  • internal/agent/runtime/metrics_test.go
  • internal/agent/runtime/selector.go
  • internal/agent/runtime/selector_test.go
  • internal/agent/runtime/state.go
  • internal/handler/admin_runtime.go
  • internal/handler/admin_runtime_test.go
  • internal/ingestion/component/chunker/common.go
  • internal/ingestion/component/chunker/group.go
  • internal/ingestion/component/chunker/hierarchy.go
  • internal/ingestion/component/chunker/register.go
  • internal/ingestion/component/chunker/title.go
  • internal/ingestion/component/chunker/token.go
  • internal/ingestion/component/extractor.go
  • internal/ingestion/component/file.go
  • internal/ingestion/component/globals/globals.go
  • internal/ingestion/component/parser.go
  • internal/ingestion/component/schema/chunker.go
  • internal/ingestion/component/tokenizer.go
  • internal/ingestion/component/tokenizer_test.go
  • internal/ingestion/pipeline/pipeline.go
  • internal/ingestion/task/dataflow_service.go
  • internal/ingestion/task/dataflow_service_test.go
  • internal/ingestion/task/task_handler_test.go
  • internal/router/admin_routes.go
  • internal/router/admin_routes_test.go
  • internal/router/router.go
💤 Files with no reviewable changes (10)
  • internal/router/admin_routes.go
  • internal/handler/admin_runtime_test.go
  • internal/agent/runtime/metrics.go
  • internal/handler/admin_runtime.go
  • internal/router/admin_routes_test.go
  • internal/agent/runtime/selector.go
  • internal/agent/runtime/metrics_test.go
  • internal/agent/runtime/selector_test.go
  • internal/router/router.go
  • cmd/ragflow_server.go

Comment on lines +72 to +74
"name": "Source document name, carried forward from upstream (pass-through) when present — Tokenizer consumes it for title embedding.",
"tenant_id": "Carried forward from upstream (pass-through) when present — Tokenizer consumes it to resolve the embedding model.",
"kb_id": "Carried forward from upstream (pass-through) when present — Tokenizer consumes it to resolve the embedding model.",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

ChunkerOutputs documents pass-through fields that the chunker does not emit.

chunkOutputs() (common.go:217-222) only returns output_format and chunks. Individual chunk maps contain only {"text": ...}. The name, tenant_id, and kb_id fields are never present in the chunker's output — they live in CanvasState.Globals and are read directly from ctx by downstream components (Tokenizer). The chunkOutputs comment itself states metadata "is NOT re-emitted here."

The current descriptions ("carried forward from upstream (pass-through)") imply these are output fields, which is misleading. Consider either removing them from ChunkerOutputs or rewording to clarify they are Globals-resolved, not chunker outputs.

📝 Suggested rewording
 var ChunkerOutputs = map[string]string{
 	"output_format": "Always \"chunks\" on success.",
 	"chunks":        "list[object]: per-chunk map (text + optional meta keys).",
-	"name":          "Source document name, carried forward from upstream (pass-through) when present — Tokenizer consumes it for title embedding.",
-	"tenant_id":     "Carried forward from upstream (pass-through) when present — Tokenizer consumes it to resolve the embedding model.",
-	"kb_id":         "Carried forward from upstream (pass-through) when present — Tokenizer consumes it to resolve the embedding model.",
+	"name":          "Not emitted in output; resolved from CanvasState.Globals by downstream Tokenizer for title embedding.",
+	"tenant_id":     "Not emitted in output; resolved from CanvasState.Globals by downstream Tokenizer for embedding model selection.",
+	"kb_id":         "Not emitted in output; resolved from CanvasState.Globals by downstream Tokenizer for embedding model selection.",
 	"_ERROR":        "Set only on validation failure.",
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"name": "Source document name, carried forward from upstream (pass-through) when present — Tokenizer consumes it for title embedding.",
"tenant_id": "Carried forward from upstream (pass-through) when present — Tokenizer consumes it to resolve the embedding model.",
"kb_id": "Carried forward from upstream (pass-through) when present — Tokenizer consumes it to resolve the embedding model.",
"name": "Not emitted in output; resolved from CanvasState.Globals by downstream Tokenizer for title embedding.",
"tenant_id": "Not emitted in output; resolved from CanvasState.Globals by downstream Tokenizer for embedding model selection.",
"kb_id": "Not emitted in output; resolved from CanvasState.Globals by downstream Tokenizer for embedding model selection.",
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/ingestion/component/chunker/register.go` around lines 72 - 74,
Update the ChunkerOutputs documentation for name, tenant_id, and kb_id to state
that these values are resolved from CanvasState.Globals by downstream components
and are not emitted by the chunker. Alternatively, remove these fields from
ChunkerOutputs if the schema should list only actual outputs; keep the
description consistent with chunkOutputs().

Comment on lines +280 to +287
// Seed the workflow-wide Globals bag with the run-level metadata
// (name, tenant_id, kb_id, model_id, doc_id, ...) once, from the
// pipeline run inputs. Downstream components read these from ctx
// instead of relying on every node re-emitting them. The File
// component re-publishes `name` (and storage refs) as it derives
// them mid-run.
globals.SeedIngestionGlobals(runCtx, current)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Stale comment references model_id which is not a seeded global.

The comment at line 281 lists model_id among the run-level metadata seeded into Globals, but GlobalMetadataKeys in globals.go does not include it. The globals package comment (lines 56–59) explicitly states the embedding-model id is intentionally NOT a global — it is a Tokenizer-scoped setup. This comment appears to predate the removal of model_id from the globals whitelist and should be corrected to avoid misleading future readers.

📝 Proposed fix for the stale comment
 	// Seed the workflow-wide Globals bag with the run-level metadata
-	// (name, tenant_id, kb_id, model_id, doc_id, ...) once, from the
+	// (name, tenant_id, kb_id, doc_id, bucket, path, file) once, from the
 	// pipeline run inputs. Downstream components read these from ctx
 	// instead of relying on every node re-emitting them. The File
 	// component re-publishes `name` (and storage refs) as it derives
 	// them mid-run.
 	globals.SeedIngestionGlobals(runCtx, current)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Seed the workflow-wide Globals bag with the run-level metadata
// (name, tenant_id, kb_id, model_id, doc_id, ...) once, from the
// pipeline run inputs. Downstream components read these from ctx
// instead of relying on every node re-emitting them. The File
// component re-publishes `name` (and storage refs) as it derives
// them mid-run.
globals.SeedIngestionGlobals(runCtx, current)
// Seed the workflow-wide Globals bag with the run-level metadata
// (name, tenant_id, kb_id, doc_id, bucket, path, file) once, from the
// pipeline run inputs. Downstream components read these from ctx
// instead of relying on every node re-emitting them. The File
// component re-publishes `name` (and storage refs) as it derives
// them mid-run.
globals.SeedIngestionGlobals(runCtx, current)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/ingestion/pipeline/pipeline.go` around lines 280 - 287, Update the
comment above globals.SeedIngestionGlobals in the pipeline initialization to
remove model_id from the listed seeded metadata, keeping only keys actually
populated by GlobalMetadataKeys and preserving the explanation of run-level
globals.

@yuzhichang
yuzhichang merged commit fb42e55 into infiniflow:main Jul 10, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant