Skip to content

Go: file syncer service framework - #16579

Merged
JinHai-CN merged 4 commits into
infiniflow:mainfrom
JinHai-CN:fix514
Jul 3, 2026
Merged

JinHai-CN merged 4 commits into
infiniflow:mainfrom
JinHai-CN:fix514

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented Jul 3, 2026 •

Copy link
Copy Markdown
Member

Summary

./ragflow_main --syncer to start file syncer

config yaml file has following config

file_syncer:
  max_concurrent_syncs: 4 # concurrent file sync threads
  sync_interval: 3 # check interval

@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds a new syncer server mode, including its runtime, configuration, CLI wiring, and server type constant. It also removes one router route and updates a handler variable used in startServer.

Changes

Syncer Server Mode

Layer / File(s) Summary
Syncer runtime
internal/syncer/syncer.go
Adds the Syncer lifecycle, worker polling loop, task execution helpers, and DB updates that mark sync logs and connectors done.
Configuration and server type support
internal/server/config.go, conf/service_conf.yaml, docker/service_conf.yaml.template, internal/common/status_message.go
Adds file_syncer config fields, YAML settings, and the ServerTypeFileSyncer constant.
CLI and server startup wiring
cmd/ragflow_main.go, internal/router/router.go
Adds --syncer parsing, help text, startup naming, runSyncer, heartbeat/shutdown handling, the router handler variable fix, and removal of the beta-auth chatbot info route.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Main
  participant runSyncer
  participant Syncer
  participant AdminServer

  Main->>runSyncer: runSyncer(arguments)
  runSyncer->>Syncer: NewSyncer(...) + Start()
  runSyncer->>AdminServer: heartbeat updates
  alt OS signal
    runSyncer->>Syncer: Stop()
  else ShutdownCh closes
    runSyncer->>Syncer: Stop()
  end
Loading

Possibly related PRs

  • infiniflow/ragflow#16462: Both PRs extend cmd/ragflow_main.go’s mode-based startup flow with additional server modes.
  • infiniflow/ragflow#16529: Both PRs change internal/router/router.go route registration inside the /api/v1 beta-auth setup.

Suggested reviewers: yuzhichang

Poem

A rabbit hops with syncer cheer,
Polling files both far and near.
Heartbeats ping, then hush the night,
Tasks go done and routes stay tight.
🐇✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Title check ✅ Passed The title clearly matches the main change: adding a Go file syncer service framework.
Description check ✅ Passed The description includes the required Summary section and explains the new syncer mode and config settings.

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 3, 2026 02:48
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jul 3, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft July 3, 2026 02:48
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 3, 2026 02:49
@JinHai-CN JinHai-CN added the ci Continue Integration label Jul 3, 2026
Signed-off-by: Jin Hai <[email protected]>

@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)
cmd/ragflow_main.go (2)

149-165: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Generic help text omits the new --syncer mode.

The no-mode printHelp branch lists --api|--admin|--ingestor and documents each mode individually, but doesn't mention --syncer anywhere, even though it's a valid mode now supported by parseArgs.

📝 Proposed fix
-		fmt.Fprintf(os.Stderr, "Usage: %s --api|--admin|--ingestor [OPTIONS]\n\n", os.Args[0])
+		fmt.Fprintf(os.Stderr, "Usage: %s --api|--admin|--ingestor|--syncer [OPTIONS]\n\n", os.Args[0])
 		fmt.Fprintf(os.Stderr, "RAGFlow Server - Open-source RAG engine based on deep document understanding\n\n")
 		fmt.Fprintf(os.Stderr, "Mode selection (default: --api):\n")
 		fmt.Fprintf(os.Stderr, "  --api          \tRun as API server\n")
 		fmt.Fprintf(os.Stderr, "  --admin        \tRun as admin server\n")
-		fmt.Fprintf(os.Stderr, "  --ingestor     \tRun as ingestion worker\n\n")
+		fmt.Fprintf(os.Stderr, "  --ingestor     \tRun as ingestion worker\n")
+		fmt.Fprintf(os.Stderr, "  --syncer       \tRun as file syncer service\n\n")
 		fmt.Fprintf(os.Stderr, "Common options:\n")
 		fmt.Fprintf(os.Stderr, "  --config string\tPath to configuration file\n")
 		fmt.Fprintf(os.Stderr, "  -v, --version  \tPrint version information and exit\n")
 		fmt.Fprintf(os.Stderr, "  --debug        \tEnable debug-level logging\n")
 		fmt.Fprintf(os.Stderr, "  -h, --help     \tShow this help message and exit\n\n")
 		fmt.Fprintf(os.Stderr, "Run '%s --api --help' for API server options.\n", os.Args[0])
 		fmt.Fprintf(os.Stderr, "Run '%s --admin --help' for admin server options.\n", os.Args[0])
 		fmt.Fprintf(os.Stderr, "Run '%s --ingestor --help' for ingester options.\n", os.Args[0])
+		fmt.Fprintf(os.Stderr, "Run '%s --syncer --help' for syncer options.\n", os.Args[0])
🤖 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 149 - 165, Update the no-mode branch in
printHelp so the usage line and mode list include the new --syncer mode
alongside --api, --admin, and --ingestor, and add a matching short description
for it. Also add the corresponding “Run ... --syncer --help” hint near the other
mode-specific help lines so the help text stays aligned with parseArgs and the
supported serverArgs.mode values.

545-618: 🩺 Stability & Availability | 🔵 Trivial | ⚖️ Poor tradeoff

runSyncer graceful-shutdown context is created but never used.

context.WithTimeout(...) at Line 610 produces a context that is discarded (_); fileSyncer.Stop() (Line 613) doesn't accept or honor any context/deadline and simply blocks on workerWg.Wait(). If a worker hangs (e.g., during a long DB call once pollAndExecute is implemented), shutdown can block indefinitely despite the apparent 30s timeout. This mirrors the existing runIngestor pattern (Lines 534-538), so it's a pre-existing issue rather than new, but worth addressing here since Syncer.Stop() is new code.

🤖 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 545 - 618, `runSyncer` creates a timeout
context but never uses it, so shutdown can still block forever in
`fileSyncer.Stop()`. Update `runSyncer` and the `syncer.Syncer.Stop` path to
accept and honor the context/deadline instead of discarding it, and use that
context when waiting for workers so shutdown can fail fast after 30 seconds.
Keep the fix aligned with the `runSyncer`/`fileSyncer.Stop` flow and the
existing timeout pattern used elsewhere.
internal/syncer/syncer.go (1)

104-128: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

pollAndExecute is a no-op stub — executeSyncTask/executePruneTask are currently unreachable.

pollAndExecute only logs and never queries sync_logs/dispatches tasks, so executeSyncTask and executePruneTask are dead code for now. If this is an intentional first-pass "framework" scaffold (per PR description), consider adding a // TODO in pollAndExecute itself for clarity, matching the TODOs already present in executeSyncTask/executePruneTask.

Also, for the future real implementation: since every worker runs its own ticker at the same pollInterval and polls independently (Line 98-100), you'll need a concurrency-safe task-claiming mechanism (e.g., SELECT ... FOR UPDATE SKIP LOCKED or an atomic status transition) to avoid multiple workers picking up and double-processing the same due task.

🤖 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/syncer/syncer.go` around lines 104 - 128, `pollAndExecute` is
currently just a logging stub, so `executeSyncTask` and `executePruneTask` never
get reached. Update `Syncer.pollAndExecute` to either clearly mark it as an
intentional TODO scaffold or implement the task lookup/dispatch flow against
`sync_logs` so due tasks are actually picked and routed to `executeSyncTask` or
`executePruneTask`. Keep the existing task handlers (`executeSyncTask`,
`executePruneTask`) as the execution paths, and for the eventual real polling
logic make task claiming concurrency-safe so multiple workers don’t process the
same task twice.
🤖 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/syncer/syncer.go`:
- Around line 47-58: `NewSyncer` currently accepts any `pollInterval`, but
`workerLoop` later passes it to `time.NewTicker`, which panics on zero or
negative values. Add validation in `NewSyncer` (or before `workerLoop` creates
the ticker) to reject or normalize non-positive intervals, and make sure
`Start`/`workerLoop` never launches a ticker with an invalid duration. Use the
existing `NewSyncer` and `workerLoop` symbols to keep the fix localized and
prevent the goroutine panic path.
- Around line 131-143: The markTaskDone method is ignoring database update
failures, which can leave SyncLogs and Connector states inconsistent. Update the
two dao.GetDB().Model(...).Updates(...) calls to capture and check the returned
gorm result, and handle result.Error (and optionally RowsAffected) with
appropriate logging or error propagation. Use the markTaskDone method plus the
SyncLogs and Connector updates to locate the change.

---

Nitpick comments:
In `@cmd/ragflow_main.go`:
- Around line 149-165: Update the no-mode branch in printHelp so the usage line
and mode list include the new --syncer mode alongside --api, --admin, and
--ingestor, and add a matching short description for it. Also add the
corresponding “Run ... --syncer --help” hint near the other mode-specific help
lines so the help text stays aligned with parseArgs and the supported
serverArgs.mode values.
- Around line 545-618: `runSyncer` creates a timeout context but never uses it,
so shutdown can still block forever in `fileSyncer.Stop()`. Update `runSyncer`
and the `syncer.Syncer.Stop` path to accept and honor the context/deadline
instead of discarding it, and use that context when waiting for workers so
shutdown can fail fast after 30 seconds. Keep the fix aligned with the
`runSyncer`/`fileSyncer.Stop` flow and the existing timeout pattern used
elsewhere.

In `@internal/syncer/syncer.go`:
- Around line 104-128: `pollAndExecute` is currently just a logging stub, so
`executeSyncTask` and `executePruneTask` never get reached. Update
`Syncer.pollAndExecute` to either clearly mark it as an intentional TODO
scaffold or implement the task lookup/dispatch flow against `sync_logs` so due
tasks are actually picked and routed to `executeSyncTask` or `executePruneTask`.
Keep the existing task handlers (`executeSyncTask`, `executePruneTask`) as the
execution paths, and for the eventual real polling logic make task claiming
concurrency-safe so multiple workers don’t process the same task twice.
🪄 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: 7e367bf4-7d66-47a5-96fa-c785a091e467

📥 Commits

Reviewing files that changed from the base of the PR and between 62f94cd and 4425aee.

📒 Files selected for processing (6)
  • cmd/ragflow_main.go
  • conf/service_conf.yaml
  • docker/service_conf.yaml.template
  • internal/common/status_message.go
  • internal/server/config.go
  • internal/syncer/syncer.go

Comment thread internal/syncer/syncer.go
Comment on lines +47 to +58
// NewSyncer creates a syncer with the given concurrency and poll interval.
func NewSyncer(maxConcurrency int, pollInterval time.Duration) *Syncer {
ctx, cancel := context.WithCancel(context.Background())
return &Syncer{
id: common.GenerateUUID(),
maxConcurrency: maxConcurrency,
pollInterval: pollInterval,
ctx: ctx,
cancel: cancel,
ShutdownCh: make(chan struct{}),
}
}

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 | 🔴 Critical | ⚡ Quick win

Panic risk: time.NewTicker with non-positive interval.

NewSyncer stores pollInterval without validation, and workerLoop calls time.NewTicker(s.pollInterval) at Line 90. If config.FileSyncer.SyncInterval is 0 (e.g., unset/misconfigured YAML, or overridden to 0), time.NewTicker panics. This happens inside a bare goroutine (go s.workerLoop(i), spawned from Start()), so an unrecovered panic will crash the entire process.

🛡️ Proposed fix
 func NewSyncer(maxConcurrency int, pollInterval time.Duration) *Syncer {
 	ctx, cancel := context.WithCancel(context.Background())
+	if maxConcurrency <= 0 {
+		maxConcurrency = 1
+	}
+	if pollInterval <= 0 {
+		pollInterval = time.Second
+	}
 	return &Syncer{
 		id:             common.GenerateUUID(),

Also applies to: 90-91

🤖 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/syncer/syncer.go` around lines 47 - 58, `NewSyncer` currently
accepts any `pollInterval`, but `workerLoop` later passes it to
`time.NewTicker`, which panics on zero or negative values. Add validation in
`NewSyncer` (or before `workerLoop` creates the ticker) to reject or normalize
non-positive intervals, and make sure `Start`/`workerLoop` never launches a
ticker with an invalid duration. Use the existing `NewSyncer` and `workerLoop`
symbols to keep the fix localized and prevent the goroutine panic path.

Comment thread internal/syncer/syncer.go
Comment on lines +131 to +143
func (s *Syncer) markTaskDone(taskID, connectorID string) {
db := dao.GetDB()
now := time.Now().Local()

db.Model(&entity.SyncLogs{}).Where("id = ?", taskID).Updates(map[string]interface{}{
"status": string(entity.TaskStatusDone),
"update_time": now,
})
db.Model(&entity.Connector{}).Where("id = ?", connectorID).Updates(map[string]interface{}{
"status": string(entity.TaskStatusDone),
"update_time": now,
})
}

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

Unchecked DB update errors in markTaskDone.

Both db.Model(...).Updates(...) calls (Lines 135-142) ignore the returned *gorm.DB (and its .Error/.RowsAffected). A failed update (e.g., DB connectivity issue) will silently leave a task/connector stuck in an inconsistent status with no log or retry.

🛡️ Proposed fix
-	db.Model(&entity.SyncLogs{}).Where("id = ?", taskID).Updates(map[string]interface{}{
+	if err := db.Model(&entity.SyncLogs{}).Where("id = ?", taskID).Updates(map[string]interface{}{
 		"status":      string(entity.TaskStatusDone),
 		"update_time": now,
-	})
-	db.Model(&entity.Connector{}).Where("id = ?", connectorID).Updates(map[string]interface{}{
+	}).Error; err != nil {
+		common.Error("Failed to update sync task status", err)
+	}
+	if err := db.Model(&entity.Connector{}).Where("id = ?", connectorID).Updates(map[string]interface{}{
 		"status":      string(entity.TaskStatusDone),
 		"update_time": now,
-	})
+	}).Error; err != nil {
+		common.Error("Failed to update connector status", err)
+	}
📝 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
func (s *Syncer) markTaskDone(taskID, connectorID string) {
db := dao.GetDB()
now := time.Now().Local()
db.Model(&entity.SyncLogs{}).Where("id = ?", taskID).Updates(map[string]interface{}{
"status": string(entity.TaskStatusDone),
"update_time": now,
})
db.Model(&entity.Connector{}).Where("id = ?", connectorID).Updates(map[string]interface{}{
"status": string(entity.TaskStatusDone),
"update_time": now,
})
}
func (s *Syncer) markTaskDone(taskID, connectorID string) {
db := dao.GetDB()
now := time.Now().Local()
if err := db.Model(&entity.SyncLogs{}).Where("id = ?", taskID).Updates(map[string]interface{}{
"status": string(entity.TaskStatusDone),
"update_time": now,
}).Error; err != nil {
common.Error("Failed to update sync task status", err)
}
if err := db.Model(&entity.Connector{}).Where("id = ?", connectorID).Updates(map[string]interface{}{
"status": string(entity.TaskStatusDone),
"update_time": now,
}).Error; err != nil {
common.Error("Failed to update connector status", err)
}
}
🤖 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/syncer/syncer.go` around lines 131 - 143, The markTaskDone method is
ignoring database update failures, which can leave SyncLogs and Connector states
inconsistent. Update the two dao.GetDB().Model(...).Updates(...) calls to
capture and check the returned gorm result, and handle result.Error (and
optionally RowsAffected) with appropriate logging or error propagation. Use the
markTaskDone method plus the SyncLogs and Connector updates to locate the
change.

@JinHai-CN
JinHai-CN merged commit 1aa8abe into infiniflow:main Jul 3, 2026
5 of 6 checks passed
xugangqiang pushed a commit to xugangqiang/ragflow that referenced this pull request Jul 3, 2026
### Summary

./ragflow_main --syncer to start file syncer


config yaml file has following config
```
file_syncer:
  max_concurrent_syncs: 4 # concurrent file sync threads
  sync_interval: 3 # check interval

```

---------

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

./ragflow_main --syncer to start file syncer


config yaml file has following config
```
file_syncer:
  max_concurrent_syncs: 4 # concurrent file sync threads
  sync_interval: 3 # check interval

```

---------

Signed-off-by: Jin Hai <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant