Repository navigation
feat[Go]: resuming transmission from the point of interruption during data source synchronisation - #18176
Conversation
… data source synchronisation
… data source synchronisation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (4)
📝 WalkthroughWalkthroughThe 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. ChangesSyncer scheduling and recovery
Estimated code review effort: 5 (Critical) | ~120 minutes Mergeability Score: ⚪ Minimal · up to 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
Possibly related PRs
Suggested labels: Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
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. Comment |
There was a problem hiding this comment.
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 winOrdering by
update_time DESCwith 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 oldestupdate_timeare dropped first.RecoverRunning(Lines 455-463) deliberately setsupdate_timeto 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 valueConsider not accumulating stats after the first job error.
stats.Add(jobResult.stats)runs for every result, including results received afterfirstErris set. The persisted checkpoint stops advancing at that point, sostatsin memory can exceed the counts stored incheckpointState. After a resume,statsFromCheckpointStaterestores 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 winLog the in-memory checkpoint-store fallback, and keep one fallback site.
NewTaskCoordinatorsubstitutesnewMemorySyncCheckpointStore()whencheckpointsis nil.NewSyncRunnerperforms the same substitution atinternal/syncer/sync_runner.golines 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 valueUse swagger path syntax and document the parameters.
The
@Routerpath uses the Gin syntax:connector_id. Swagger expects{connector_id}. The annotation also omits@Paramentries for the path parameter and the JSON body, so the generated documentation does not describekb_idandtask_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 valueThe shift cap is unreachable.
maxTransientTaskRetriesis 3, soattemptsnever exceeds 3 andshiftnever exceeds 2. Theshift > 5branch 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 winFilter empty task IDs for consistency with
ScheduleConnectorTasks.
scheduleConnectorTaskreturns("", nil)when a RUNNING task already exists for the connector, knowledge base, and task type (Lines 448-450).ScheduleConnectorTasksfilters that case (Lines 254-256), but this path appends the value unconditionally. The current consumerpublishDatasetSyncerTasksskips 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 tradeoffSubstring matching on error text is fragile.
The HTTP checks require the exact lowercase text
http 429orhttp 5xx. Common formats such asstatus code 429,429 Too Many Requests, orunexpected status: 503do not match. The generic termstimeoutandtemporaryalso 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 winRemove
net.Error.Temporary()without narrowing retry coverage.net.Error.Temporary()is deprecated and should be removed. The proposed replacement misses wrappednet.Errorvalues whereTemporary()is true andTimeout()is false. Define specific retryable error types or codes for this path instead of using onlyECONNRESETandECONNREFUSED.🤖 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 valuePublication 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
SCHEDULEstatus until the scheduler reconciles them throughListScheduledTasks. 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 valueAvoid the unused scheduler allocation.
NewScheduleronly allocates aSchedulerand an emptytimersmap. 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 winUse the synchronized accessor here too.
Lines 379-380 read
broker.publisheddirectly. The other updated tests now usebroker.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 valueStop 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. Addt.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 winGuard
handlerwith the same mutex, or delete the field.
PublishSyncerTaskandpublishedIDsholdb.mu, butSubscribeSyncerTaskswritesb.handlerwithout 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,-racereports 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 winAccept common boolean string forms.
syncerConfigBoolmatches"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
NewSchedulerproduces a scheduler that cannot run.
NewSchedulerleavesbrokernil.Runthen always returns the "syncer scheduler requires a NATS broker" error at Line 75. The only production caller ininternal/syncer/syncer.goimmediately replaces this value withNewNATSSchedulerwhen the message queue implementsSyncTaskBroker, 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 winConsider inverting this dependency.
The engine package now imports
ragflow/internal/syncer/connectorto type the checkpoint payload. The syncer already depends on the engine (internal/syncer/syncer.gotype-asserts the message queue toSyncCheckpointStore). This creates a two-way coupling between the transport layer and the connector domain model, and it blocksinternal/syncer/connectorfrom 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 winDecide 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 theSchedulerPollIntervalfield, the default assignment, and thescheduler_poll_intervalViper 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 tosyncer.NewSyncerand 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
📒 Files selected for processing (31)
cmd/ragflow_server.goconf/service_conf.yamldocker/service_conf.yaml.templateinternal/dao/connector.gointernal/dao/sync_task.gointernal/engine/nats/nats.gointernal/engine/nats/syncer.gointernal/engine/nats/syncer_test.gointernal/handler/connector.gointernal/handler/connector_test.gointernal/router/router.gointernal/server/config/syncer_config.gointernal/service/connector.gointernal/service/connector_syncer_test.gointernal/service/dataset/update.gointernal/service/sync_task_service.gointernal/syncer/checkpoint_store.gointernal/syncer/connector/fingerprint.gointernal/syncer/connector/gmail.gointernal/syncer/connector/gmail_test.gointernal/syncer/connector/mock/mock.gointernal/syncer/connector/models.gointernal/syncer/job_executor.gointernal/syncer/prune_runner.gointernal/syncer/scheduler.gointernal/syncer/sync_runner.gointernal/syncer/syncer.gointernal/syncer/syncer_test.gointernal/syncer/task_coordinator.gointernal/syncer/task_worker.gointernal/syncer/transient_error.go
💤 Files with no reviewable changes (2)
- conf/service_conf.yaml
- docker/service_conf.yaml.template
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
| connector *GmailConnector | ||
| users []string | ||
| userIndex int | ||
| pageToken string | ||
| batchSize int | ||
| query string | ||
| buffer []gmailBufferedDocument | ||
| resumePageToken string | ||
| resumeOffset int |
There was a problem hiding this comment.
only support Gmail's resuming transmission for now
left a comment
There was a problem hiding this comment.
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
📒 Files selected for processing (15)
internal/engine/nats/syncer.gointernal/server/config/syncer_config.gointernal/service/sync_document_id_resolver.gointernal/syncer/config.gointernal/syncer/connector/fingerprint.gointernal/syncer/connector/gmail.gointernal/syncer/connector/gmail_test.gointernal/syncer/connector/google_drive.gointernal/syncer/connector/google_drive_test.gointernal/syncer/connector/models.gointernal/syncer/scheduler.gointernal/syncer/sync_runner.gointernal/syncer/syncer.gointernal/syncer/syncer_test.gointernal/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
Summary
As title