Skip to content

Go: unify three services into one binary - #16462

Merged
JinHai-CN merged 35 commits into
infiniflow:mainfrom
JinHai-CN:fix509
Jul 2, 2026
Merged

JinHai-CN merged 35 commits into
infiniflow:mainfrom
JinHai-CN:fix509

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

Summary

Plan to start api_server, admin_server and ingestor in one binary:

  • ./ragflow_main --admin
  • ./ragflow_main --api
  • ./ragflow_main --ingestor

Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 29, 2026
@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds a new ragflow_main entrypoint that boots API, admin, and ingestor modes from CLI flags, adds shared server local state, updates config logging output, and rewires build/run scripts around the new binary.

Changes

RAGFlow Process Entrypoint

Layer / File(s) Summary
CLI argument parsing and help text
cmd/ragflow_main.go
Defines serverArgs, parseArgs for mode/flag parsing and validation, and printHelp for mode-specific usage output.
Process bootstrap and shared runtime init
cmd/ragflow_main.go, internal/server/local_variables.go, internal/server/config.go
Initializes local variables, logging, config, DB, doc engine, Redis, storage, task queue, and server variables, and changes config log delimiters.
Admin server mode
cmd/ragflow_main.go
Implements runAdmin: builds the admin service/handler/router, starts HTTP server, optionally seeds the default superuser, and shuts down gracefully.
Ingestor server mode
cmd/ragflow_main.go
Implements runIngestor: starts the ingestion worker, runs admin heartbeat, and stops on signal or shutdown channel.
API server mode and startup wiring
cmd/ragflow_main.go
Implements runAPI/startServer to build the full service/handler graph, configure agent run options and TTS dispatch, and run the HTTP server with graceful shutdown.
Build and run script wiring
build.sh, docker/.env
Switches build, clean, and run logic to the new ragflow_main binary and mode flags, and adds the commented Go deployment proxy option.

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

Sequence Diagram(s)

sequenceDiagram
  participant CLI
  participant main
  participant LocalVariables
  participant Config
  participant Redis
  participant ModeRunner

  CLI->>main: parseArgs()
  main->>LocalVariables: InitLocalVariables()
  main->>Config: load and reconfigure logging
  main->>Redis: initialize runtime-backed variables
  main->>ModeRunner: dispatch runAPI, runAdmin, or runIngestor
Loading

Possibly related PRs

Suggested labels: ☯️ refactor

Poem

I hopped through the burrow, light and spry,
One main to rule the API sky 🐇
Admin and ingestor now share the way,
With logs that gleam and configs that stay.
Thump! The build wheel spins clean and true,
And rabbit paws cheer: hop-hurray for the new!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.08% 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 matches the main change: consolidating api, admin, and ingestor into one binary.
Description check ✅ Passed The description includes the required Summary section and clearly states the unified-binary startup plan.
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.

@JinHai-CN
JinHai-CN marked this pull request as ready for review July 1, 2026 03:33
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jul 1, 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: 8

🤖 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 `@cmd/ragflow_main.go`:
- Around line 418-424: Propagate ingestor startup failures instead of only
logging inside the goroutine. In the ingestor startup path around
ingestor.Start() (and the same pattern used later in runIngestor), capture the
error and send it back to the caller or return it from the surrounding startup
flow so the process can fail fast rather than continuing heartbeat/reporting
indefinitely. Update the goroutine/startup coordination logic to use the
ingestor.Start result as a blocking error signal, and ensure runIngestor exits
immediately on startup failure.
- Around line 93-116: The CLI flag handling in the main argument parser is
reading the flag token itself instead of the following argv value, which also
makes --admin-host unsafe and leaves --name unhandled. Update the argument
parsing logic in the routine that processes these cases so --config, --port,
--admin-host, and --name each consume the next token as their value, and
validate admin host parsing before splitting into ip and port to avoid panics.
- Around line 104-116: The --admin-host flag is parsed in cmd/ragflow_main.go
via the argument handling around args.adminHost/args.adminPort, but those values
are never used when building the heartbeat/AdminServiceClient setup, so the
override has no effect. Update the API and ingestor client construction paths
that create AdminServiceClient to prefer the parsed args.adminHost and
args.adminPort when present, falling back to the default admin address
otherwise, and keep the wiring consistent in the referenced heartbeat setup call
sites.
- Around line 746-752: The heartbeat callback in NewScheduledTask is closing
over the outer err variable, which can race with shutdown logic that reuses the
same err value. Update the heartbeat reporter callback to use a local error
variable inside the anonymous function, and keep shutdown/error handling in
ragflow_main.go separate so SendHeartbeat failures only affect local status
updates. Apply the same fix to the other heartbeat-related block mentioned in
the comment so no goroutine shares err across scopes.
- Around line 366-369: The admin HTTP server setup in the http.Server
initialization for the ginEngine should be aligned with the API server by adding
read, write, and idle timeouts. Update the server configuration where srv is
created to include the same timeout fields used elsewhere so the admin server is
not left with default unlimited behavior.
- Around line 651-655: The admin runtime selector setup currently calls
redis.Get().GetClient() without guarding the redis.Get() result, which can panic
when Redis is not initialized. Update the selector creation block in the code
around adminRuntimeSelector/adminRuntimeHandler to first check that redis.Get()
is non-nil before calling GetClient, and only construct runtime.NewSelector when
a valid Redis client exists; otherwise leave adminRuntimeSelector nil and
proceed safely.

In `@internal/server/local_variables.go`:
- Around line 24-26: Make the server-name accessors nil-safe by updating
LocalVariables, InitLocalVariables, SetServerName, and GetServerName so they
work correctly even when initialization has not happened or no name has been
set. Ensure SetServerName initializes the storage if needed before assigning,
and make GetServerName handle a nil pointer by returning an empty/default value
instead of dereferencing it. Keep the zero-value behavior safe across the
server-name accessor methods.
🪄 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: 02deafc5-90e7-416d-8308-c825dcd27935

📥 Commits

Reviewing files that changed from the base of the PR and between 828c578 and 4e80ae7.

📒 Files selected for processing (3)
  • cmd/ragflow_main.go
  • internal/server/config.go
  • internal/server/local_variables.go

Comment thread cmd/ragflow_main.go Resolved
Comment thread cmd/ragflow_main.go
Comment on lines +104 to +116
case "--admin-host":
adminHost := arg
// split ip:port into ip and port
ip, portStr := strings.SplitN(adminHost, ":", 2)[0], strings.SplitN(adminHost, ":", 2)[1]
if len(portStr) == 0 {
return nil, errors.New("--admin-host must be in the form 'ip:port'")
}
port, convErr := strconv.Atoi(portStr)
if convErr != nil {
return nil, fmt.Errorf("invalid admin port: %w", convErr)
}
args.adminHost = &ip
args.adminPort = &port

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Wire the admin-host override into heartbeat setup.

args.adminHost and args.adminPort are parsed but never consumed when constructing the API or ingestor AdminServiceClient, so --admin-host is a no-op after parsing is fixed.

Also applies to: 447-455, 734-742

🤖 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 `@cmd/ragflow_main.go` around lines 104 - 116, The --admin-host flag is parsed
in cmd/ragflow_main.go via the argument handling around
args.adminHost/args.adminPort, but those values are never used when building the
heartbeat/AdminServiceClient setup, so the override has no effect. Update the
API and ingestor client construction paths that create AdminServiceClient to
prefer the parsed args.adminHost and args.adminPort when present, falling back
to the default admin address otherwise, and keep the wiring consistent in the
referenced heartbeat setup call sites.

Comment thread cmd/ragflow_main.go Resolved
Comment thread cmd/ragflow_main.go
Comment on lines +366 to +369
srv := &http.Server{
Addr: addr,
Handler: ginEngine,
}

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Add HTTP timeouts to the admin server.

The admin http.Server lacks read/write/idle timeouts, unlike the API server, leaving it exposed to slow-client resource exhaustion.

Proposed timeout alignment
 	srv := &http.Server{
-		Addr:    addr,
-		Handler: ginEngine,
+		Addr:              addr,
+		Handler:           ginEngine,
+		ReadHeaderTimeout: 10 * time.Second,
+		ReadTimeout:       60 * time.Second,
+		WriteTimeout:      120 * time.Second,
+		IdleTimeout:       120 * time.Second,
 	}
📝 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
srv := &http.Server{
Addr: addr,
Handler: ginEngine,
}
srv := &http.Server{
Addr: addr,
Handler: ginEngine,
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 60 * time.Second,
WriteTimeout: 120 * time.Second,
IdleTimeout: 120 * time.Second,
}
🤖 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 `@cmd/ragflow_main.go` around lines 366 - 369, The admin HTTP server setup in
the http.Server initialization for the ginEngine should be aligned with the API
server by adding read, write, and idle timeouts. Update the server configuration
where srv is created to include the same timeout fields used elsewhere so the
admin server is not left with default unlimited behavior.

Source: Linters/SAST tools

Comment thread cmd/ragflow_main.go
Comment on lines +418 to +424
go func() {
err := ingestor.Start()
if err != nil {
common.Error("Failed to initialize ingestor", err)
return
}
}()

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Propagate ingestor startup failures.

If ingestor.Start() fails, the goroutine only logs and exits while runIngestor continues heartbeat/reporting and waits forever.

Proposed startup error propagation
+	startErr := make(chan error, 1)
 	go func() {
-		err := ingestor.Start()
-		if err != nil {
-			common.Error("Failed to initialize ingestor", err)
+		if err := ingestor.Start(); err != nil {
+			startErr <- fmt.Errorf("failed to initialize ingestor: %w", err)
 			return
 		}
 	}()
@@
 	select {
+	case err := <-startErr:
+		return err
 	case sig := <-quit:
 		common.Info("Received signal", zap.String("signal", sig.String()))

Also applies to: 471-478

🤖 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 `@cmd/ragflow_main.go` around lines 418 - 424, Propagate ingestor startup
failures instead of only logging inside the goroutine. In the ingestor startup
path around ingestor.Start() (and the same pattern used later in runIngestor),
capture the error and send it back to the caller or return it from the
surrounding startup flow so the process can fail fast rather than continuing
heartbeat/reporting indefinitely. Update the goroutine/startup coordination
logic to use the ingestor.Start result as a blocking error signal, and ensure
runIngestor exits immediately on startup failure.

Comment thread cmd/ragflow_main.go Resolved
Comment thread cmd/ragflow_main.go
Comment on lines +746 to +752
heartbeatReporter := utility.NewScheduledTask("Heartbeat reporter", 3*time.Second, func() {
if err = service.AdminServiceClient.SendHeartbeat(); err == nil {
local.SetAdminStatus(0, "")
} else {
local.SetAdminStatus(1, err.Error())
//logger.Warn(fmt.Sprintf(err.Error()))
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Avoid sharing err with the heartbeat goroutine.

The heartbeat callback writes the outer err while shutdown later reuses it, creating a data race and possible false shutdown failure.

Proposed local error variables
 		heartbeatReporter := utility.NewScheduledTask("Heartbeat reporter", 3*time.Second, func() {
-			if err = service.AdminServiceClient.SendHeartbeat(); err == nil {
+			if heartbeatErr := service.AdminServiceClient.SendHeartbeat(); heartbeatErr == nil {
 				local.SetAdminStatus(0, "")
 			} else {
-				local.SetAdminStatus(1, err.Error())
+				local.SetAdminStatus(1, heartbeatErr.Error())
 				//logger.Warn(fmt.Sprintf(err.Error()))
 			}
 		})
@@
-	if err = srv.Shutdown(ctx); err != nil {
-		common.Fatal("Server forced to shutdown", zap.Error(err))
+	if shutdownErr := srv.Shutdown(ctx); shutdownErr != nil {
+		common.Fatal("Server forced to shutdown", zap.Error(shutdownErr))
 	}

Also applies to: 770-772

🤖 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 `@cmd/ragflow_main.go` around lines 746 - 752, The heartbeat callback in
NewScheduledTask is closing over the outer err variable, which can race with
shutdown logic that reuses the same err value. Update the heartbeat reporter
callback to use a local error variable inside the anonymous function, and keep
shutdown/error handling in ragflow_main.go separate so SendHeartbeat failures
only affect local status updates. Apply the same fix to the other
heartbeat-related block mentioned in the comment so no goroutine shares err
across scopes.

Comment on lines +24 to +26
type LocalVariables struct {
ServerName *string // Server name, can be modified at runtime
}

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Make the server-name accessors nil-safe.

SetServerName assumes InitLocalVariables already ran, and GetServerName dereferences ServerName even if no name has been set yet.

Proposed zero-value-safe storage
 type LocalVariables struct {
-	ServerName *string // Server name, can be modified at runtime
+	ServerName string // Server name, can be modified at runtime
 }
@@
 func SetServerName(serverName string) {
+	_ = InitLocalVariables()
 	localVariablesMu.Lock()
 	defer localVariablesMu.Unlock()
-	localVariables.ServerName = &serverName
+	localVariables.ServerName = serverName
 }
 
 func GetServerName() string {
+	_ = InitLocalVariables()
 	localVariablesMu.RLock()
 	defer localVariablesMu.RUnlock()
-	return *localVariables.ServerName
+	return localVariables.ServerName
 }

Also applies to: 43-52

🤖 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/server/local_variables.go` around lines 24 - 26, Make the
server-name accessors nil-safe by updating LocalVariables, InitLocalVariables,
SetServerName, and GetServerName so they work correctly even when initialization
has not happened or no name has been set. Ensure SetServerName initializes the
storage if needed before assigning, and make GetServerName handle a nil pointer
by returning an empty/default value instead of dereferencing it. Keep the
zero-value behavior safe across the server-name accessor methods.

@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

🤖 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 `@build.sh`:
- Line 529: The foreground API launch command is splitting the mode flag
incorrectly, so `ragflow_main` never sees API mode. Update the `build.sh`
command that invokes `RAGFLOW_MAIN_BINARY` to pass the single `--api` flag,
matching the dispatch logic in `cmd/ragflow_main.go` so `--run` starts the API
server correctly.
- Line 525: The EXIT/INT/TERM trap for INGESTOR_PID is overwriting the earlier
admin cleanup trap, so both background processes need to be handled together.
Update the trap logic in the build script around the existing admin and ingestor
startup flow so that the cleanup for ragflow_main --admin and the ingestor both
run on exit or interruption, using the relevant trap setup near the process PID
variables.
🪄 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: 641e34d5-adc0-42ff-bcb2-4dd9277338b9

📥 Commits

Reviewing files that changed from the base of the PR and between 4e80ae7 and 6774604.

📒 Files selected for processing (1)
  • build.sh

Comment thread build.sh
"$INGESTOR_BINARY" &
"$RAGFLOW_MAIN_BINARY" --ingestor &
INGESTOR_PID=$!
trap 'kill "$INGESTOR_PID" 2>/dev/null || true' EXIT INT TERM

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Preserve cleanup for both background processes.

The second trap replaces the admin cleanup trap from Line 516, so ragflow_main --admin can be left running after the script exits or is interrupted.

🧹 Proposed fix
-    trap 'kill "$INGESTOR_PID" 2>/dev/null || true' EXIT INT TERM
+    trap 'kill "$ADMIN_PID" "$INGESTOR_PID" 2>/dev/null || true' EXIT INT TERM
📝 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
trap 'kill "$INGESTOR_PID" 2>/dev/null || true' EXIT INT TERM
trap 'kill "$ADMIN_PID" "$INGESTOR_PID" 2>/dev/null || true' EXIT INT TERM
🤖 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 `@build.sh` at line 525, The EXIT/INT/TERM trap for INGESTOR_PID is overwriting
the earlier admin cleanup trap, so both background processes need to be handled
together. Update the trap logic in the build script around the existing admin
and ingestor startup flow so that the cleanup for ragflow_main --admin and the
ingestor both run on exit or interruption, using the relevant trap setup near
the process PID variables.

Comment thread build.sh

print_section "Starting RAGFlow server (foreground)"
"$RAGFLOW_SERVER_BINARY"
"$RAGFLOW_MAIN_BINARY" -- api

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.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Use the actual --api mode flag.

Line 529 passes -- and api as separate arguments, but cmd/ragflow_main.go only dispatches API mode on the single --api flag. This prevents ./build.sh --run from starting the foreground API server correctly.

🐛 Proposed fix
-    "$RAGFLOW_MAIN_BINARY" -- api
+    "$RAGFLOW_MAIN_BINARY" --api
📝 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
"$RAGFLOW_MAIN_BINARY" -- api
"$RAGFLOW_MAIN_BINARY" --api
🤖 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 `@build.sh` at line 529, The foreground API launch command is splitting the
mode flag incorrectly, so `ragflow_main` never sees API mode. Update the
`build.sh` command that invokes `RAGFLOW_MAIN_BINARY` to pass the single `--api`
flag, matching the dispatch logic in `cmd/ragflow_main.go` so `--run` starts the
API server correctly.

@codecov

codecov Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (c8cf0c9) to head (416d1e0).
⚠️ Report is 12 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16462   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@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

♻️ Duplicate comments (4)
cmd/ragflow_main.go (4)

194-205: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Return a failing exit code for parse errors and let --version work without a mode.

Right now parse failures return from main with exit code 0, and ragflow_main --version prints help because the mode check runs first.

Proposed fix
 	if err != nil {
-		fmt.Printf("Failed to parse arguments: %v\n", err)
-		return
+		fmt.Fprintf(os.Stderr, "Failed to parse arguments: %v\n", err)
+		os.Exit(2)
 	}
 
-	if arguments.helpFlag || arguments.mode == nil {
+	if arguments.helpFlag {
 		printHelp(arguments)
 		return
 	}
 
 	if arguments.versionFlag {
 		fmt.Printf("RAGFlow version: %s\n", utility.GetRAGFlowVersion())
 		return
 	}
+
+	if arguments.mode == nil {
+		printHelp(arguments)
+		return
+	}
🤖 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 `@cmd/ragflow_main.go` around lines 194 - 205, Update main argument handling in
ragflow_main.main so parse errors exit non-zero instead of returning normally,
and reorder the help/version logic so arguments.versionFlag is checked before
the arguments.mode nil guard; use the existing printHelp(arguments) and
utility.GetRAGFlowVersion() flow to ensure --version works without requiring a
mode.

491-496: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Keep heartbeat errors local to the heartbeat goroutine.

Both heartbeat callbacks assign to the outer err, which is later reused during shutdown. Use local error variables to avoid racing and false shutdown state.

Proposed fix
-			if err = service.AdminServiceClient.SendHeartbeat(); err == nil {
+			if heartbeatErr := service.AdminServiceClient.SendHeartbeat(); heartbeatErr == nil {
 				local.SetAdminStatus(0, "")
 			} else {
-				local.SetAdminStatus(1, err.Error())
+				local.SetAdminStatus(1, heartbeatErr.Error())
 			}
@@
-	if err = srv.Shutdown(ctx); err != nil {
-		common.Fatal("Server forced to shutdown", zap.Error(err))
+	if shutdownErr := srv.Shutdown(ctx); shutdownErr != nil {
+		common.Fatal("Server forced to shutdown", zap.Error(shutdownErr))
 	}
#!/bin/bash
# Verify no heartbeat callback assigns to the outer err variable.
rg -n -C3 'if err = service\.AdminServiceClient\.SendHeartbeat\(\)' cmd/ragflow_main.go

Also applies to: 780-805

🤖 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 `@cmd/ragflow_main.go` around lines 491 - 496, The heartbeat callbacks in
Heartbeat reporter and the other heartbeat task are assigning SendHeartbeat()
results into the outer err, which can leak into shutdown handling. Update those
scheduled-task closures to use a local error variable inside the callback and
keep service.AdminServiceClient.SendHeartbeat() errors scoped to the goroutine,
while preserving local.SetAdminStatus updates based on that local value.

129-130: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Finish wiring --admin-host after parsing it.

args.adminHost / args.adminPort are set here, but the shown API and ingestor heartbeat client setup still does not consume them, so the flag remains a no-op. Also range-check this port like --port.

🤖 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 `@cmd/ragflow_main.go` around lines 129 - 130, The --admin-host flag is being
parsed into args.adminHost/args.adminPort but never used, so wire those values
through the API and ingestor heartbeat client setup in ragflow_main.go (the main
startup/config assembly path) so the flag actually takes effect. Also apply the
same port validation used for --port when parsing --admin-port, and reject
out-of-range values before storing them in args.adminPort.

450-456: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Propagate ingestor startup failures.

If ingestor.Start() fails, the goroutine only logs and exits while runIngestor continues heartbeat/reporting and waits forever.

Proposed fix
+	startErr := make(chan error, 1)
 	go func() {
-		err := ingestor.Start()
-		if err != nil {
-			common.Error("Failed to initialize ingestor", err)
-			return
-		}
+		startErr <- ingestor.Start()
 	}()
@@
 	select {
+	case err := <-startErr:
+		if err != nil {
+			return fmt.Errorf("failed to initialize ingestor: %w", err)
+		}
+		return nil
 	case sig := <-quit:
🤖 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 `@cmd/ragflow_main.go` around lines 450 - 456, The startup failure handling in
the ingestor launch goroutine does not propagate errors, so `runIngestor` keeps
running even when `ingestor.Start()` fails. Update the goroutine around
`ingestor.Start()` to report the failure back to `runIngestor` and stop the main
flow instead of only calling `common.Error`; use the existing
`runIngestor`/`ingestor.Start` control path to exit or return the error so
heartbeat/reporting does not continue forever.
🤖 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 `@cmd/ragflow_main.go`:
- Around line 270-272: The ingestor branch in main startup is overwriting the
user-provided server name, so `--ingestor --name foo` is not honored for
`server.SetServerName` and related log naming. Update the `ingestor` case in
`ragflow_main.go` so `serverName` preserves the `--name` value when present, and
only falls back to a generated `ingestor_server_*` name when no explicit name
was supplied. Keep the behavior aligned with `NewIngestor` and the `serverName`
assignment used later in startup.
- Around line 137-138: The CLI flag parsing in the main argument switch
currently ignores unknown options, so typos like --prot can silently fall
through and start with defaults. Update the argument handling in the main
command parser around ragflow_main.go to add a default branch that rejects
unsupported flags, using the existing switch over the supported CLI arguments so
unknown inputs are reported and stop execution.

---

Duplicate comments:
In `@cmd/ragflow_main.go`:
- Around line 194-205: Update main argument handling in ragflow_main.main so
parse errors exit non-zero instead of returning normally, and reorder the
help/version logic so arguments.versionFlag is checked before the arguments.mode
nil guard; use the existing printHelp(arguments) and utility.GetRAGFlowVersion()
flow to ensure --version works without requiring a mode.
- Around line 491-496: The heartbeat callbacks in Heartbeat reporter and the
other heartbeat task are assigning SendHeartbeat() results into the outer err,
which can leak into shutdown handling. Update those scheduled-task closures to
use a local error variable inside the callback and keep
service.AdminServiceClient.SendHeartbeat() errors scoped to the goroutine, while
preserving local.SetAdminStatus updates based on that local value.
- Around line 129-130: The --admin-host flag is being parsed into
args.adminHost/args.adminPort but never used, so wire those values through the
API and ingestor heartbeat client setup in ragflow_main.go (the main
startup/config assembly path) so the flag actually takes effect. Also apply the
same port validation used for --port when parsing --admin-port, and reject
out-of-range values before storing them in args.adminPort.
- Around line 450-456: The startup failure handling in the ingestor launch
goroutine does not propagate errors, so `runIngestor` keeps running even when
`ingestor.Start()` fails. Update the goroutine around `ingestor.Start()` to
report the failure back to `runIngestor` and stop the main flow instead of only
calling `common.Error`; use the existing `runIngestor`/`ingestor.Start` control
path to exit or return the error so heartbeat/reporting does not continue
forever.
🪄 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: 17576997-6d55-41fd-9836-b24679c321b7

📥 Commits

Reviewing files that changed from the base of the PR and between 9a1e318 and f9e4ace.

📒 Files selected for processing (1)
  • cmd/ragflow_main.go

Comment thread cmd/ragflow_main.go Resolved
Comment thread cmd/ragflow_main.go Resolved
@JinHai-CN JinHai-CN removed the ci Continue Integration label Jul 1, 2026
@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 1, 2026
Signed-off-by: Jin Hai <[email protected]>
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jul 2, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft July 2, 2026 02:42
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 2, 2026 09:15
@JinHai-CN
JinHai-CN merged commit 7d64a78 into infiniflow:main Jul 2, 2026
5 of 6 checks passed
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
### Summary

Plan to start api_server, admin_server and ingestor in one binary:
- ./ragflow_main --admin
- ./ragflow_main --api
- ./ragflow_main --ingestor

---------

Signed-off-by: Jin Hai <[email protected]>
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 6, 2026
### Summary

Plan to start api_server, admin_server and ingestor in one binary:
- ./ragflow_main --admin
- ./ragflow_main --api
- ./ragflow_main --ingestor

---------

Signed-off-by: Jin Hai <[email protected]>
@coderabbitai coderabbitai Bot mentioned this pull request Jul 18, 2026
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