Skip to content

fix: implement Go syncer execution engine with RSS data source support - #17695

Closed
euvre wants to merge 1 commit into
infiniflow:mainfrom
euvre:fix/go-syncer-rss-data-source
Closed

euvre wants to merge 1 commit into
infiniflow:mainfrom
euvre:fix/go-syncer-rss-data-source

Conversation

@euvre

@euvre euvre commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Summary

In Go mode, RSS data sources could never be imported into a knowledge base (the Python backend works fine). The Go syncer was a stub: pollAndExecute only logged, no sync_logs rows were ever consumed, and no RSS connector existed on the Go side, so sync tasks stayed in Schedule/Cancel forever.

This PR implements the full Go sync execution path, mirroring the Python reference (rag/svr/sync_data_source.py, common/data_source/rss_connector.py, FileService.upload_document):

  • Syncer engine (internal/syncer): polls due sync/prune tasks honoring refresh_freq/prune_freq windows, claims tasks atomically, executes with the connector's timeout_secs, performs done/fail status bookkeeping, and reschedules the next run after success (mirrors SyncBase.__call__).
  • RSS connector: SSRF-safe feed fetching (reuses utility.FetchRemoteFileSafely), RSS 2.0 + Atom parsing, deterministic document IDs (rss:md5(...) + hash128 with legacy-ID compatibility), HTML-to-text content building, poll-window filtering, and batching.
  • Document import (DocumentService.UploadConnectorDocuments): mirrors duplicate_and_parse + FileService.upload_document — content-hash dedupe (unchanged docs are not re-parsed), name dedupe, storage upload, file-manager linkage, and doc_num counters; parsing is enqueued when the link has auto_parse enabled.
  • DAO support: due-task listing, atomic claim, increase_docs/increase_removed_docs accumulation, finish/reschedule with 100-row log retention; the first sync after link/rebuild is due immediately (Python run_immediately=True).
  • Prune: when sync_deleted_files is enabled, documents that disappeared from the feed are deleted from the knowledge base.

Other sources (S3, Confluence, etc.) remain unimplemented in Go and now fail fast with a clear "not supported by the Go syncer" message instead of being silently marked done.

Verified: unit tests for feed parsing/poll windows/batching/HTML normalization, Hash128Hex parity with Python hash128, package tests for syncer/dao/service/document, and a full build.sh --go build.

The Go syncer was a stub: pollAndExecute only logged, no sync_logs rows
were ever consumed, and no RSS connector existed, so RSS data sources
never imported into knowledge bases in Go mode (Python worked).

- syncer: poll due sync/prune tasks (refresh_freq/prune_freq window),
  claim atomically, execute with timeout_secs, done/fail bookkeeping,
  and reschedule the next run (mirrors Python SyncBase.__call__)
- rss: RSS/Atom connector with SSRF-safe fetch, deterministic doc IDs
  (rss:md5 + hash128, legacy-id compatible), HTML-to-text content,
  poll-window filtering and batching (mirrors rss_connector.py)
- document: UploadConnectorDocuments mirrors FileService.upload_document
  (content-hash dedupe, name dedupe, file linkage, doc_num counters)
- dao: due-task listing, claim, increase_docs/removed_docs, finish,
  reschedule with log retention; first sync (link/rebuild) due
  immediately (Python run_immediately=True)
- prune: delete connector docs that disappeared from the feed when
  sync_deleted_files is enabled

Verified: Hash128Hex parity with Python hash128, unit tests for feed
parsing/poll windows/batching, full build passes.
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. 💞 feature Feature request, pull request that fullfill a new feature. labels Aug 3, 2026
@euvre euvre added the ci Continue Integration label Aug 3, 2026
@coderabbitai

coderabbitai Bot commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR adds scheduled connector task execution for RSS and Atom sources. It introduces feed parsing, document import and update handling, stale-document pruning, task progress tracking, error handling, and sync-log rescheduling.

Changes

RSS Connector Sync

Layer / File(s) Summary
Scheduled task lifecycle
internal/dao/connector.go
The connector DAO lists due tasks, claims tasks atomically, records progress, finalizes tasks, reschedules tasks, prunes sync logs, and marks reindex tasks as immediately due.
RSS and Atom feed ingestion
internal/syncer/rss.go, internal/syncer/rss_test.go
The RSS syncer retrieves and parses feeds, normalizes entries and HTML content, filters time windows, creates stable document IDs, and validates these behaviors with RSS and Atom tests.
Connector document import
internal/service/document/document_upload.go, internal/service/document/document_upload_helpers.go
The document service imports new and existing connector documents, validates files, stores blobs, links files, rejects ID collisions, rolls back failures, and exposes the 128-bit hash helper.
Sync and prune execution
internal/syncer/syncer.go
The syncer claims due tasks, applies timeouts and panic recovery, imports RSS documents, updates metadata, optionally starts parsing, prunes stale entries, records progress, and reschedules tasks.

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

Sequence Diagram(s)

sequenceDiagram
  participant Syncer
  participant ConnectorDAO
  participant RSSConnector
  participant DocumentService
  participant DocumentStore

  Syncer->>ConnectorDAO: ListDueTasks and ClaimTask
  Syncer->>RSSConnector: Load RSS or Atom feed
  RSSConnector-->>Syncer: Normalized documents and entry IDs
  Syncer->>DocumentService: UploadConnectorDocuments
  DocumentService->>DocumentStore: Insert or update documents
  DocumentStore-->>DocumentService: Upload results
  DocumentService-->>Syncer: Results and errors
  Syncer->>ConnectorDAO: Record progress and finish task
  Syncer->>ConnectorDAO: Reschedule task
Loading

Poem

I hop through feeds with ears held high,
Parse little stories from the sky.
New blobs land, old ones renew,
Stale leaves fall from the dataset too.
Tasks wake, run, and safely rest.
Bunny says: this sync is best!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.08% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: implementing the Go syncer execution engine and RSS support.
Description check ✅ Passed The description includes the required Summary section and clearly explains the problem, implementation scope, and verification performed.
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.

@euvre
euvre requested a review from wangq8 August 3, 2026 02:22

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 11

🧹 Nitpick comments (4)
internal/syncer/rss.go (2)

258-261: 🔒 Security & Privacy | 🔵 Trivial | 💤 Low value

MD5 use is acceptable here; document the intent.

Static analysis flags md5.Sum. The hash produces a deterministic entry identifier and is not used for a security decision, and it maintains parity with the Python connector. Add a short comment so the finding is not re-raised.

📝 Proposed comment
+// buildDocumentID derives a stable, non-security entry identifier. MD5 is used
+// for parity with the Python RSSConnector document ids.
 func (c *rssConnector) buildDocumentID(entry feedEntry) string {
🤖 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/rss.go` around lines 258 - 261, Add a brief comment directly
above the md5.Sum call in rssConnector.buildDocumentID explaining that MD5 is
intentionally used for deterministic, non-security entry identifiers and to
maintain parity with the Python connector.

Source: Linters/SAST tools


290-297: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low value

Dateless entries are re-imported on every poll.

resolveEntryTime returns time.Now() when no timestamp parses. In an incremental poll the value is always after start, so the entry passes the window filter on every run. IncreaseDocs then counts the entry again, and poll_range_start advances to the current time on each poll. Content deduplication in UploadConnectorDocuments prevents a re-parse, but the progress counters become inaccurate.

Consider excluding dateless entries from bounded polls, or deriving a stable time from the entry content.

🤖 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/rss.go` around lines 290 - 297, Update resolveEntryTime so
entries without a parseable Updated or Published timestamp do not receive a
fresh time.Now value on every poll; exclude them from bounded incremental polls
or derive a deterministic timestamp from stable entry content. Preserve the
existing UTC conversion for valid feed timestamps and ensure dateless entries
cannot repeatedly pass the poll window and inflate progress counters.
internal/syncer/rss_test.go (1)

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

Register the restore logic with t.Cleanup.

serveFeed returns a cleanup closure that each caller must defer. If a test forgets the defer, the global overrides of utility.AssertURLSafe and utility.PinnedHTTPClient leak into later tests in the package. t.Cleanup removes that risk and simplifies the call sites.

Also note that these package-level overrides prevent t.Parallel() in any test that uses this helper.

♻️ Proposed refactor
-func serveFeed(t *testing.T, body string) (*httptest.Server, func()) {
+func serveFeed(t *testing.T, body string) *httptest.Server {
 	t.Helper()
 	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		w.Header().Set("Content-Type", "application/rss+xml")
 		_, _ = w.Write([]byte(body))
 	}))
 
 	origAssert := utility.AssertURLSafe
 	origPinned := utility.PinnedHTTPClient
 	utility.AssertURLSafe = func(rawURL string) (string, string, error) {
 		return "127.0.0.1", "127.0.0.1", nil
 	}
 	utility.PinnedHTTPClient = func(hostname, resolvedIP string, timeout time.Duration) *http.Client {
 		return server.Client()
 	}
-	return server, func() {
+	t.Cleanup(func() {
 		utility.AssertURLSafe = origAssert
 		utility.PinnedHTTPClient = origPinned
 		server.Close()
-	}
+	})
+	return server
 }

Each caller then becomes server := serveFeed(t, testRSSFeed) without the defer cleanup() line.

🤖 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/rss_test.go` around lines 77 - 97, Update serveFeed to
register restoration of utility.AssertURLSafe, utility.PinnedHTTPClient, and
server.Close with t.Cleanup instead of returning a cleanup closure. Adjust every
caller to use only the returned server and remove its explicit cleanup defer;
keep tests using this helper non-parallel because the package-level overrides
remain shared.
internal/service/document/document_upload.go (1)

186-208: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Compare the hash before the storage upload.

The code uploads the blob and updates the row, and only then compares newHash with oldHash. For an unchanged entry this performs a full object write and a database write with no effect. RSS polls re-deliver unchanged entries on every cycle, so this is the common path.

Move the comparison before the Put call and skip both writes when the hash matches.

🤖 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/document/document_upload.go` around lines 186 - 208, In the
document update flow, compare newHash with oldHash before calling
storageImpl.Put and documentDAO.UpdateByID. When the hashes match, continue
immediately so unchanged RSS-delivered content skips both the storage and
database writes; retain the existing write and re-parse behavior for changed
content.
🤖 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 510-532: Update pruneOldSyncLogs to filter the candidate rows by
terminal sync status before ordering and deleting, excluding scheduled and
running records from the ids selected for deletion. Preserve the existing
connectorID/kbID scope and retention limits.
- Around line 396-406: Update the query building the sync log tasks to include
sync_logs.update_time in its Select projection before the existing Distinct and
Order calls, preserving the descending sort by update_time and satisfying
MySQL’s ONLY_FULL_GROUP_BY requirements.

In `@internal/service/document/document_upload.go`:
- Around line 191-198: In the document upload flow around storageImpl.Put,
validate that the resolved location from existing.Location is non-empty before
attempting the storage write. For nil or empty locations, append an error for
the current input.SemanticIdentifier and continue without calling
storageImpl.Put or proceeding with the document update; retain the existing
write and error handling for valid locations.
- Around line 227-230: Replace the unbounded existence-check loop in the
document upload flow with a location derived from the already-unique docID, and
use that value directly for storage so concurrent workers cannot resolve the
same filename or overwrite each other.
- Around line 236-248: Update the addFileFromKB failure path around
rollbackAddFileFromKBError so it also removes any File and File2Document rows
created before the failure. Extend the existing transactional cleanup used by
deleteDocRecordWithCounters, or reuse its transaction, ensuring document
deletion, counter rollback, and file-link cleanup succeed or fail together.

In `@internal/syncer/rss.go`:
- Around line 263-270: Update rssConnector.resolveStableKey so entries lacking
ID, Link, and Title receive a unique per-entry fallback instead of c.feedURL
alone. Include a stable discriminator derived from the entry content or entry
index while preserving the existing preferred-key order and trimmed values.
- Around line 79-91: Update atomXMLEntry.Content from a string to an inner-XML
container using xml:",innerxml", exposing its raw markup through Content.Inner;
then update the feed-entry construction to read atom.Content.Inner so nested
Atom content elements are preserved.

In `@internal/syncer/syncer.go`:
- Line 196: Update the failure handling around FinishTask in the recovered
executeTask flow to stop calling debug.Stack() after recovery, since it captures
the post-unwind stack; pass an empty trace or reuse the panic stack captured by
the recover handler near runErr instead.
- Around line 361-393: Guard the rss prune flow after connector.listEntryIDs
returns successfully: if entryIDs is empty, return without computing staleIDs or
calling DeleteDocuments. Preserve the existing retrieval-error no-op behavior
and ensure non-empty snapshots continue through the current retention and
deletion logic.
- Around line 195-200: Update the failure and timeout handling paths surrounding
FinishTask in the syncer task execution flow to reset the connector status to
schedule and reschedule the failed task, matching the normal retry behavior.
Apply this consistently to both runErr and timeout errors, while preserving the
existing failure logging and early-return behavior.
- Around line 327-329: Update the IncreaseDocs call in the sync flow to use the
number of returned upload results rather than int64(len(batch)). Preserve the
existing error aggregation and task update behavior, ensuring unchanged
documents skipped by UploadConnectorDocuments are excluded from both document
counters.

---

Nitpick comments:
In `@internal/service/document/document_upload.go`:
- Around line 186-208: In the document update flow, compare newHash with oldHash
before calling storageImpl.Put and documentDAO.UpdateByID. When the hashes
match, continue immediately so unchanged RSS-delivered content skips both the
storage and database writes; retain the existing write and re-parse behavior for
changed content.

In `@internal/syncer/rss_test.go`:
- Around line 77-97: Update serveFeed to register restoration of
utility.AssertURLSafe, utility.PinnedHTTPClient, and server.Close with t.Cleanup
instead of returning a cleanup closure. Adjust every caller to use only the
returned server and remove its explicit cleanup defer; keep tests using this
helper non-parallel because the package-level overrides remain shared.

In `@internal/syncer/rss.go`:
- Around line 258-261: Add a brief comment directly above the md5.Sum call in
rssConnector.buildDocumentID explaining that MD5 is intentionally used for
deterministic, non-security entry identifiers and to maintain parity with the
Python connector.
- Around line 290-297: Update resolveEntryTime so entries without a parseable
Updated or Published timestamp do not receive a fresh time.Now value on every
poll; exclude them from bounded incremental polls or derive a deterministic
timestamp from stable entry content. Preserve the existing UTC conversion for
valid feed timestamps and ensure dateless entries cannot repeatedly pass the
poll window and inflate progress counters.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 48afd3c4-3968-4528-8a81-7fd5d149feac

📥 Commits

Reviewing files that changed from the base of the PR and between 288be80 and 9d98506.

📒 Files selected for processing (6)
  • internal/dao/connector.go
  • internal/service/document/document_upload.go
  • internal/service/document/document_upload_helpers.go
  • internal/syncer/rss.go
  • internal/syncer/rss_test.go
  • internal/syncer/syncer.go

Comment thread internal/dao/connector.go
Comment on lines +396 to +406
Joins("JOIN connector ON sync_logs.connector_id = connector.id").
Joins("JOIN connector2kb ON sync_logs.connector_id = connector2kb.connector_id AND sync_logs.kb_id = connector2kb.kb_id").
Joins("JOIN knowledgebase ON sync_logs.kb_id = knowledgebase.id").
Where("connector.input_type = ?", "poll").
Where("connector.status = ?", string(entity.TaskStatusSchedule)).
Where("sync_logs.status = ?", string(entity.TaskStatusSchedule)).
Where("sync_logs.task_type = ?", taskType).
Where("sync_logs.update_date < NOW() - INTERVAL connector." + freqField + " MINUTE").
Distinct().
Order("sync_logs.update_time DESC").
Scan(&tasks).Error

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect SyncLogs entity columns and any existing DISTINCT+ORDER BY patterns.
fd -t f 'sync_log' internal/entity --exec cat -n {}
rg -n 'Distinct\(\)' --type=go -C4

Repository: infiniflow/ragflow

Length of output: 156


🏁 Script executed:

#!/bin/bash
set -u

echo "== files =="
git ls-files | rg '(^internal/dao/connector\.go$|entity.*sync|sync.*log|connector\.go$)' || true

echo "== connector outline =="
ast-grep outline internal/dao/connector.go --match 'ListDueTasks' --view expanded || true

echo "== relevant connector sections =="
sed -n '360,425p' internal/dao/connector.go
echo "== ListDueTasks signature and usages =="
rg -n 'ListDueTasks|freqField|Distince|Distinct\(\).*Order|Order\(.*Distinct' internal -g '*.go' -C3

echo "== entity files =="
fd -t f 'sync|log|connector' internal/entity internal | sed -n '1,120p'

Repository: infiniflow/ragflow

Length of output: 6568


🏁 Script executed:

#!/bin/bash
set -u

echo "== inspect SyncLogs candidate rows =="
python3 - <<'PY'
import os, re, pathlib
for p in pathlib.Path('internal').rglob('*.go'):
    txt=p.read_text(errors='ignore')
    if 'type SyncLogs struct' in txt or 'sync_logs' in txt.lower():
        print(f'--- {p}')
        for i,line in enumerate(txt.splitlines(),1):
            if 'type SyncLogs struct' in line or 'update_time' in line or 'update_date' in line or 'refresh_freq' in line or 'prune_freq' in line:
                print(f'{i}: {line}')
PY

echo "== compile-ish struct extraction =="
python3 - <<'PY'
from pathlib import Path
for p in Path('internal').rglob('*.go'):
    text=p.read_text(errors='ignore')
    s=text.find('type SyncLogs')
    if s==-1: continue
    e=text.find('\n}', s)
    print(f'--- {p}')
    print(text[s:e+2])
PY

Repository: infiniflow/ragflow

Length of output: 3508


🌐 Web query:

MySQL DISTINCT ORDER BY column not in SELECT list error 3065

💡 Result:

MySQL error 3065 occurs when a query uses both DISTINCT and ORDER BY while the ONLY_FULL_GROUP_BY SQL mode is enabled [1][2][3]. This error indicates that an expression in your ORDER BY clause is not present in your SELECT list [1][4]. The underlying reason for this restriction is to prevent nondeterministic results [3][5]. When you use DISTINCT, MySQL must first remove duplicate rows [3][5]. If your ORDER BY clause refers to a column not in the SELECT list, the server would have to make an arbitrary choice about which row's value to use for sorting after duplicates have been eliminated [3][6][5]. To ensure consistent, predictable behavior, MySQL requires that any column used for sorting in a DISTINCT query must be part of the SELECT list [3][6]. To resolve this error, you have two primary options: 1. Update the query (Recommended): Add the column(s) used in your ORDER BY clause to your SELECT list [7][8]. If you only need to sort by a specific value without retrieving it, you might alternatively consider using aggregate functions (such as MIN or MAX) in conjunction with a GROUP BY clause to define how to handle the data for each distinct group [9]. 2. Adjust the SQL Mode: If you cannot modify the query, you can disable the ONLY_FULL_GROUP_BY mode [2][10]. Note that this affects the entire session or server and may have implications for other queries [2][10]. To disable it for the current session, run: SET SESSION sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); To disable it globally, run: SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY','')); The ONLY_FULL_GROUP_BY mode has been enabled by default in MySQL since version 5.7.5 [6][11].

Citations:


Add update_time to the query projection before sorting it.

distinct() + ORDER BY sync_logs.update_time DESC fails on MySQL with ONLY_FULL_GROUP_BY when the order-by column is not selected. Include sync_logs.update_time in the Select list, or order by sync_logs.update_date.

🤖 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 396 - 406, Update the query building
the sync log tasks to include sync_logs.update_time in its Select projection
before the existing Distinct and Order calls, preserving the descending sort by
update_time and satisfying MySQL’s ONLY_FULL_GROUP_BY requirements.

Comment thread internal/dao/connector.go
Comment on lines +510 to +532
func (dao *ConnectorDAO) pruneOldSyncLogs(ctx context.Context, db *gorm.DB, connectorID, kbID string) error {
var total int64
if err := db.WithContext(ctx).Model(&entity.SyncLogs{}).
Where("connector_id = ? AND kb_id = ?", connectorID, kbID).
Count(&total).Error; err != nil {
return err
}
if total <= 100 {
return nil
}
var ids []string
if err := db.WithContext(ctx).Model(&entity.SyncLogs{}).
Where("connector_id = ? AND kb_id = ?", connectorID, kbID).
Order("update_time ASC").
Limit(70).
Pluck("id", &ids).Error; err != nil {
return err
}
if len(ids) == 0 {
return nil
}
return db.WithContext(ctx).Where("id IN ?", ids).Delete(&entity.SyncLogs{}).Error
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Retention pruning can delete an active task row.

pruneOldSyncLogs deletes the 70 oldest rows by update_time without a status filter. A row in scheduled or running state for the same connector/kb pair can be deleted if the history exceeds 100 rows. Exclude non-terminal rows from the delete set.

♻️ Proposed filter
 	if err := db.WithContext(ctx).Model(&entity.SyncLogs{}).
 		Where("connector_id = ? AND kb_id = ?", connectorID, kbID).
+		Where("status NOT IN ?", []string{string(entity.TaskStatusSchedule), string(entity.TaskStatusRunning)}).
 		Order("update_time ASC").
 		Limit(70).
 		Pluck("id", &ids).Error; err != nil {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func (dao *ConnectorDAO) pruneOldSyncLogs(ctx context.Context, db *gorm.DB, connectorID, kbID string) error {
var total int64
if err := db.WithContext(ctx).Model(&entity.SyncLogs{}).
Where("connector_id = ? AND kb_id = ?", connectorID, kbID).
Count(&total).Error; err != nil {
return err
}
if total <= 100 {
return nil
}
var ids []string
if err := db.WithContext(ctx).Model(&entity.SyncLogs{}).
Where("connector_id = ? AND kb_id = ?", connectorID, kbID).
Order("update_time ASC").
Limit(70).
Pluck("id", &ids).Error; err != nil {
return err
}
if len(ids) == 0 {
return nil
}
return db.WithContext(ctx).Where("id IN ?", ids).Delete(&entity.SyncLogs{}).Error
}
func (dao *ConnectorDAO) pruneOldSyncLogs(ctx context.Context, db *gorm.DB, connectorID, kbID string) error {
var total int64
if err := db.WithContext(ctx).Model(&entity.SyncLogs{}).
Where("connector_id = ? AND kb_id = ?", connectorID, kbID).
Count(&total).Error; err != nil {
return err
}
if total <= 100 {
return nil
}
var ids []string
if err := db.WithContext(ctx).Model(&entity.SyncLogs{}).
Where("connector_id = ? AND kb_id = ?", connectorID, kbID).
Where("status NOT IN ?", []string{string(entity.TaskStatusSchedule), string(entity.TaskStatusRunning)}).
Order("update_time ASC").
Limit(70).
Pluck("id", &ids).Error; err != nil {
return err
}
if len(ids) == 0 {
return nil
}
return db.WithContext(ctx).Where("id IN ?", ids).Delete(&entity.SyncLogs{}).Error
}
🤖 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 510 - 532, Update pruneOldSyncLogs to
filter the candidate rows by terminal sync status before ordering and deleting,
excluding scheduled and running records from the ids selected for deletion.
Preserve the existing connectorID/kbID scope and retention limits.

Comment on lines +191 to +198
location := ""
if existing.Location != nil {
location = *existing.Location
}
if err = storageImpl.Put(kb.ID, location, input.Blob); err != nil {
errMsgs = append(errMsgs, input.SemanticIdentifier+": "+err.Error())
continue
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Guard against an empty location before the storage write.

If existing.Location is nil or empty, the code calls storageImpl.Put(kb.ID, "", input.Blob). That writes the blob under an empty object key and silently corrupts the bucket state, while the document row is still updated with the new size and hash. Treat an empty location as an error for this document.

🛠️ Proposed fix
 			location := ""
 			if existing.Location != nil {
 				location = *existing.Location
 			}
+			if location == "" {
+				errMsgs = append(errMsgs, input.SemanticIdentifier+": existing document has no storage location")
+				continue
+			}
 			if err = storageImpl.Put(kb.ID, location, input.Blob); err != nil {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
location := ""
if existing.Location != nil {
location = *existing.Location
}
if err = storageImpl.Put(kb.ID, location, input.Blob); err != nil {
errMsgs = append(errMsgs, input.SemanticIdentifier+": "+err.Error())
continue
}
location := ""
if existing.Location != nil {
location = *existing.Location
}
if location == "" {
errMsgs = append(errMsgs, input.SemanticIdentifier+": existing document has no storage location")
continue
}
if err = storageImpl.Put(kb.ID, location, input.Blob); err != nil {
errMsgs = append(errMsgs, input.SemanticIdentifier+": "+err.Error())
continue
}
🤖 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/document/document_upload.go` around lines 191 - 198, In the
document upload flow around storageImpl.Put, validate that the resolved location
from existing.Location is non-empty before attempting the storage write. For nil
or empty locations, append an error for the current input.SemanticIdentifier and
continue without calling storageImpl.Put or proceeding with the document update;
retain the existing write and error handling for valid locations.

Comment on lines +227 to +230
location := filename
for storageImpl.ObjExist(kb.ID, location) {
location += "_"
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

The location loop is unbounded and races between workers.

for storageImpl.ObjExist(kb.ID, location) { location += "_" } issues one storage call per iteration with no upper bound. It also checks existence and then writes in a separate step. Two syncer workers that import the same feed title at the same time can resolve the same location and overwrite each other.

Derive the location from the already-unique docID instead.

🛠️ Proposed fix
-		location := filename
-		for storageImpl.ObjExist(kb.ID, location) {
-			location += "_"
-		}
+		location := docID + input.Extension
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
location := filename
for storageImpl.ObjExist(kb.ID, location) {
location += "_"
}
location := docID + input.Extension
🤖 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/document/document_upload.go` around lines 227 - 230, Replace
the unbounded existence-check loop in the document upload flow with a location
derived from the already-unique docID, and use that value directly for storage
so concurrent workers cannot resolve the same filename or overwrite each other.

Comment on lines +236 to +248
doc := s.newDatasetDocument(kb, tenantID, filename, location, string(filetype), kb.ParserConfig, src, int64(len(input.Blob)), input.Blob)
doc.ID = docID
if err = s.InsertDocument(doc); err != nil {
_ = storageImpl.Remove(kb.ID, location)
errMsgs = append(errMsgs, filename+": "+err.Error())
continue
}
if err = s.addFileFromKB(ctx, doc, kbFolder.ID, kb.TenantID); err != nil {
err = s.rollbackAddFileFromKBError(ctx, doc, kb.ID, err)
_ = storageImpl.Remove(kb.ID, location)
errMsgs = append(errMsgs, filename+": "+err.Error())
continue
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Inspect rollbackAddFileFromKBError and InsertDocument for counter updates.
ast-grep run --pattern $'func ($_ *DocumentService) rollbackAddFileFromKBError($$$) $_ {
  $$$
}' --lang go internal/service/document
ast-grep run --pattern $'func ($_ *DocumentService) InsertDocument($$$) $_ {
  $$$
}' --lang go internal/service/document

Repository: infiniflow/ragflow

Length of output: 2720


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files =="
git ls-files internal/service/document | sed -n '1,80p'

echo "== outline document_crud.go relevant methods =="
ast-grep outline internal/service/document/document_crud.go --match DocumentService --view expanded | sed -n '1,220p'

echo "== relevant document_crud.go lines =="
sed -n '260,445p' internal/service/document/document_crud.go

echo "== document_upload upload context lines =="
sed -n '200,270p' internal/service/document/document_upload.go
sed -n '430,455p' internal/service/document/document_upload.go

echo "== usages of rollbackAddFileFromKB and deleteDocRecordWithCounters =="
rg -n "rollbackAddFileFromKBError|deleteDocRecordWithCounters|InsertDocument" internal/service/document

Repository: infiniflow/ragflow

Length of output: 17707


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== addFileFromKB definition and related helpers =="
ast-grep run --pattern $'func ($_ *DocumentService) addFileFromKB($$$) $_ {
  $$$
}' --lang go internal/service/document/internal/service/document
rg -n "func \\(s \\*DocumentService\\) addFileFromKB|func .*cleanupFileReferences|func .*deleteDocEngineData" internal/service/document

echo "== addFileFromKB lines =="
ast-grep outline internal/service/document/document_crud.go --match addFileFromKB --view expanded || true
rg -n "addFileFromKB\\(" internal/service/document -C 8

echo "== document_id token assignment context in document_upload.go =="
rg -n "token|Token|GenerateToken|token:" internal/service/document/document_upload.go -C 4

Repository: infiniflow/ragflow

Length of output: 306


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== addFileFromKB occurrences =="
rg -n "addFileFromKB" internal/service/document -C 4

echo "== token generation occurrences in upload helpers =="
rg -n "GenerateToken|token_id|token:" internal/service/document/document_upload.go document_upload_helpers.go -C 3

Repository: infiniflow/ragflow

Length of output: 7573


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== addFileFromKB implementation =="
sed -n '330,380p' internal/service/document/document_upload.go

echo "== rollbackAddFileFromKBError implementation =="
sed -n '408,416p' internal/service/document/document_crud.go

echo "== deleteDocRecordWithCounters implementation =="
sed -n '379,390p' internal/service/document/document_crud.go

echo "== InsertDocument implementation =="
sed -n '298,319p' internal/service/document/document_crud.go

Repository: infiniflow/ragflow

Length of output: 3979


Roll back the added File and File2Document rows on addFileFromKB failure.

When InsertDocument succeeds and then addFileFromKB fails, rollbackAddFileFromKBError only deletes the Document row and KB counters. If the File and File2Document inserts already succeeded before the error, this leaves orphan file-manager records. Roll back those linkage rows too, preferably in the same transaction path as deleteDocRecordWithCounters.

🤖 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/document/document_upload.go` around lines 236 - 248, Update
the addFileFromKB failure path around rollbackAddFileFromKBError so it also
removes any File and File2Document rows created before the failure. Extend the
existing transactional cleanup used by deleteDocRecordWithCounters, or reuse its
transaction, ensuring document deletion, counter rollback, and file-link cleanup
succeed or fail together.

Comment thread internal/syncer/rss.go
Comment on lines +263 to +270
func (c *rssConnector) resolveStableKey(entry feedEntry) string {
for _, candidate := range []string{entry.ID, entry.Link, entry.Title, c.feedURL} {
if trimmed := strings.TrimSpace(candidate); trimmed != "" {
return trimmed
}
}
return c.feedURL
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

The feedURL fallback collapses distinct entries into one document ID.

If an entry has no ID, no Link, and no Title, resolveStableKey returns c.feedURL. Every such entry in the same feed then produces the same document ID. The importer treats them as one document, and each entry overwrites the previous content.

Include a per-entry discriminator in the fallback, for example a hash of the entry content or its index.

🤖 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/rss.go` around lines 263 - 270, Update
rssConnector.resolveStableKey so entries lacking ID, Link, and Title receive a
unique per-entry fallback instead of c.feedURL alone. Include a stable
discriminator derived from the entry content or entry index while preserving the
existing preferred-key order and trimmed values.

Comment thread internal/syncer/syncer.go
Comment on lines +195 to +200
if runErr != nil {
if finishErr := connectorDAO.FinishTask(context.Background(), db, task.ID, task.ConnectorID, entity.TaskStatusFail, runErr.Error(), string(debug.Stack())); finishErr != nil {
common.Error(fmt.Sprintf("Failed to mark task %s failed", task.ID), finishErr)
}
return
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

A failed task leaves the connector permanently stuck.

FinishTask updates the connector status only when the status is Done (see internal/dao/connector.go Lines 483-487). On the failure path here the connector keeps the running status, and no new task is scheduled. ListDueTasks requires connector.status = schedule, so this connector is never polled again. One transient feed error disables the connector until an operator intervenes.

Reset the connector to schedule and reschedule the task after a failure.

🛠️ Proposed fix
 	if runErr != nil {
 		if finishErr := connectorDAO.FinishTask(context.Background(), db, task.ID, task.ConnectorID, entity.TaskStatusFail, runErr.Error(), string(debug.Stack())); finishErr != nil {
 			common.Error(fmt.Sprintf("Failed to mark task %s failed", task.ID), finishErr)
 		}
+		if err := connectorDAO.RescheduleTask(context.Background(), db, task.ConnectorID, task.KbID, task.TaskType); err != nil {
+			common.Error(fmt.Sprintf("Failed to reschedule %s for connector %s", task.TaskType, task.ConnectorID), err)
+		}
 		return
 	}

Apply the same handling to the timeout path at Lines 188-194.

🤖 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 195 - 200, Update the failure and
timeout handling paths surrounding FinishTask in the syncer task execution flow
to reset the connector status to schedule and reschedule the failed task,
matching the normal retry behavior. Apply this consistently to both runErr and
timeout errors, while preserving the existing failure logging and early-return
behavior.

Comment thread internal/syncer/syncer.go
return
}
if runErr != nil {
if finishErr := connectorDAO.FinishTask(context.Background(), db, task.ID, task.ConnectorID, entity.TaskStatusFail, runErr.Error(), string(debug.Stack())); finishErr != nil {

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

debug.Stack() here captures the wrong stack.

At this point the panic has already been recovered and the stack has unwound. string(debug.Stack()) records the stack of executeTask, not the panic site. The useful trace is already embedded in runErr by the recover handler at Line 176. Pass an empty trace, or capture the stack separately in the recover handler and store it in a variable.

🤖 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` at line 196, Update the failure handling around
FinishTask in the recovered executeTask flow to stop calling debug.Stack() after
recovery, since it captures the post-unwind stack; pass an empty trace or reuse
the panic stack captured by the recover handler near runErr instead.

Comment thread internal/syncer/syncer.go
Comment on lines +327 to +329
if err := connectorDAO.IncreaseDocs(ctx, db, task.ID, maxUpdate, int64(len(batch)), strings.Join(errs, "\n"), int64(len(errs))); err != nil {
common.Error(fmt.Sprintf("Failed to increase docs for task %s", task.ID), err)
}

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

IncreaseDocs counts unchanged documents.

int64(len(batch)) counts every entry in the batch. UploadConnectorDocuments skips documents whose content hash is unchanged and does not return them in results. RSS feeds re-deliver the same entries on each poll, so new_docs_indexed and total_docs_indexed grow on every cycle even when nothing changed. Count the returned results instead.

🛠️ Proposed fix
-		if err := connectorDAO.IncreaseDocs(ctx, db, task.ID, maxUpdate, int64(len(batch)), strings.Join(errs, "\n"), int64(len(errs))); err != nil {
+		if err := connectorDAO.IncreaseDocs(ctx, db, task.ID, maxUpdate, int64(len(results)), strings.Join(errs, "\n"), int64(len(errs))); err != nil {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err := connectorDAO.IncreaseDocs(ctx, db, task.ID, maxUpdate, int64(len(batch)), strings.Join(errs, "\n"), int64(len(errs))); err != nil {
common.Error(fmt.Sprintf("Failed to increase docs for task %s", task.ID), err)
}
if err := connectorDAO.IncreaseDocs(ctx, db, task.ID, maxUpdate, int64(len(results)), strings.Join(errs, "\n"), int64(len(errs))); err != nil {
common.Error(fmt.Sprintf("Failed to increase docs for task %s", task.ID), err)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/syncer/syncer.go` around lines 327 - 329, Update the IncreaseDocs
call in the sync flow to use the number of returned upload results rather than
int64(len(batch)). Preserve the existing error aggregation and task update
behavior, ensuring unchanged documents skipped by UploadConnectorDocuments are
excluded from both document counters.

Comment thread internal/syncer/syncer.go
Comment on lines +361 to +393
entryIDs, err := connector.listEntryIDs(ctx)
if err != nil {
common.Warn(fmt.Sprintf("rss prune snapshot retrieval failed (connector_id=%s, kb_id=%s): %v", task.ConnectorID, task.KbID, err))
return nil
}

retain := make(map[string]bool, len(entryIDs)*2)
for _, entryID := range entryIDs {
retain[document.Hash128Hex([]byte(task.ConnectorID+":"+entryID))] = true
retain[document.Hash128Hex([]byte(task.KbID+":"+task.ConnectorID+":"+entryID))] = true
}

sourceType := fmt.Sprintf("%s/%s", task.Source, task.ConnectorID)
existingDocs, err := connectorDAO.ListDocumentsByKBAndSourceType(ctx, db, task.KbID, sourceType)
if err != nil {
return err
}
staleIDs := make([]string, 0)
for _, existingDoc := range existingDocs {
if !retain[existingDoc.ID] {
staleIDs = append(staleIDs, existingDoc.ID)
}
}

var removed int64
var errs []string
if len(staleIDs) > 0 {
deleted, err := document.NewDocumentService().DeleteDocuments(ctx, staleIDs, false, task.KbID, task.TenantID)
removed = int64(deleted)
if err != nil {
errs = append(errs, err.Error())
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

An empty feed deletes every connector document.

If listEntryIDs returns successfully with zero entries, retain is empty and every existing document for this connector becomes stale. DeleteDocuments then removes the whole imported corpus. A feed that is temporarily empty, or an XML change that yields no recognized items, causes irreversible data loss.

The code already treats a retrieval error as a safe no-op. Apply the same protection to an empty snapshot.

🛡️ Proposed guard
 	entryIDs, err := connector.listEntryIDs(ctx)
 	if err != nil {
 		common.Warn(fmt.Sprintf("rss prune snapshot retrieval failed (connector_id=%s, kb_id=%s): %v", task.ConnectorID, task.KbID, err))
 		return nil
 	}
+	if len(entryIDs) == 0 {
+		common.Warn(fmt.Sprintf("rss prune skipped: empty feed snapshot (connector_id=%s, kb_id=%s)", task.ConnectorID, task.KbID))
+		return nil
+	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
entryIDs, err := connector.listEntryIDs(ctx)
if err != nil {
common.Warn(fmt.Sprintf("rss prune snapshot retrieval failed (connector_id=%s, kb_id=%s): %v", task.ConnectorID, task.KbID, err))
return nil
}
retain := make(map[string]bool, len(entryIDs)*2)
for _, entryID := range entryIDs {
retain[document.Hash128Hex([]byte(task.ConnectorID+":"+entryID))] = true
retain[document.Hash128Hex([]byte(task.KbID+":"+task.ConnectorID+":"+entryID))] = true
}
sourceType := fmt.Sprintf("%s/%s", task.Source, task.ConnectorID)
existingDocs, err := connectorDAO.ListDocumentsByKBAndSourceType(ctx, db, task.KbID, sourceType)
if err != nil {
return err
}
staleIDs := make([]string, 0)
for _, existingDoc := range existingDocs {
if !retain[existingDoc.ID] {
staleIDs = append(staleIDs, existingDoc.ID)
}
}
var removed int64
var errs []string
if len(staleIDs) > 0 {
deleted, err := document.NewDocumentService().DeleteDocuments(ctx, staleIDs, false, task.KbID, task.TenantID)
removed = int64(deleted)
if err != nil {
errs = append(errs, err.Error())
}
}
entryIDs, err := connector.listEntryIDs(ctx)
if err != nil {
common.Warn(fmt.Sprintf("rss prune snapshot retrieval failed (connector_id=%s, kb_id=%s): %v", task.ConnectorID, task.KbID, err))
return nil
}
if len(entryIDs) == 0 {
common.Warn(fmt.Sprintf("rss prune skipped: empty feed snapshot (connector_id=%s, kb_id=%s)", task.ConnectorID, task.KbID))
return nil
}
retain := make(map[string]bool, len(entryIDs)*2)
for _, entryID := range entryIDs {
retain[document.Hash128Hex([]byte(task.ConnectorID+":"+entryID))] = true
retain[document.Hash128Hex([]byte(task.KbID+":"+task.ConnectorID+":"+entryID))] = true
}
sourceType := fmt.Sprintf("%s/%s", task.Source, task.ConnectorID)
existingDocs, err := connectorDAO.ListDocumentsByKBAndSourceType(ctx, db, task.KbID, sourceType)
if err != nil {
return err
}
staleIDs := make([]string, 0)
for _, existingDoc := range existingDocs {
if !retain[existingDoc.ID] {
staleIDs = append(staleIDs, existingDoc.ID)
}
}
var removed int64
var errs []string
if len(staleIDs) > 0 {
deleted, err := document.NewDocumentService().DeleteDocuments(ctx, staleIDs, false, task.KbID, task.TenantID)
removed = int64(deleted)
if err != nil {
errs = append(errs, err.Error())
}
}
🤖 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 361 - 393, Guard the rss prune flow
after connector.listEntryIDs returns successfully: if entryIDs is empty, return
without computing staleIDs or calling DeleteDocuments. Preserve the existing
retrieval-error no-op behavior and ensure non-empty snapshots continue through
the current retention and deletion logic.

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this comprehensive PR! The Go syncer was a significant gap in the Go mode, and this fills it well. Overall the implementation is solid — good architecture, good test coverage, and proper safety nets (SSRF-safe fetching, atomic task claiming, timeout enforcement, panic recovery).

A few observations and suggestions:

High-level feedback

  1. Legacy doc ID compatibility — nice touch handling both kb_id:connector_id:doc_id and connector_id:doc_id hash forms. This ensures existing indexed documents are found regardless of which format was used when they were first created.

  2. Atomic claiming — the ClaimTask pattern (WHERE status=Schedule, update to Running) correctly prevents duplicate execution across workers.

Potential issues

  1. connectorAutoParse("") returns true: Since "" != "0" && "" != "false" evaluates to true, an empty auto_parse field from the DB would enable auto-parsing. In Python, an empty/None value typically means no auto-parse. In practice the connector2kb table likely has a default of "1", so this may not manifest, but it is brittle. Consider making the default explicit:

    func connectorAutoParse(autoParse string) bool {
        return autoParse == "1" || autoParse == "true" || autoParse == "TRUE"
    }

    or at least treat empty as false.

  2. RescheduleTask transaction scope: pruneOldSyncLogs runs outside the transaction in RescheduleTask, while scheduleConnectorTask runs inside it. If two workers concurrently reschedule the same connector/kb pair, they could both pass the pruning check before either transaction commits. Consider moving pruneOldSyncLogs inside the transaction.

  3. executePruneTask swallows feed fetch errors: When listEntryIDs fails, it returns nil (success). This means the prune task is marked done and rescheduled with no deletions, which is conservative and won't cause data loss, but it silently skips a prune cycle. Consider whether this should fail the task to surface the error more visibly.

Minor suggestions

  1. Hash128Hex location: This is exported from internal/service/document/document_upload_helpers.go but is really a general-purpose utility (used in syncer and tests). Consider moving it to internal/utility/ for better cohesion.

  2. rss.go parseFeedTime: The layout list covers common formats. It might be worth adding ISO 8601 with fractional seconds (2006-01-02T15:04:05.000Z) and the comma-variant of RFC1123 (Mon, 02 Jan 2006 15:04:05 GMT), which some feeds use.

  3. Test TestHash128HexParity: The test hardcodes a single expected hash. Consider adding a table-driven test with a few more inputs to guard against xxh3 library version changes.

Summary

The PR is well-structured, mirrors the Python reference faithfully, and includes meaningful tests. The issues above are all edge cases or style nits — none are blockers. Nice work!

@wangq8

wangq8 commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator

@Haruko386 already handle it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants