Skip to content

feat[Go]: complete the base for data Syncer - #17890

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

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

Conversation

@Haruko386

Copy link
Copy Markdown
Member

Summary

As title

@Haruko386 Haruko386 added 💞 feature Feature request, pull request that fullfill a new feature. go Pull requests that update go code labels Aug 5, 2026
@coderabbitai

coderabbitai Bot commented Aug 6, 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: 0f29fd99-2224-4487-a84a-b41d71d87fb5

📥 Commits

Reviewing files that changed from the base of the PR and between 00e8477 and f357d3b.

📒 Files selected for processing (2)
  • internal/service/document/document_test.go
  • internal/service/document/sync_document.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/service/document/sync_document.go

📝 Walkthrough

Walkthrough

Added a complete Go syncer architecture with task scheduling, connector sessions, RSS and GitHub ingestion, document upserts, ID resolution, pruning, retries, concurrency control, and task recovery.

Changes

Syncer architecture

Layer / File(s) Summary
Connector contracts and source integrations
internal/syncer/config.go, internal/syncer/connector/*
Defines normalized settings, connector models, session interfaces, registry lookup, mock sessions, RSS parsing, GitHub API ingestion, and connector tests.
Task and prune persistence
internal/dao/sync_task.go, internal/dao/sync_prune_snapshot.go, internal/service/sync_task_service.go
Adds GORM task lifecycle management, due-task discovery, claiming, completion, recovery, scheduling, statistics, and prune snapshots.
Document synchronization and pruning
internal/service/document/*, internal/service/sync_document_id_resolver.go, internal/service/sync_document_sink.go, internal/service/sync_prune_service.go
Adds ID resolution, retry classification, document upserts, file-manager updates, metadata handling, staged-storage cleanup, and stale-document deletion.
Scheduling and task execution
internal/syncer/scheduler.go, internal/syncer/task_worker.go, internal/syncer/task_coordinator.go, internal/syncer/sync_runner.go, internal/syncer/prune_runner.go, internal/syncer/syncer.go, internal/utility/upload.go
Replaces the placeholder worker loop with coordinated scheduling, connector locking, bounded concurrency, retries, sync and prune runners, configurable remote fetch timeouts, graceful shutdown, and recovery.
Integration validation
internal/syncer/syncer_test.go, internal/syncer/connector/*_test.go, internal/service/document/document_test.go
Adds coverage for scheduling, concurrency, batching, ID compatibility, document skipping, task failures, pruning, connector output, EOF behavior, and staged-blob cleanup.

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

Possibly related PRs

  • infiniflow/ragflow#17695: Implements overlapping Go syncer execution, task lifecycle, document synchronization, and RSS functionality.

Suggested reviewers: jinhai-cn

Poem

A rabbit checks each task in line,
While feeds and issues neatly align.
Snapshots guard the prune-time run,
Hashes mark each document done.
Workers retry, then close the door—
The syncer hops through tasks once more.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description includes the required Summary heading but does not explain the purpose, background, or scope of the extensive changes. Replace "As title" with a concise summary of the Syncer architecture, task execution, connectors, document synchronization, pruning, and testing changes.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately identifies the main change as completing the base Go data Syncer implementation.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.

@Haruko386
Haruko386 marked this pull request as ready for review August 6, 2026 09:16
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Aug 6, 2026
@Haruko386 Haruko386 added ci Continue Integration and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Aug 6, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 17

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

🟡 Minor comments (6)
internal/syncer/connector/rss.go-282-289 (1)

282-289: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

RDF feeds parse to zero entries.

parseRSSFeed at Line 356 routes an rdf root element to parseRSSXML. rssRoot reads items only from Channel.Items, which maps to <channel><item>. RSS 1.0 and RDF place <item> as a direct child of <rdf:RDF>, next to <channel>, not inside it.

An RDF feed therefore produces an empty entry list. Validate then reports "RSS feed contains no entries", which does not describe the real cause.

Add a top-level item list and merge the two sources.

🐛 Proposed fix
 type rssRoot struct {
 	XMLName xml.Name
 	Channel rssChannel   `xml:"channel"`
+	Items   []rssXMLItem `xml:"item"`
 }

Then in parseRSSXML:

-	entries := make([]rssEntry, 0, len(root.Channel.Items))
-	for _, item := range root.Channel.Items {
+	items := append(root.Channel.Items, root.Items...)
+	entries := make([]rssEntry, 0, len(items))
+	for _, item := range items {
🤖 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/connector/rss.go` around lines 282 - 289, Update rssRoot and
parseRSSXML to support RDF feeds by adding a top-level item collection for
direct rdf:RDF item elements, then merging it with rssRoot.Channel.Items when
building the parsed entries. Preserve existing channel-based RSS parsing while
ensuring direct RDF items are included and not duplicated.
internal/dao/sync_task.go-262-271 (1)

262-271: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Connector status reset can clear a still-running connector.

The final update sets every recovered connector to SyncStatusSchedule when its status is SyncStatusRunning. A connector can own several tasks. If one task timed out and another task of the same connector still runs, the connector is marked scheduled while work continues.

Restrict the reset to connectors that have no remaining task in SyncStatusRunning.

🤖 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 262 - 271, Update the connector
status reset in the surrounding recovery method so it only changes connectors
with no remaining task in SyncStatusRunning. Preserve the existing
recovered-count and connector ID filtering, and add the appropriate absence
check against the task records before setting status to SyncStatusSchedule.
internal/service/sync_task_service.go-121-127 (1)

121-127: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

error_count never accumulates.

Fail always passes 1. FailTask assigns "error_count": errorCount rather than incrementing it. A task that fails repeatedly always reports one error. The error_count column then carries no useful signal.

Increment the column in the DAO, or pass the current count plus one.

♻️ Proposed change in internal/dao/sync_task.go
"error_count": gorm.Expr("error_count + 1"),
🤖 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/sync_task_service.go` around lines 121 - 127, Update
SyncTaskDAO.FailTask to increment the persisted error_count atomically using the
existing database expression mechanism, rather than assigning the incoming
errorCount value. Keep SyncTaskService.Fail passing the failure signal as
currently implemented.
internal/syncer/syncer.go-101-120 (1)

101-120: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

StartContext allows a second start.

A second call overwrites s.cancel and adds two more goroutines to workerGroup. The goroutines from the first call are then unreachable through Stop, and two schedulers claim tasks concurrently. Return an error, or ignore the call, when the syncer already runs.

🤖 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 101 - 120, The StartContext method
must reject or ignore repeated starts. Track whether the Syncer is already
running using synchronized state, check that state before creating the context,
assigning s.cancel, incrementing workerGroup, or launching goroutines, and
preserve the existing single-start behavior; reset the state when the run is
stopped or completed so a later start is supported.
internal/syncer/sync_runner.go-81-97 (1)

81-97: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Commit windowEnd as the sync watermark.

The connectors return only documents in the interval (updatedAt > WindowStart && updatedAt <= WindowEnd), but this runner stores max(UpdatedAt) or falls back to WindowStart on an empty batch. Use windowEnd as the completed interval boundary so incremental runs do not re-scan the tail of the current window.

🤖 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 81 - 97, Update the completion
watermark logic in the sync runner to always pass windowEnd to CompleteSync,
rather than deriving candidateEnd from document timestamps or an empty-batch
fallback. Remove the candidateEnd tracking and preserve the existing batch
processing and stats aggregation.
internal/syncer/task_coordinator.go-69-76 (1)

69-76: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Guard against a nil connector from the registry.

Execute calls connector.Validate without checking the returned value. A factory that returns (nil, nil) causes a nil interface dereference and panics the worker goroutine. The test registry in internal/syncer/syncer_test.go line 197 returns connectors[row.Connector.ID], which is nil for an unknown connector ID.

🛡️ Proposed fix
 	connector, err := c.registry.Open(ctx, taskContext)
 	if err != nil {
 		return err
 	}
+	if connector == nil {
+		return fmt.Errorf("no connector registered for source %q", taskContext.Connector.Source)
+	}
🤖 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 69 - 76, Update
TaskCoordinator.Execute to check whether connector returned by c.registry.Open
is nil before calling connector.Validate; return an appropriate error for a nil
connector while preserving existing error propagation and validation behavior
for non-nil connectors.
🧹 Nitpick comments (18)
internal/service/sync_document_id_resolver.go (1)

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

Replace the migration reference in the Hash128 comment.

Line 28 does not describe the current function behavior. Remove the reference to the external implementation path.

Proposed comment update
-// Hash128 api.utils.common.hash128.
+// Hash128 returns a 128-bit hash encoded as hexadecimal.

As per coding guidelines, “keep package and doc comments aligned with the current runtime path rather than migration history”.

🤖 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/sync_document_id_resolver.go` around lines 28 - 32, Update
the doc comment immediately above Hash128 to describe its current behavior
without mentioning the external api.utils.common.hash128 implementation path or
migration history. Leave the Hash128 implementation unchanged.

Source: Coding guidelines

internal/syncer/connector/rss.go (2)

143-173: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Drop the unused return values from fetchRSSFeedWithRetry.

The function returns ([]byte, http.Header, string, error). The only caller at Line 143 discards the header and the final URL. Return ([]byte, error) instead. This also removes the net/http import from this file if no other use remains.

Based on the coding guideline "Reduce public surface area when a helper can be private or internal, and keep refactors centered on the owning abstraction."

🤖 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/connector/rss.go` around lines 143 - 173, Update
fetchRSSFeedWithRetry to return only ([]byte, error), remove the unused headers
and finalURL values from its success and failure returns, and adjust the caller
to receive the reduced result. Remove the net/http import if it is no longer
used elsewhere in the file.

Source: Coding guidelines


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

Document why MD5 is required here.

Static analysis flags md5.Sum as a broken hash. In this function MD5 produces a stable document identity, not a security digest, and the identifier must match the value produced by the existing Python connector. A change to SHA-256 would change every SourceID, so the prune snapshot would no longer match stored documents and would delete and re-index the whole feed.

Record that constraint in the code so a later contributor does not change the algorithm.

📝 Proposed comment
 // sourceID returns the RSS source document ID.
+// The MD5 digest is an identity key, not a security digest. It must stay
+// byte-compatible with the Python RSS connector, because a different digest
+// would orphan every previously synced document.
+//
+//nolint:gosec // G401: non-cryptographic identity hash, see above.
 func (e rssEntry) sourceID() string {
 	stable := firstNonEmpty(e.id, e.link, e.title)
 	sum := md5.Sum([]byte(stable))
 	return "rss:" + hex.EncodeToString(sum[:])
 }
🤖 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/connector/rss.go` around lines 236 - 241, Add an explanatory
comment in rssEntry.sourceID immediately before md5.Sum documenting that MD5 is
intentionally used for stable RSS document identity, must remain compatible with
the existing Python connector, and must not be replaced with SHA-256 because
SourceID changes would invalidate prune snapshots and trigger full re-indexing.

Source: Linters/SAST tools

internal/syncer/connector/rss_test.go (1)

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

Pin the source ID to a literal digest.

expectedRSSSourceID recomputes the same MD5 digest that rssEntry.sourceID computes. The test therefore cannot detect a change to the hash algorithm or to the firstNonEmpty(e.id, e.link, e.title) input order. The code comment states that these identifiers must stay Python-compatible, so that change is exactly the regression the test should catch.

Assert against hard-coded digest literals for entry-old and entry-new instead.

🤖 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/connector/rss_test.go` around lines 118 - 122, Replace the
computed digest in expectedRSSSourceID with hard-coded expected digest literals
for “entry-old” and “entry-new” in the relevant RSS tests. Remove or stop using
expectedRSSSourceID so the assertions independently detect changes to
rssEntry.sourceID hashing or input ordering.
internal/syncer/connector/mock/mock.go (1)

75-77: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Return an error for an unknown fetch key.

Fetch returns nil, nil when FetchBlobs does not contain ref.Key. A test that misconfigures the key then observes an empty document body instead of a failure. Return an explicit error to make the misconfiguration visible.

♻️ Proposed change
 func (s *SyncSession) Fetch(ctx context.Context, ref syncerconnector.FetchReference) ([]byte, error) {
-	return s.connector.FetchBlobs[ref.Key], nil
+	blob, ok := s.connector.FetchBlobs[ref.Key]
+	if !ok {
+		return nil, fmt.Errorf("mock: no blob configured for fetch key %q", ref.Key)
+	}
+	return blob, 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/connector/mock/mock.go` around lines 75 - 77, Update
SyncSession.Fetch to check whether ref.Key exists in s.connector.FetchBlobs;
return the stored bytes with nil error for known keys, and return an explicit
error for unknown keys instead of nil, nil.
internal/syncer/connector/github_test.go (1)

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

Assert the io.EOF termination of the prune session.

PruneRunner.Run at internal/syncer/prune_runner.go breaks its loop only on io.EOF. This test stops after the first batch, so it does not cover that contract. The RSS test at internal/syncer/connector/rss_test.go Lines 39-41 already checks it.

💚 Proposed addition
 	for i := range want {
 		if got[i] != want[i] {
 			t.Fatalf("ids[%d] = %q, want %q", i, got[i], want[i])
 		}
 	}
+	if _, err = session.NextBatch(context.Background()); !errors.Is(err, io.EOF) {
+		t.Fatalf("NextBatch EOF = %v", err)
+	}
 }

Add "errors" and "io" to the import block.

🤖 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/connector/github_test.go` around lines 31 - 51, Add coverage
in the prune session test after validating the first batch by calling NextBatch
again and asserting the returned error is io.EOF, using errors.Is for the
comparison. Update the test imports to include errors and io, while preserving
the existing document ID assertions.
internal/syncer/connector/registry.go (1)

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

Remove the unreachable source-probing branches.

Line 56 asserts taskContext to the unnamed type struct{ Connector struct{ Source string } }. Go type assertion requires exact type identity, so a named type such as service.SyncTaskContext never matches this branch. The branch is dead code.

Line 61 also wraps taskContext in any(...), but taskContext is already any.

The only known caller, TaskCoordinator.Execute, passes a value that implements ConnectorSource() string. Keep one lookup path and delete the shims.

♻️ Proposed simplification
 // Open creates a connector for a task context.
 func (r *Registry) Open(ctx context.Context, taskContext any) (Connector, error) {
-	row, ok := taskContext.(interface{ ConnectorSource() string })
-	if ok {
-		return r.openSource(ctx, row.ConnectorSource(), taskContext)
-	}
-	sourceProvider, ok := taskContext.(interface{ Source() string })
-	if ok {
-		return r.openSource(ctx, sourceProvider.Source(), taskContext)
-	}
-	rowContext, ok := taskContext.(struct{ Connector struct{ Source string } })
-	if ok {
-		return r.openSource(ctx, rowContext.Connector.Source, taskContext)
-	}
-	source := ""
-	if value, ok := any(taskContext).(interface{ GetSource() string }); ok {
-		source = value.GetSource()
-	}
-	return r.openSource(ctx, source, taskContext)
+	row, ok := taskContext.(interface{ ConnectorSource() string })
+	if !ok {
+		return nil, fmt.Errorf("task context %T does not expose a connector source", taskContext)
+	}
+	return r.openSource(ctx, row.ConnectorSource(), taskContext)
 }

Based on the coding guideline "Treat legacy code as liability; prefer deletion over compatibility 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/syncer/connector/registry.go` around lines 46 - 65, Remove the
fallback source-probing branches from Registry.Open, including the exact unnamed
struct assertion and the GetSource lookup. Keep only the ConnectorSource() path
used by TaskCoordinator.Execute, and directly pass taskContext to the remaining
openSource call without wrapping it in any.

Source: Coding guidelines

internal/syncer/connector/github.go (3)

156-162: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Restrict the org-to-user fallback to a not-found response.

The code falls back to /users/{owner}/repos for any error from /orgs/{owner}/repos. An authentication failure, a rate-limit response, or a network timeout therefore triggers a second request, and the original error is discarded. The caller then sees only the user-endpoint error, which hides the real cause.

GitHub returns HTTP 404 when the owner is not an organization. Gate the fallback on that status, and return the org error otherwise.

To do this, getJSON must expose the status code. Add a typed error, for example:

type githubAPIError struct {
	StatusCode int
	Body       string
}

func (e *githubAPIError) Error() string {
	return fmt.Sprintf("GitHub API returned HTTP %d: %s", e.StatusCode, e.Body)
}

Then return &githubAPIError{...} at Line 277 and check it here.

♻️ Proposed fallback logic
 	repos, err := c.listRepoEndpoint(ctx, "/orgs/"+url.PathEscape(c.owner)+"/repos")
-	if err == nil {
-		return repos, nil
-	}
-	return c.listRepoEndpoint(ctx, "/users/"+url.PathEscape(c.owner)+"/repos")
+	if err == nil {
+		return repos, nil
+	}
+	var apiErr *githubAPIError
+	if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
+		return nil, err
+	}
+	return c.listRepoEndpoint(ctx, "/users/"+url.PathEscape(c.owner)+"/repos")
🤖 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/connector/github.go` around lines 156 - 162, Restrict the
fallback in the repository lookup flow around listRepoEndpoint to HTTP 404
responses from the organization endpoint; return the original error for
authentication, rate-limit, network, and other failures. Update getJSON to
return a typed githubAPIError containing StatusCode and Body, and use that type
here to gate the user-endpoint request.

270-283: 🩺 Stability & Availability | 🔵 Trivial | 🏗️ Heavy lift

Handle GitHub rate-limit responses.

getJSON treats every status at or above 400 as a terminal error. GitHub returns 403 or 429 with Retry-After or X-RateLimit-Reset when it throttles a client. A large owner with many repositories reaches that limit during a single loadDocuments call, and the whole sync task then fails.

Read Retry-After and X-RateLimit-Remaining, and retry after the indicated delay. The RSS connector already has fetchRSSFeedWithRetry at internal/syncer/connector/rss.go Lines 155-173 as a precedent.

🤖 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/connector/github.go` around lines 270 - 283, Update getJSON
to recognize GitHub rate-limit responses (403 or 429), read Retry-After and
X-RateLimit-Reset (alongside X-RateLimit-Remaining), wait for the indicated
delay, and retry the request before treating the response as terminal. Follow
the retry behavior established by fetchRSSFeedWithRetry, while preserving the
existing error handling for other HTTP failures and decode errors.

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

Extract the shared paginated window scan.

listPullRequests and listIssues repeat the same query construction, pagination loop, window comparison, and stop condition. Only the response type and the extra PullRequest != nil filter differ.

Extract one generic helper, for example:

func listGitHubWindow[T any](
	ctx context.Context,
	c *GitHubConnector,
	path string,
	updatedAt func(T) time.Time,
	skip func(T) bool,
	convert func(T) SourceDocument,
	windowStart *time.Time,
	windowEnd time.Time,
) ([]SourceDocument, error)

This keeps the window semantics in one place, so a later change to the stop condition cannot apply to only one endpoint.

🤖 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/connector/github.go` around lines 183 - 251, Extract the
duplicated pagination and window-scanning logic from listPullRequests and
listIssues into a generic helper such as listGitHubWindow. Parameterize the
endpoint path, item timestamp accessor, skip predicate, and SourceDocument
converter; preserve the existing window bounds, pagination headers, empty-batch
termination, and pull-request filtering behavior through those callbacks. Update
both methods to delegate to the helper.
internal/syncer/syncer_test.go (2)

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

The fixed sleeps make these tests timing-dependent.

TestWorkersRunDifferentConnectorsInParallel sleeps 40ms and expects both tasks to be in flight. TestConnectorLockSerializesSameConnector sleeps 180ms. On a loaded CI runner, the worker goroutines may not reach the sink in time, and the tests fail without a code defect.

Replace the sleeps with synchronization. For example, have fakeSink signal on a channel when it reaches the configured concurrency, and wait on that channel with a generous timeout.

🤖 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 253 - 262, Replace fixed sleeps
in TestWorkersRunDifferentConnectorsInParallel and
TestConnectorLockSerializesSameConnector with synchronization through fakeSink,
signaling when the expected sink state is reached. Wait for those signals using
generous timeouts, while preserving the existing concurrency and serialization
assertions.

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

Do not discard setup errors in tests.

Line 305 discards the result of the status update, and line 321 discards the error from GetContext. If either fails, the test proceeds with an empty task context and reports a confusing failure later. The same pattern repeats at lines 334, 340, 368, 375, 391, 396, 409, and 453.

Check each error with t.Fatalf.

Also applies to: 321-321

🤖 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` at line 305, Update the test setup operations
in the relevant syncer tests, including the status updates and GetContext calls,
to capture and check each returned error with t.Fatalf. Apply this consistently
to all repeated instances identified in the diff so setup failures stop the test
immediately instead of allowing invalid task context to propagate.
internal/dao/sync_task.go (1)

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

Remove or complete the bare // TODO marker.

The comment gives no information. The coding guidelines require removal of stale notes instead of preserving them. If work remains here, describe it or track it in an issue.

Do you want me to open an issue for the remaining work in ListDueTasks?

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

🤖 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` at line 90, Remove the bare TODO marker in
ListDueTasks, or replace it with a specific actionable note only if unfinished
work remains; do not leave an unexplained stale marker.

Source: Coding guidelines

internal/service/sync_task_service.go (1)

82-93: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Extract the hard-coded page size.

ListDueTasks passes the literal 128. The value controls scheduler load and interacts with Config.TaskQueueSize. Move it to a named constant or to Config.

🤖 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/sync_task_service.go` around lines 82 - 93, Extract the
hard-coded 128 page size from SyncTaskService.ListDueTasks into a named constant
or the relevant Config field, then pass that symbol to taskDAO.ListDueTasks
while preserving the existing behavior.
internal/syncer/sync_runner.go (1)

100-137: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

processBatch returns one error and drops the rest.

The function reads a single error from errs and discards the others. The task fails either way, so behavior is correct, but the operator loses the other failure reasons. Consider joining the errors with errors.Join, or recording the remaining errors in SyncStats.ErrorMsg.

🤖 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 100 - 137, Update
SyncRunner.processBatch to preserve all errors collected in errs instead of
returning only the first one; aggregate them with errors.Join (or record every
message through SyncStats.ErrorMsg) while keeping the existing failure behavior
and successful result aggregation unchanged.
internal/syncer/recovery.go (1)

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

Delete the unused RecoverStaleRunning wrapper.

internal/syncer/recovery.go only forwards to service.SyncTaskService.RecoverStaleRunning, while callers use the service method directly. Remove the exported wrapper or delete internal/syncer/recovery.go if it has no other usage.

🤖 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/recovery.go` around lines 25 - 28, Remove the unused exported
RecoverStaleRunning wrapper from internal/syncer/recovery.go; if the file
contains no other required symbols or usage, delete the file entirely. Keep
service.SyncTaskService.RecoverStaleRunning as the direct caller-facing
implementation.

Source: Coding guidelines

internal/dao/sync_prune_snapshot.go (1)

48-57: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Bound prune snapshot inserts with conflict handling.

InsertBatch writes every row of a prune slice in one statement, so large source sets can still exceed driver/database limits. CreateInBatches bounds each statement size. Use clause.OnConflict{DoNothing: true} at the same time because task_id plus source_doc_id is a primary key; duplicate SourceID values in one connector slice would fail the insert and abort PRUNE.

♻️ Proposed change
-	return d.db.WithContext(ctx).Create(&rows).Error
+	return d.db.WithContext(ctx).
+		Clauses(clause.OnConflict{DoNothing: true}).
+		CreateInBatches(&rows, 500).Error

Add the import:

import "gorm.io/gorm/clause"
🤖 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_prune_snapshot.go` around lines 48 - 57, Update
SyncPruneSnapshotDAO.InsertBatch to use GORM CreateInBatches with an appropriate
bounded batch size instead of one unbounded Create call, and add
clause.OnConflict{DoNothing: true} so duplicate taskID/source_doc_id keys are
ignored. Preserve the empty-documents early return and existing row
construction.
internal/syncer/task_coordinator.go (1)

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

Use service.SyncTaskContext for connector context.

ConnectorRegistry.Open, syncerconnector.Factory, and syncerconnector.Registry.Open all accept any and then type-assert to dao.SyncTaskContext at runtime. TaskCoordinator.Execute already passes service.SyncTaskContext, and service.SyncTaskContext is an alias for dao.SyncTaskContext, so declare the context as service.SyncTaskContext` and remove the factory/runtime assertions.

🤖 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 27 - 31, Replace the any
context type with service.SyncTaskContext across ConnectorRegistry.Open,
syncerconnector.Factory, and syncerconnector.Registry.Open. Remove the runtime
assertions to dao.SyncTaskContext and pass the strongly typed context through
directly, preserving TaskCoordinator.Execute’s existing service.SyncTaskContext
usage.
🤖 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/sync_task.go`:
- Around line 104-118: Update ListDueTasks to select connector.refresh_freq,
connector.prune_freq, and connector.config in its existing joined query,
evaluate isDue from those in-memory values, and call GetTaskContext only for
tasks that pass. Apply the same optimization to RecoverStaleRunning by selecting
time_started and connector.timeout_secs in its query and avoiding GetTaskContext
for each running task.
- Around line 275-284: The createScheduledTask check is vulnerable to concurrent
duplicate scheduled-task inserts because the count and insert are separate
operations. Add a database-backed uniqueness guard for the connectorID, kbID,
taskType, and scheduled status combination, and make the insert path handle
conflicts idempotently so concurrent callers leave only one scheduled SyncLogs
record.
- Line 97: The task rescheduling flow must also restore connector status for
running tasks so rows remain eligible for ListDueTasks. Update RescheduleClaimed
in internal/dao/sync_task.go and daemonConnectorService in
internal/syncer/task_worker.go to reset the connector status to
SyncStatusSchedule when rescheduling claimed/running tasks, while preserving
completed task statuses and not resetting tasks that finished successfully.

In `@internal/service/document/sync_document.go`:
- Around line 75-89: Update the sync flow around storageImpl.Put,
insertSyncDocument, and updateSyncDocument to write new blobs to a distinct
staged location rather than overwriting the active object. Perform the database
mutation first, publish the staged location and content hash only after it
succeeds, and remove staged objects whenever a subsequent operation fails;
preserve cleanup for both insert and update paths.
- Around line 71-73: Update the content-hash fast path in the document sync
method so it does not return DocumentActionSkipped solely because
existing.ContentHash matches. Persist or inspect completion state for the
file-manager link, metadata, and parsing request, retry any incomplete work
before returning, and only return DocumentActionSkipped once all dependent
post-write operations are complete.

In `@internal/service/sync_document_id_resolver.go`:
- Around line 58-84: Update DocumentIDResolver.Resolve to avoid loading all
knowledge-base IDs and fingerprints for every document; either introduce
task/batch-scoped resolver state reused across calls, or change the store access
to query only legacyID and newID for the current document. Preserve legacy-ID
selection and StoredFingerprint fallback behavior while eliminating the
per-document full ListIDs and ListFingerprints scans.

In `@internal/service/sync_task_service.go`:
- Around line 146-149: Update IsFromBeginning so a nil value returns false,
preserving full-sync behavior only when the trimmed value is "1"; keep
SyncRunner.Run’s existing handling unchanged.

In `@internal/syncer/connector/github.go`:
- Around line 96-141: Replace the eager loadDocuments flow used by OpenSync and
OpenPrune with on-demand pagination in githubSyncSession.NextBatch, retaining
repository and page cursors and buffering no more than one batch while fetching
pull requests and issues as needed. Update OpenSync to initialize this streaming
session without loading the corpus; keep errors and window filtering propagated
during iteration. Update OpenPrune to collect only SourceID values through a
lightweight streaming path, avoiding materialization of document bodies while
preserving prune session batching.

In `@internal/syncer/connector/rss.go`:
- Around line 106-114: The RSS sync must always enforce request.WindowEnd,
including from-beginning syncs: update the OpenSync entry filtering near lines
106-114 to apply the unconditional after-window-end check, matching the GitHub
connector. In the RSS date fallback near lines 413-419, remove time.Now().UTC(),
leave UpdatedAt zero, and derive Fingerprint from the rendered body for
deterministic change detection. Add an entry dated after WindowEnd to
TestRSSConnectorOpenSyncFullAndIncremental in
internal/syncer/connector/rss_test.go to cover the upper-bound behavior.

In `@internal/syncer/prune_runner.go`:
- Around line 56-75: Update the prune flow around NextBatch, AddSnapshotBatch,
and DeleteStale to use a single cleanup helper or equivalent path that calls
ClearSnapshot with context.WithoutCancel(ctx). Replace the repeated
cancellation-sensitive cleanup calls while preserving the existing error returns
and successful cleanup behavior.

In `@internal/syncer/scheduler.go`:
- Around line 71-84: Update the task-processing loop in scan so an error from
taskService.Claim does not return immediately and abandon previously claimed
tasks. Record the claim error, continue processing the remaining tasks, and
preserve enqueueing for successfully claimed tasks; return the recorded error
after the loop completes.
- Around line 43-59: Update Scheduler.Run so scan errors from both the initial
scan and ticker-triggered scans are logged with the repository’s existing
logging package instead of returned, allowing the scheduler to continue and
retry on the next tick. Preserve context cancellation by returning only when
ctx.Done() is signaled, while retaining ticker cleanup.

In `@internal/syncer/sync_runner.go`:
- Around line 142-162: The retry backoff in processDocumentWithRetry must avoid
overflow and invalid jitter values at high attempts. Guard rand.Int63n so it is
only used when ItemRetryBaseDelay/2 is positive, and cap the exponential shift
before multiplying by time.Duration so the computed delay never wraps negative.

In `@internal/syncer/syncer_test.go`:
- Around line 286-296: Protect the `sink.maxConcurrent` read in the test with
`sink.mu`, matching the locked read used in the previous test. Acquire the mutex
before checking the value and release it afterward, while preserving the
existing failure condition and message.

In `@internal/syncer/syncer.go`:
- Around line 122-130: Update Syncer.Stop to use a sync.Once-backed shutdown
guard so it is safe to call repeatedly, always closes ShutdownCh even when Start
was never called, and only invokes the non-nil cancel function when available.
Add the required sync.Once field to Syncer and remove the trailing “Potential”
comment.

In `@internal/syncer/task_worker.go`:
- Around line 66-71: Update TaskWorker.handle so errors from GetContext and
Execute are rescheduled when ctx.Err() is non-nil, including context
cancellation during shutdown, instead of calling taskService.Fail. Preserve the
existing failure path for non-cancellation errors and ensure the task is not
marked failed or the connector set to SyncStatusFail during shutdown.

In `@internal/utility/upload.go`:
- Around line 45-56: Update FetchRemoteFileSafelyWithTimeout to create each
redirect request with http.NewRequestWithContext(ctx, http.MethodGet,
currentURL, nil) and pass that request to client.Do, ensuring cancellation
reaches the in-flight fetch. Add an httptest cancellation test if this path
lacks existing coverage.

---

Minor comments:
In `@internal/dao/sync_task.go`:
- Around line 262-271: Update the connector status reset in the surrounding
recovery method so it only changes connectors with no remaining task in
SyncStatusRunning. Preserve the existing recovered-count and connector ID
filtering, and add the appropriate absence check against the task records before
setting status to SyncStatusSchedule.

In `@internal/service/sync_task_service.go`:
- Around line 121-127: Update SyncTaskDAO.FailTask to increment the persisted
error_count atomically using the existing database expression mechanism, rather
than assigning the incoming errorCount value. Keep SyncTaskService.Fail passing
the failure signal as currently implemented.

In `@internal/syncer/connector/rss.go`:
- Around line 282-289: Update rssRoot and parseRSSXML to support RDF feeds by
adding a top-level item collection for direct rdf:RDF item elements, then
merging it with rssRoot.Channel.Items when building the parsed entries. Preserve
existing channel-based RSS parsing while ensuring direct RDF items are included
and not duplicated.

In `@internal/syncer/sync_runner.go`:
- Around line 81-97: Update the completion watermark logic in the sync runner to
always pass windowEnd to CompleteSync, rather than deriving candidateEnd from
document timestamps or an empty-batch fallback. Remove the candidateEnd tracking
and preserve the existing batch processing and stats aggregation.

In `@internal/syncer/syncer.go`:
- Around line 101-120: The StartContext method must reject or ignore repeated
starts. Track whether the Syncer is already running using synchronized state,
check that state before creating the context, assigning s.cancel, incrementing
workerGroup, or launching goroutines, and preserve the existing single-start
behavior; reset the state when the run is stopped or completed so a later start
is supported.

In `@internal/syncer/task_coordinator.go`:
- Around line 69-76: Update TaskCoordinator.Execute to check whether connector
returned by c.registry.Open is nil before calling connector.Validate; return an
appropriate error for a nil connector while preserving existing error
propagation and validation behavior for non-nil connectors.

---

Nitpick comments:
In `@internal/dao/sync_prune_snapshot.go`:
- Around line 48-57: Update SyncPruneSnapshotDAO.InsertBatch to use GORM
CreateInBatches with an appropriate bounded batch size instead of one unbounded
Create call, and add clause.OnConflict{DoNothing: true} so duplicate
taskID/source_doc_id keys are ignored. Preserve the empty-documents early return
and existing row construction.

In `@internal/dao/sync_task.go`:
- Line 90: Remove the bare TODO marker in ListDueTasks, or replace it with a
specific actionable note only if unfinished work remains; do not leave an
unexplained stale marker.

In `@internal/service/sync_document_id_resolver.go`:
- Around line 28-32: Update the doc comment immediately above Hash128 to
describe its current behavior without mentioning the external
api.utils.common.hash128 implementation path or migration history. Leave the
Hash128 implementation unchanged.

In `@internal/service/sync_task_service.go`:
- Around line 82-93: Extract the hard-coded 128 page size from
SyncTaskService.ListDueTasks into a named constant or the relevant Config field,
then pass that symbol to taskDAO.ListDueTasks while preserving the existing
behavior.

In `@internal/syncer/connector/github_test.go`:
- Around line 31-51: Add coverage in the prune session test after validating the
first batch by calling NextBatch again and asserting the returned error is
io.EOF, using errors.Is for the comparison. Update the test imports to include
errors and io, while preserving the existing document ID assertions.

In `@internal/syncer/connector/github.go`:
- Around line 156-162: Restrict the fallback in the repository lookup flow
around listRepoEndpoint to HTTP 404 responses from the organization endpoint;
return the original error for authentication, rate-limit, network, and other
failures. Update getJSON to return a typed githubAPIError containing StatusCode
and Body, and use that type here to gate the user-endpoint request.
- Around line 270-283: Update getJSON to recognize GitHub rate-limit responses
(403 or 429), read Retry-After and X-RateLimit-Reset (alongside
X-RateLimit-Remaining), wait for the indicated delay, and retry the request
before treating the response as terminal. Follow the retry behavior established
by fetchRSSFeedWithRetry, while preserving the existing error handling for other
HTTP failures and decode errors.
- Around line 183-251: Extract the duplicated pagination and window-scanning
logic from listPullRequests and listIssues into a generic helper such as
listGitHubWindow. Parameterize the endpoint path, item timestamp accessor, skip
predicate, and SourceDocument converter; preserve the existing window bounds,
pagination headers, empty-batch termination, and pull-request filtering behavior
through those callbacks. Update both methods to delegate to the helper.

In `@internal/syncer/connector/mock/mock.go`:
- Around line 75-77: Update SyncSession.Fetch to check whether ref.Key exists in
s.connector.FetchBlobs; return the stored bytes with nil error for known keys,
and return an explicit error for unknown keys instead of nil, nil.

In `@internal/syncer/connector/registry.go`:
- Around line 46-65: Remove the fallback source-probing branches from
Registry.Open, including the exact unnamed struct assertion and the GetSource
lookup. Keep only the ConnectorSource() path used by TaskCoordinator.Execute,
and directly pass taskContext to the remaining openSource call without wrapping
it in any.

In `@internal/syncer/connector/rss_test.go`:
- Around line 118-122: Replace the computed digest in expectedRSSSourceID with
hard-coded expected digest literals for “entry-old” and “entry-new” in the
relevant RSS tests. Remove or stop using expectedRSSSourceID so the assertions
independently detect changes to rssEntry.sourceID hashing or input ordering.

In `@internal/syncer/connector/rss.go`:
- Around line 143-173: Update fetchRSSFeedWithRetry to return only ([]byte,
error), remove the unused headers and finalURL values from its success and
failure returns, and adjust the caller to receive the reduced result. Remove the
net/http import if it is no longer used elsewhere in the file.
- Around line 236-241: Add an explanatory comment in rssEntry.sourceID
immediately before md5.Sum documenting that MD5 is intentionally used for stable
RSS document identity, must remain compatible with the existing Python
connector, and must not be replaced with SHA-256 because SourceID changes would
invalidate prune snapshots and trigger full re-indexing.

In `@internal/syncer/recovery.go`:
- Around line 25-28: Remove the unused exported RecoverStaleRunning wrapper from
internal/syncer/recovery.go; if the file contains no other required symbols or
usage, delete the file entirely. Keep
service.SyncTaskService.RecoverStaleRunning as the direct caller-facing
implementation.

In `@internal/syncer/sync_runner.go`:
- Around line 100-137: Update SyncRunner.processBatch to preserve all errors
collected in errs instead of returning only the first one; aggregate them with
errors.Join (or record every message through SyncStats.ErrorMsg) while keeping
the existing failure behavior and successful result aggregation unchanged.

In `@internal/syncer/syncer_test.go`:
- Around line 253-262: Replace fixed sleeps in
TestWorkersRunDifferentConnectorsInParallel and
TestConnectorLockSerializesSameConnector with synchronization through fakeSink,
signaling when the expected sink state is reached. Wait for those signals using
generous timeouts, while preserving the existing concurrency and serialization
assertions.
- Line 305: Update the test setup operations in the relevant syncer tests,
including the status updates and GetContext calls, to capture and check each
returned error with t.Fatalf. Apply this consistently to all repeated instances
identified in the diff so setup failures stop the test immediately instead of
allowing invalid task context to propagate.

In `@internal/syncer/task_coordinator.go`:
- Around line 27-31: Replace the any context type with service.SyncTaskContext
across ConnectorRegistry.Open, syncerconnector.Factory, and
syncerconnector.Registry.Open. Remove the runtime assertions to
dao.SyncTaskContext and pass the strongly typed context through directly,
preserving TaskCoordinator.Execute’s existing service.SyncTaskContext usage.
🪄 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: d1404310-e1f6-429f-85a7-6aec6d5a7f09

📥 Commits

Reviewing files that changed from the base of the PR and between 2fcc349 and 24f8522.

📒 Files selected for processing (26)
  • internal/dao/sync_prune_snapshot.go
  • internal/dao/sync_task.go
  • internal/service/document/sync_document.go
  • internal/service/sync_document_id_resolver.go
  • internal/service/sync_document_sink.go
  • internal/service/sync_prune_service.go
  • internal/service/sync_task_service.go
  • internal/syncer/config.go
  • internal/syncer/connector/github.go
  • internal/syncer/connector/github_test.go
  • internal/syncer/connector/interface.go
  • internal/syncer/connector/mock/mock.go
  • internal/syncer/connector/models.go
  • internal/syncer/connector/registry.go
  • internal/syncer/connector/rss.go
  • internal/syncer/connector/rss_test.go
  • internal/syncer/connector_lock.go
  • internal/syncer/prune_runner.go
  • internal/syncer/recovery.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/utility/upload.go

Comment thread internal/dao/sync_task.go Resolved
Comment thread internal/dao/sync_task.go Resolved
Comment thread internal/dao/sync_task.go Resolved
Comment thread internal/syncer/sync_runner.go Resolved
Comment thread internal/syncer/syncer_test.go Resolved
Comment thread internal/syncer/syncer.go Resolved
Comment thread internal/syncer/task_worker.go Resolved
Comment thread internal/utility/upload.go Resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Aug 6, 2026
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

@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: 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/scheduler.go`:
- Around line 44-45: Replace the undefined log reference in the scheduler scan
error paths around s.scan and the corresponding line 55 with the repository’s
existing logging package or logger available to the scheduler package, adding
the required import if needed. Ensure both log.Errorf calls compile, then
validate with the narrowest package-scoped bash build.sh --test command.
🪄 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: aef5e2b6-50f2-4be5-bf1d-094d085ba172

📥 Commits

Reviewing files that changed from the base of the PR and between 24f8522 and 5e17a51.

📒 Files selected for processing (2)
  • internal/service/sync_task_service.go
  • internal/syncer/scheduler.go

Comment thread internal/syncer/scheduler.go Resolved

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

🧹 Nitpick comments (2)
internal/syncer/connector/github.go (1)

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

Consider unifying the duplicated session pagination logic.

githubPruneSession.NextBatch duplicates githubSyncSession.NextBatch line for line. nextSlimPage duplicates nextDocumentPage, and each session repeats advanceStage and advanceRepo. Only the element type and the page fetcher differ.

Extract one generic cursor type parameterized on the document type. Give it the buffer loop, the stage machine, and the repo cursor. Each session then supplies a fetch function.

This is optional for this PR. Keep it in mind if a third stage or a third session type appears.

Also applies to: 391-495

🤖 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/connector/github.go` around lines 349 - 379, The current
pagination, buffering, and repository cursor logic in
githubPruneSession.NextBatch and the corresponding githubSyncSession methods is
duplicated. If undertaking this optional refactor, extract the shared buffer
loop, stage machine, and repo advancement into one generic cursor parameterized
by document type, and have each session provide only its page-fetch function,
preserving existing batching and EOF behavior.
internal/dao/sync_task.go (1)

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

The bulk connector update is now redundant.

RescheduleClaimed already resets the connector status from RUNNING to SCHEDULE inside its own transaction at line 183. By the time the loop ends, no connector in connectorIDs is still RUNNING, so the statement at line 291 matches zero rows on every call.

Drop the connectorIDs set and the trailing update, and return recovered, nil. Keeping both paths leaves two owners for the same state transition.

🤖 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 285 - 291, Remove the connectorIDs
collection and the trailing bulk status update from RescheduleClaimed, since its
transaction already performs the RUNNING-to-SCHEDULE transition. Return
recovered, nil after the loop, leaving RescheduleClaimed as the sole owner of
this state change.

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/sync_task.go`:
- Around line 296-302: Update the lockRow query in the sync completion path to
avoid applying clause.Locking with Strength "UPDATE" when the active database
dialect is SQLite, while preserving row locking for supported databases. Keep
the existing transaction, context, filters, and error handling unchanged.
- Around line 113-119: Remove the GetTaskContext call from ListDueTasks so due
tasks are appended directly after the isDue check. Do not re-fetch joined data
or return probe errors; if validation is retained, skip only rows whose lookup
returns IsNotFound and preserve processing of other errors according to the
existing flow.

In `@internal/service/sync_document_id_resolver.go`:
- Around line 48-50: Update DocumentStore to expose GetFingerprintsByIDs,
implement it in internal/syncer/syncer_test.go’s fakeStore, and make
DocumentIDResolver.Resolve use the targeted lookup directly. Remove
pairDocumentStore, its type assertion, and the ListIDs/ListFingerprints
fallback; delete ListFingerprints if unused, while retaining ListIDs for
SyncPruneService.

---

Nitpick comments:
In `@internal/dao/sync_task.go`:
- Around line 285-291: Remove the connectorIDs collection and the trailing bulk
status update from RescheduleClaimed, since its transaction already performs the
RUNNING-to-SCHEDULE transition. Return recovered, nil after the loop, leaving
RescheduleClaimed as the sole owner of this state change.

In `@internal/syncer/connector/github.go`:
- Around line 349-379: The current pagination, buffering, and repository cursor
logic in githubPruneSession.NextBatch and the corresponding githubSyncSession
methods is duplicated. If undertaking this optional refactor, extract the shared
buffer loop, stage machine, and repo advancement into one generic cursor
parameterized by document type, and have each session provide only its
page-fetch function, preserving existing batching and EOF behavior.
🪄 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: 0099781e-0c6f-4383-9fe7-eaf0ccd1b9be

📥 Commits

Reviewing files that changed from the base of the PR and between 5e17a51 and 75c6734.

📒 Files selected for processing (13)
  • internal/dao/sync_task.go
  • internal/service/document/sync_document.go
  • internal/service/sync_document_id_resolver.go
  • internal/syncer/connector/github.go
  • internal/syncer/connector/rss.go
  • internal/syncer/connector/rss_test.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_worker.go
  • internal/utility/upload.go
🚧 Files skipped from review as they are similar to previous changes (7)
  • internal/syncer/scheduler.go
  • internal/syncer/task_worker.go
  • internal/syncer/sync_runner.go
  • internal/syncer/prune_runner.go
  • internal/utility/upload.go
  • internal/service/document/sync_document.go
  • internal/syncer/syncer_test.go

Comment thread internal/dao/sync_task.go Resolved
Comment thread internal/dao/sync_task.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. go Pull requests that update go code 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