Skip to content

feat[Go]: resuming transmission from the point of interruption during data source synchronisation - #18176

Merged
JinHai-CN merged 7 commits into
infiniflow:mainfrom
Haruko386:main
Aug 13, 2026
Merged

JinHai-CN merged 7 commits into
infiniflow:mainfrom
Haruko386:main

Conversation

@Haruko386

Copy link
Copy Markdown
Member

Summary

As title

@Haruko386
Haruko386 marked this pull request as ready for review August 12, 2026 10:07
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Aug 12, 2026
@Haruko386 Haruko386 added the ci Continue Integration label Aug 12, 2026
@coderabbitai

coderabbitai Bot commented Aug 12, 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

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: fa5ff0ec-d4a1-42a9-b387-839d00426717

📥 Commits

Reviewing files that changed from the base of the PR and between b1c8e01 and 506dc68.

📒 Files selected for processing (4)
  • internal/syncer/connector/gmail.go
  • internal/syncer/connector/gmail_test.go
  • internal/syncer/connector/google_drive.go
  • internal/syncer/connector/google_drive_test.go
🚧 Files skipped from review as they are similar to previous changes (4)
  • internal/syncer/connector/gmail_test.go
  • internal/syncer/connector/google_drive_test.go
  • internal/syncer/connector/google_drive.go
  • internal/syncer/connector/gmail.go

📝 Walkthrough

Walkthrough

The syncer now uses push-based NATS delivery, timer-based scheduling, persistent checkpoints, transient retry handling, and failed-sync resume support. Connector updates return task IDs, and startup errors propagate through context-aware initialization.

Changes

Syncer scheduling and recovery

Layer / File(s) Summary
Task scheduling data flow
internal/dao/*, internal/service/sync_task_service.go, internal/service/dataset/update.go
Scheduling APIs return task IDs and scheduled-task metadata. Completion, recovery, duplicate prevention, and transient-failure handling now return scheduling results.
Push delivery and timer scheduling
internal/engine/nats/*, internal/syncer/scheduler.go, internal/syncer/syncer.go, internal/server/config/*, cmd/ragflow_server.go, conf/service_conf.yaml, docker/service_conf.yaml.template
NATS uses durable push subscriptions, wake-up messages, and JetStream checkpoint storage. The scheduler uses task reconciliation and one-shot timers. Startup uses StartContext and returns initialization errors.
Checkpointed connector execution
internal/syncer/checkpoint_store.go, internal/syncer/connector/*, internal/syncer/job_executor.go, internal/syncer/sync_runner.go, internal/syncer/task_coordinator.go, internal/syncer/prune_runner.go
Sync checkpoints flow through connector requests, batches, jobs, and runners. Gmail and Google Drive resume cursor-based processing. Successful runs delete checkpoints.
Transient retry processing
internal/syncer/transient_error.go, internal/syncer/task_worker.go, internal/syncer/syncer_test.go
Transient failures use retry counting and bounded exponential delays. Exhausted retries mark tasks and connectors failed.
Failed-sync resume endpoint
internal/service/connector.go, internal/dao/connector.go, internal/handler/connector.go, internal/router/router.go
Failed tasks resume after checkpoint and identity validation. Resume resets failure state and publishes a task wake-up. Rebuilds delete obsolete sync checkpoints.

Estimated code review effort: 5 (Critical) | ~120 minutes

Mergeability Score: ⚪ Minimal · up to 506dc

No actionable merge-blocking risk remains based on the supplied evidence; the PR is merge-ready after normal checks and review.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant ConnectorHandler
  participant ConnectorService
  participant ConnectorDAO
  participant NatsEngine
  Client->>ConnectorHandler: POST resume-failed-sync
  ConnectorHandler->>ConnectorService: ResumeFailedSync request
  ConnectorService->>ConnectorDAO: validate and reset failed task
  ConnectorService->>NatsEngine: publish task wake-up
  NatsEngine-->>ConnectorService: accept wake-up
  ConnectorService-->>ConnectorHandler: return success
  ConnectorHandler-->>Client: return HTTP success
Loading

Possibly related PRs

Suggested labels: go

Poem

A rabbit checks each task in line,
Saves each checkpoint, one by one.
Timers wake the work on cue,
Failed runs start anew,
While NATS carries tasks through.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description only says "As title" and does not provide the required summary or background context. Replace "As title" with a brief summary that explains the synchronization resume feature and the problem it solves.
Docstring Coverage ⚠️ Warning Docstring coverage is 61.54% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: resuming data source synchronization from the interruption point.
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.

@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: 11

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/dao/sync_task.go (1)

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

Ordering by update_time DESC with a limit can starve the oldest scheduled tasks.

The query orders scheduled tasks newest-first and truncates at limit (the service passes 4096). Tasks with the oldest update_time are dropped first. RecoverRunning (Lines 455-463) deliberately sets update_time to the Unix epoch so recovered tasks become immediately due; under this ordering those tasks sort last and are the first to fall outside the limit. Order ascending so the most overdue tasks are reconciled first.

🔧 Proposed fix
-		Order("sync_logs.update_time DESC").
+		Order("sync_logs.update_time ASC").
🤖 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/dao/sync_task.go` around lines 105 - 129, Update ListScheduledTasks
to order scheduled tasks by sync_logs.update_time ascending instead of
descending, so the oldest and most overdue tasks are selected first when Limit
truncates the result. Preserve the existing filters, limit, and task mapping
behavior.
🧹 Nitpick comments (16)
internal/syncer/sync_runner.go (1)

143-155: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Consider not accumulating stats after the first job error.

stats.Add(jobResult.stats) runs for every result, including results received after firstErr is set. The persisted checkpoint stops advancing at that point, so stats in memory can exceed the counts stored in checkpointState. After a resume, statsFromCheckpointState restores the smaller persisted values, and the later jobs are counted again if their documents are reprocessed. Counting only the results up to the first error keeps the in-memory and persisted counters aligned.

🤖 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/sync_runner.go` around lines 143 - 155, Update the
result-processing loop around firstErr so jobResult.stats is added only while no
prior job error has been recorded. Keep the existing firstErr assignment and
checkpoint persistence behavior, ensuring results received after the first error
do not increase stats.
internal/syncer/task_coordinator.go (1)

70-75: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Log the in-memory checkpoint-store fallback, and keep one fallback site.

NewTaskCoordinator substitutes newMemorySyncCheckpointStore() when checkpoints is nil. NewSyncRunner performs the same substitution at internal/syncer/sync_runner.go lines 49-51, and the coordinator always passes a non-nil store to it. The duplicate default is dead in this path. The silent fallback also hides a misconfiguration: checkpoints are then lost on restart, and resume of a failed task fails with "checkpoint not found". Emit a warning here, and keep the default in one place.

Also applies to: 99-99

🤖 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/task_coordinator.go` around lines 70 - 75, Update
NewTaskCoordinator to log a warning when checkpoints is nil before applying the
in-memory fallback, explicitly indicating that checkpoint persistence is
unavailable. Remove the duplicate newMemorySyncCheckpointStore fallback from
NewSyncRunner so the default is applied in only one location.
internal/handler/connector.go (1)

384-391: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use swagger path syntax and document the parameters.

The @Router path uses the Gin syntax :connector_id. Swagger expects {connector_id}. The annotation also omits @Param entries for the path parameter and the JSON body, so the generated documentation does not describe kb_id and task_id.

📝 Proposed annotation fix
+// `@Param` connector_id path string true "Connector ID"
+// `@Param` request body service.ResumeFailedSyncRequest true "Resume request"
 // `@Success` 200 {object} map[string]interface{}
-// `@Router` /connector/:connector_id/resume-failed-sync [post]
+// `@Router` /connector/{connector_id}/resume-failed-sync [post]
🤖 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/handler/connector.go` around lines 384 - 391, Update the Swagger
annotations for the resume-failed-sync handler around its documented route:
replace the Gin-style :connector_id segment with Swagger’s {connector_id}
syntax, and add `@Param` entries describing the connector_id path parameter plus
the JSON body fields kb_id and task_id using the appropriate request type or
schema.
internal/syncer/task_worker.go (1)

189-198: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The shift cap is unreachable.

maxTransientTaskRetries is 3, so attempts never exceeds 3 and shift never exceeds 2. The shift > 5 branch is dead. Keep the cap only if the retry limit becomes configurable; otherwise remove it.

🤖 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/task_worker.go` around lines 189 - 198, The shift cap in
transientRetryDelay is unreachable because maxTransientTaskRetries limits
attempts to three; remove the shift > 5 branch and retain the existing delay
calculation and minimum-attempt handling.
internal/dao/connector.go (1)

170-181: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Filter empty task IDs for consistency with ScheduleConnectorTasks.

scheduleConnectorTask returns ("", nil) when a RUNNING task already exists for the connector, knowledge base, and task type (Lines 448-450). ScheduleConnectorTasks filters that case (Lines 254-256), but this path appends the value unconditionally. The current consumer publishDatasetSyncerTasks skips empty IDs, so there is no user-visible defect today. Align both call sites to avoid a future publisher that does not filter.

♻️ Proposed change
 		taskID, err := scheduleConnectorTask(ctx, tx, connector.ID, kbID, connectorTaskTypeSync, true)
 		if err != nil {
 			return nil, err
 		}
-		taskIDs = append(taskIDs, taskID)
+		if taskID != "" {
+			taskIDs = append(taskIDs, taskID)
+		}
 
 		if connectorConfigBool(fullConnector.Config, "sync_deleted_files") {
 			taskID, err = scheduleConnectorTask(ctx, tx, connector.ID, kbID, connectorTaskTypePrune, false)
 			if err != nil {
 				return nil, err
 			}
-			taskIDs = append(taskIDs, taskID)
+			if taskID != "" {
+				taskIDs = append(taskIDs, taskID)
+			}
 		}
🤖 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/dao/connector.go` around lines 170 - 181, Update the task ID appends
in the connector scheduling flow around scheduleConnectorTask so empty IDs are
not added to taskIDs, matching the filtering behavior in ScheduleConnectorTasks.
Apply this to both sync and prune task scheduling while preserving error
handling and appending non-empty IDs normally.
internal/syncer/transient_error.go (2)

44-55: 🎯 Functional Correctness | 🔵 Trivial | ⚖️ Poor tradeoff

Substring matching on error text is fragile.

The HTTP checks require the exact lowercase text http 429 or http 5xx. Common formats such as status code 429, 429 Too Many Requests, or unexpected status: 503 do not match. The generic terms timeout and temporary also match unrelated messages, for example a message that contains "temporary directory". Prefer typed errors or an explicit status code from the connector layer where the HTTP response is available, and keep the string checks only as a last resort.

🤖 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/transient_error.go` around lines 44 - 55, Update the
transient-error classification logic containing message and strings.Contains
checks to prefer typed connector errors or explicit HTTP status codes when
available, marking 429 and 5xx responses as transient regardless of message
wording. Retain the existing string matching only as a last-resort fallback,
narrowing or removing broad matches such as “timeout” and “temporary” that can
classify unrelated errors.

39-42: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove net.Error.Temporary() without narrowing retry coverage. net.Error.Temporary() is deprecated and should be removed. The proposed replacement misses wrapped net.Error values where Temporary() is true and Timeout() is false. Define specific retryable error types or codes for this path instead of using only ECONNRESET and ECONNREFUSED.

🤖 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/transient_error.go` around lines 39 - 42, The transient-error
check in the relevant error-classification function must stop calling the
deprecated net.Error.Temporary() while preserving retries for wrapped transient
network failures, including non-timeout temporary errors. Replace the current
net.Error-only condition with explicit retryable error types or codes that cover
the existing temporary cases beyond ECONNRESET and ECONNREFUSED, while retaining
wrapped-error matching and timeout handling.

Source: Coding guidelines

internal/service/dataset/update.go (1)

386-407: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Publication failures are silent to the caller; confirm the reconciliation fallback.

A failed or unconfigured publisher produces only a warning. The linked connectors then stay in SCHEDULE status until the scheduler reconciles them through ListScheduledTasks. That fallback is acceptable, but it depends on the reconciliation pass running on a bounded interval. Add a metric or counter for publish failures so operators can detect a broken publisher instead of discovering delayed syncs.

🤖 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/service/dataset/update.go` around lines 386 - 407, Add an
operational metric or counter for syncer task publication failures in
publishDatasetSyncerTasks, incrementing it when the publisher is unconfigured
and whenever PublishSyncerTask returns an error. Keep the existing warning logs
and reconciliation fallback unchanged.
internal/syncer/syncer.go (1)

92-95: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Avoid the unused scheduler allocation. NewScheduler only allocates a Scheduler and an empty timers map. It does not create channels, timers, or goroutines. Select the constructor branch before creating the scheduler to avoid this unnecessary allocation.

🤖 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 92 - 95, Choose between NewScheduler
and NewNATSScheduler based on the SyncTaskBroker assertion before constructing
either scheduler, so only the selected constructor runs. Preserve the existing
broker-specific behavior and resulting scheduler assignment in the syncer setup.
internal/syncer/syncer_test.go (3)

375-381: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use the synchronized accessor here too.

Lines 379-380 read broker.published directly. The other updated tests now use broker.publishedIDs(). Keep one access pattern so the fixture stays race-safe if publication ever moves off the test goroutine.

♻️ Proposed change
-	if len(broker.published) != 1 || broker.published[0] != "task-1" {
-		t.Fatalf("published = %v", broker.published)
+	if got := broker.publishedIDs(); len(got) != 1 || got[0] != "task-1" {
+		t.Fatalf("published = %v", got)
 	}
🤖 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_test.go` around lines 375 - 381, Update the assertion
in the startup-task test to use the synchronized broker.publishedIDs() accessor
instead of reading broker.published directly, while preserving the existing
count and expected task ID checks.

416-421: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Stop the armed timer before the test ends.

The test asserts that a timer exists for task-1. The timer is armed for five minutes and stays live in the test binary after this test returns. Add t.Cleanup(scheduler.stopTimers) after constructing the scheduler so the timer goroutine does not outlive the test.

🤖 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_test.go` around lines 416 - 421, Register
t.Cleanup(scheduler.stopTimers) immediately after constructing the scheduler in
the test, so the timer armed for task-1 is stopped when the test completes.

159-175: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Guard handler with the same mutex, or delete the field.

PublishSyncerTask and publishedIDs hold b.mu, but SubscribeSyncerTasks writes b.handler without the lock. The field is also never read in the current tests. If a future test subscribes from the scheduler goroutine and reads the handler from the test goroutine, -race reports a data race.

Either remove the unused field or protect the write.

As per coding guidelines: "Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them."

♻️ Proposed change
 func (b *fakeSyncTaskBroker) SubscribeSyncerTasks(ctx context.Context, handler func(common.TaskHandle)) error {
+	b.mu.Lock()
+	defer b.mu.Unlock()
 	b.handler = handler
 	return nil
 }
🤖 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_test.go` around lines 159 - 175, Remove the unused
handler field from fakeSyncTaskBroker and stop assigning it in
SubscribeSyncerTasks, since it is never read by the tests. Keep the method’s
existing subscription behavior and interface implementation unchanged.

Source: Coding guidelines

internal/syncer/scheduler.go (2)

212-225: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Accept common boolean string forms.

syncerConfigBool matches "1", "true", and "TRUE" exactly. A stored value of "True", "yes", or " true" evaluates to false. Because this flag gates prune scheduling, a mixed-case value silently disables prune.

♻️ Proposed refactor
 	case string:
-		return typed == "1" || typed == "true" || typed == "TRUE"
+		parsed, err := strconv.ParseBool(strings.TrimSpace(typed))
+		return err == nil && parsed
🤖 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/scheduler.go` around lines 212 - 225, Update syncerConfigBool
to normalize string values before comparison, accepting common boolean forms
such as mixed-case “true”, “yes”, and surrounding whitespace while preserving
false for unsupported values. Keep direct bool handling unchanged.

55-58: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

NewScheduler produces a scheduler that cannot run.

NewScheduler leaves broker nil. Run then always returns the "syncer scheduler requires a NATS broker" error at Line 75. The only production caller in internal/syncer/syncer.go immediately replaces this value with NewNATSScheduler when the message queue implements SyncTaskBroker, so the non-broker constructor exists only as a fallback that fails at startup.

Consider making the broker a required constructor argument and deleting NewScheduler, or returning the error at construction time. This removes a dual-track path and reduces the public surface.

As per coding guidelines: "When old and new implementations coexist, converge on one implementation path unless an external contract requires compatibility" and "Reduce public surface area when a helper can be made private or internal."

🤖 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/scheduler.go` around lines 55 - 58, Remove the unusable
NewScheduler constructor and converge scheduler creation on NewNATSScheduler,
updating its production caller in syncer.go as needed. Ensure no code path can
construct a Scheduler with a nil broker, while preserving the existing
broker-backed Run behavior.

Source: Coding guidelines

internal/engine/nats/syncer.go (1)

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

Consider inverting this dependency.

The engine package now imports ragflow/internal/syncer/connector to type the checkpoint payload. The syncer already depends on the engine (internal/syncer/syncer.go type-asserts the message queue to SyncCheckpointStore). This creates a two-way coupling between the transport layer and the connector domain model, and it blocks internal/syncer/connector from ever importing the engine package.

An alternative is to keep the engine API byte-oriented (SaveSyncCheckpoint(ctx, taskID string, data []byte)) and move JSON encoding into the syncer-side store adapter. The engine then stays free of domain types.

🤖 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/engine/nats/syncer.go` at line 28, Remove the engine’s dependency on
syncerconnector by making the checkpoint API byte-oriented, including updating
SaveSyncCheckpoint to accept []byte rather than the connector payload type. Move
checkpoint JSON encoding into the syncer-side store adapter in
internal/syncer/syncer.go, preserving the existing serialized payload and
storage behavior while eliminating the circular dependency.
internal/server/config/syncer_config.go (1)

22-29: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Decide whether the scheduler poll interval survives the move to push delivery. The scheduler no longer polls the database on an interval; it subscribes to JetStream push delivery and arms one-shot timers. The interval knob was renamed instead of removed, and it is still threaded from config into the syncer constructor. One decision resolves both sites.

  • internal/server/config/syncer_config.go#L22-L29: if no runtime path consumes the value, delete the SchedulerPollInterval field, the default assignment, and the scheduler_poll_interval Viper block. If a path still consumes it, document what it now controls.
  • cmd/ragflow_server.go#L628-L633: if the field is removed, drop the second argument to syncer.NewSyncer and update the constructor signature accordingly.

As per coding guidelines: "Treat legacy code as a liability rather than a compatibility target; prefer deletion over shims, deprecated branches, wrapper APIs, and dual-track migrations."

🤖 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/config/syncer_config.go` around lines 22 - 29, Remove the
obsolete scheduler poll interval because push delivery now uses one-shot timers:
in internal/server/config/syncer_config.go:22-29 delete SchedulerPollInterval,
its default assignment, and the scheduler_poll_interval Viper configuration; in
cmd/ragflow_server.go:628-633 remove the corresponding syncer.NewSyncer argument
and update the constructor signature and related call sites.

Source: Coding guidelines

🤖 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/dao/connector.go`:
- Around line 111-119: Update the knowledgebase lookup inside the transaction
callback in LinkDatasetConnectors to use the provided tx handle instead of
db.WithContext(ctx). Keep the existing context, selected field, filters, and
error handling unchanged so the read participates in the same transaction as
LinkDatasetConnectorsTx.

In `@internal/dao/sync_task.go`:
- Around line 288-298: The missing RUNNING-row branch in the sync task lookup
currently returns a success-like result that triggers a retry; update the
surrounding function in internal/dao/sync_task.go to return a distinguishable
failure result when gorm.ErrRecordNotFound occurs, such as setting its failed
result or returning the established sentinel error. Ensure the worker can
recognize this outcome and skip publishing the delayed wake-up while preserving
normal error propagation for other query failures.

In `@internal/engine/nats/syncer.go`:
- Around line 96-110: Restrict the replacement branch around
shouldRecreateSyncerConsumer to the specific typed JetStream
consumer-configuration mismatch, rather than free-form text matches or the
generic JSErrCodeConsumerCreate alone. Before DeleteConsumer, compare the
existing durable consumer configuration or validate the narrowly intended API
error, then log the original error and whether deletion is proceeding; preserve
deletion only for that confirmed condition.
- Around line 119-142: Update NatsEngine.initSyncCheckpointsLocked to inspect
the existing syncCheckpointBucket configuration when CreateOrUpdateKeyValue
fails due to an incompatible Storage type. Return a targeted migration error
identifying the configured storage and required FileStorage, and do not delete
or overwrite the existing checkpoint bucket or its data.

In `@internal/service/connector.go`:
- Around line 1035-1044: The rebuild currently returns CodeServerError when
checkpoint cleanup fails, preventing committed task IDs from being published. In
the rebuild flow around connectorDAO.RebuildConnector, treat
deleteSyncCheckpoints errors as best-effort: log the failure and continue to
publishSyncerTasks(taskIDs), preserving successful rebuild completion.

In `@internal/syncer/checkpoint_store.go`:
- Around line 41-61: Update memorySyncCheckpointStore.SaveSyncCheckpoint and
LoadSyncCheckpoint to deep-copy all nested pointer fields in
SyncCheckpointState, including WindowStart, Checkpoint, and
Checkpoint.UpdatedAt, so caller mutations cannot alter stored or returned state.
Add a test that mutates the original state after SaveSyncCheckpoint and verifies
a subsequent load remains unchanged.

In `@internal/syncer/connector/gmail.go`:
- Line 618: Update the fingerprint assignment in the Gmail sync flow around
contentFingerprint so changes to external_user_emails are detected alongside
content changes. Incorporate the permission metadata produced by getUserEmails
into change detection, or ensure that metadata is refreshed independently for
previously skipped documents.

In `@internal/syncer/scheduler.go`:
- Around line 195-210: Update Scheduler.taskDelay and its ScheduleTaskAfter
caller so disabled prune tasks return and propagate a distinct “do not schedule”
signal rather than a zero delay; preserve zero-delay behavior for genuinely due
tasks, while ensuring publishTask is not called when sync_deleted_files is
disabled.

In `@internal/syncer/syncer_test.go`:
- Around line 502-506: Rename TestNATSSchedulerBuffersFetchedTasks to reflect
pushed-task delivery, such as TestNATSSchedulerBuffersPushedTasks, and update
its comment to describe enqueueHandle buffering pushed handles rather than
fetching tasks.

In `@internal/syncer/task_worker.go`:
- Around line 139-152: Update the HandleTransientFailure call in the
transient-error branch of the worker to pass the original err directly instead
of wrapping it with “sync task transient failure”. Keep the DAO’s existing
terminal message formatting in HandleTransientFailure responsible for the
persisted error message.
- Around line 133-138: Update the cancellation branch in the task worker to use
only one retry mechanism: after RescheduleClaimed succeeds, ACK the envelope and
retain scheduleRetry, or remove rescheduling and use a delayed NACK instead. Do
not leave nackEnvelope alongside scheduleRetry, and preserve the existing
cancellation handling and retry delay.

---

Outside diff comments:
In `@internal/dao/sync_task.go`:
- Around line 105-129: Update ListScheduledTasks to order scheduled tasks by
sync_logs.update_time ascending instead of descending, so the oldest and most
overdue tasks are selected first when Limit truncates the result. Preserve the
existing filters, limit, and task mapping behavior.

---

Nitpick comments:
In `@internal/dao/connector.go`:
- Around line 170-181: Update the task ID appends in the connector scheduling
flow around scheduleConnectorTask so empty IDs are not added to taskIDs,
matching the filtering behavior in ScheduleConnectorTasks. Apply this to both
sync and prune task scheduling while preserving error handling and appending
non-empty IDs normally.

In `@internal/engine/nats/syncer.go`:
- Line 28: Remove the engine’s dependency on syncerconnector by making the
checkpoint API byte-oriented, including updating SaveSyncCheckpoint to accept
[]byte rather than the connector payload type. Move checkpoint JSON encoding
into the syncer-side store adapter in internal/syncer/syncer.go, preserving the
existing serialized payload and storage behavior while eliminating the circular
dependency.

In `@internal/handler/connector.go`:
- Around line 384-391: Update the Swagger annotations for the resume-failed-sync
handler around its documented route: replace the Gin-style :connector_id segment
with Swagger’s {connector_id} syntax, and add `@Param` entries describing the
connector_id path parameter plus the JSON body fields kb_id and task_id using
the appropriate request type or schema.

In `@internal/server/config/syncer_config.go`:
- Around line 22-29: Remove the obsolete scheduler poll interval because push
delivery now uses one-shot timers: in
internal/server/config/syncer_config.go:22-29 delete SchedulerPollInterval, its
default assignment, and the scheduler_poll_interval Viper configuration; in
cmd/ragflow_server.go:628-633 remove the corresponding syncer.NewSyncer argument
and update the constructor signature and related call sites.

In `@internal/service/dataset/update.go`:
- Around line 386-407: Add an operational metric or counter for syncer task
publication failures in publishDatasetSyncerTasks, incrementing it when the
publisher is unconfigured and whenever PublishSyncerTask returns an error. Keep
the existing warning logs and reconciliation fallback unchanged.

In `@internal/syncer/scheduler.go`:
- Around line 212-225: Update syncerConfigBool to normalize string values before
comparison, accepting common boolean forms such as mixed-case “true”, “yes”, and
surrounding whitespace while preserving false for unsupported values. Keep
direct bool handling unchanged.
- Around line 55-58: Remove the unusable NewScheduler constructor and converge
scheduler creation on NewNATSScheduler, updating its production caller in
syncer.go as needed. Ensure no code path can construct a Scheduler with a nil
broker, while preserving the existing broker-backed Run behavior.

In `@internal/syncer/sync_runner.go`:
- Around line 143-155: Update the result-processing loop around firstErr so
jobResult.stats is added only while no prior job error has been recorded. Keep
the existing firstErr assignment and checkpoint persistence behavior, ensuring
results received after the first error do not increase stats.

In `@internal/syncer/syncer_test.go`:
- Around line 375-381: Update the assertion in the startup-task test to use the
synchronized broker.publishedIDs() accessor instead of reading broker.published
directly, while preserving the existing count and expected task ID checks.
- Around line 416-421: Register t.Cleanup(scheduler.stopTimers) immediately
after constructing the scheduler in the test, so the timer armed for task-1 is
stopped when the test completes.
- Around line 159-175: Remove the unused handler field from fakeSyncTaskBroker
and stop assigning it in SubscribeSyncerTasks, since it is never read by the
tests. Keep the method’s existing subscription behavior and interface
implementation unchanged.

In `@internal/syncer/syncer.go`:
- Around line 92-95: Choose between NewScheduler and NewNATSScheduler based on
the SyncTaskBroker assertion before constructing either scheduler, so only the
selected constructor runs. Preserve the existing broker-specific behavior and
resulting scheduler assignment in the syncer setup.

In `@internal/syncer/task_coordinator.go`:
- Around line 70-75: Update NewTaskCoordinator to log a warning when checkpoints
is nil before applying the in-memory fallback, explicitly indicating that
checkpoint persistence is unavailable. Remove the duplicate
newMemorySyncCheckpointStore fallback from NewSyncRunner so the default is
applied in only one location.

In `@internal/syncer/task_worker.go`:
- Around line 189-198: The shift cap in transientRetryDelay is unreachable
because maxTransientTaskRetries limits attempts to three; remove the shift > 5
branch and retain the existing delay calculation and minimum-attempt handling.

In `@internal/syncer/transient_error.go`:
- Around line 44-55: Update the transient-error classification logic containing
message and strings.Contains checks to prefer typed connector errors or explicit
HTTP status codes when available, marking 429 and 5xx responses as transient
regardless of message wording. Retain the existing string matching only as a
last-resort fallback, narrowing or removing broad matches such as “timeout” and
“temporary” that can classify unrelated errors.
- Around line 39-42: The transient-error check in the relevant
error-classification function must stop calling the deprecated
net.Error.Temporary() while preserving retries for wrapped transient network
failures, including non-timeout temporary errors. Replace the current
net.Error-only condition with explicit retryable error types or codes that cover
the existing temporary cases beyond ECONNRESET and ECONNREFUSED, while retaining
wrapped-error matching and timeout handling.
🪄 Autofix

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 Plus

Run ID: 424e9d8d-a55b-40f7-a917-b32b39985844

📥 Commits

Reviewing files that changed from the base of the PR and between 7646afa and 6aaa1e4.

📒 Files selected for processing (31)
  • cmd/ragflow_server.go
  • conf/service_conf.yaml
  • docker/service_conf.yaml.template
  • internal/dao/connector.go
  • internal/dao/sync_task.go
  • internal/engine/nats/nats.go
  • internal/engine/nats/syncer.go
  • internal/engine/nats/syncer_test.go
  • internal/handler/connector.go
  • internal/handler/connector_test.go
  • internal/router/router.go
  • internal/server/config/syncer_config.go
  • internal/service/connector.go
  • internal/service/connector_syncer_test.go
  • internal/service/dataset/update.go
  • internal/service/sync_task_service.go
  • internal/syncer/checkpoint_store.go
  • internal/syncer/connector/fingerprint.go
  • internal/syncer/connector/gmail.go
  • internal/syncer/connector/gmail_test.go
  • internal/syncer/connector/mock/mock.go
  • internal/syncer/connector/models.go
  • internal/syncer/job_executor.go
  • internal/syncer/prune_runner.go
  • internal/syncer/scheduler.go
  • internal/syncer/sync_runner.go
  • internal/syncer/syncer.go
  • internal/syncer/syncer_test.go
  • internal/syncer/task_coordinator.go
  • internal/syncer/task_worker.go
  • internal/syncer/transient_error.go
💤 Files with no reviewable changes (2)
  • conf/service_conf.yaml
  • docker/service_conf.yaml.template

Comment thread internal/dao/connector.go Resolved
Comment thread internal/dao/sync_task.go Resolved
Comment thread internal/engine/nats/syncer.go Resolved
Comment thread internal/engine/nats/syncer.go Resolved
Comment thread internal/service/connector.go Resolved
Comment thread internal/syncer/connector/gmail.go Resolved
Comment thread internal/syncer/scheduler.go Resolved
Comment thread internal/syncer/syncer_test.go Resolved
Comment thread internal/syncer/task_worker.go Resolved
Comment thread internal/syncer/task_worker.go Resolved
@codecov

codecov Bot commented Aug 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.65%. Comparing base (eada2f6) to head (bf4c7ac).
⚠️ Report is 43 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #18176   +/-   ##
=======================================
  Coverage   90.65%   90.65%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          650      650           
  Misses         39       39           
  Partials       28       28           

☔ 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.

Comment on lines +293 to +301
connector *GmailConnector
users []string
userIndex int
pageToken string
batchSize int
query string
buffer []gmailBufferedDocument
resumePageToken string
resumeOffset int

ghost Aug 12, 2026

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

only support Gmail's resuming transmission for now

ghost 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: 1

🤖 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`:
- Line 52: Update the NewSyncer call in ragflow_server.go to pass only the
taskWorkerCount argument, matching the single-parameter NewSyncer signature and
resolving the compile error.
🪄 Autofix

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 Plus

Run ID: 39e357ec-1e43-4c4f-a07d-d96915f3ceae

📥 Commits

Reviewing files that changed from the base of the PR and between d601906 and 73652e6.

📒 Files selected for processing (15)
  • internal/engine/nats/syncer.go
  • internal/server/config/syncer_config.go
  • internal/service/sync_document_id_resolver.go
  • internal/syncer/config.go
  • internal/syncer/connector/fingerprint.go
  • internal/syncer/connector/gmail.go
  • internal/syncer/connector/gmail_test.go
  • internal/syncer/connector/google_drive.go
  • internal/syncer/connector/google_drive_test.go
  • internal/syncer/connector/models.go
  • internal/syncer/scheduler.go
  • internal/syncer/sync_runner.go
  • internal/syncer/syncer.go
  • internal/syncer/syncer_test.go
  • internal/syncer/task_worker.go
💤 Files with no reviewable changes (1)
  • internal/syncer/config.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • internal/syncer/task_worker.go
  • internal/syncer/sync_runner.go
  • internal/syncer/connector/gmail.go
  • internal/syncer/scheduler.go
  • internal/syncer/syncer_test.go
  • internal/engine/nats/syncer.go

Comment thread internal/syncer/syncer.go Resolved
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:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants