Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(datasource): retain retry cursors on ingestion failure (#3852)
诉说晚秋0645a572e65d
diff --git a/internal/application/service/datasource_ingest_ack_helpers_test.go b/internal/application/service/datasource_ingest_ack_helpers_test.gonew file mode 100644index 000000000..d1fac9621--- /dev/null+++ b/internal/application/service/datasource_ingest_ack_helpers_test.go@@ -0,0 +1,129 @@+package service++import (+ "context"+ "encoding/json"+ "fmt"+ "mime/multipart"+ "strconv"+ "testing"++ "github.com/Tencent/WeKnora/internal/datasource"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/hibiken/asynq"+ "github.com/stretchr/testify/require"+)++type ingestAckConnector struct {+ deletedItemConnector+ items []types.FetchedItem+ starts []int+}++func ingestAckCursor(offset int) *types.SyncCursor {+ return &types.SyncCursor{ConnectorCursor: map[string]interface{}{"offset": offset}}+}++func ingestAckOffset(cursor *types.SyncCursor) int {+ if cursor == nil {+ return 0+ }+ offset, _ := strconv.Atoi(fmt.Sprint(cursor.ConnectorCursor["offset"]))+ return offset+}++func (c *ingestAckConnector) FetchIncremental(+ _ context.Context, _ *types.DataSourceConfig, cursor *types.SyncCursor,+) ([]types.FetchedItem, *types.SyncCursor, error) {+ offset := ingestAckOffset(cursor)+ c.starts = append(c.starts, offset)+ return c.items[offset:], ingestAckCursor(len(c.items)), nil+}++type ingestAckStream struct{ *ingestAckConnector }++func (c *ingestAckStream) FetchStream(+ ctx context.Context, cfg *types.DataSourceConfig, cursor *types.SyncCursor, h datasource.StreamHandler,+) (*types.SyncCursor, error) {+ items, next, _ := c.FetchIncremental(ctx, cfg, cursor)+ offset := ingestAckOffset(cursor)+ for i, item := range items {+ if err := h.Emit(ctx, item); err != nil {+ return nil, err+ }+ if err := h.Checkpoint(ctx, ingestAckCursor(offset+i+1)); err != nil {+ return nil, err+ }+ }+ return next, nil+}++// ignoringIngestAckStream exercises the service's final cursor guard when a+// connector fails to propagate a handler error.+type ignoringIngestAckStream struct{ *ingestAckConnector }++func (c *ignoringIngestAckStream) FetchStream(+ ctx context.Context, cfg *types.DataSourceConfig, cursor *types.SyncCursor, h datasource.StreamHandler,+) (*types.SyncCursor, error) {+ items, next, _ := c.FetchIncremental(ctx, cfg, cursor)+ for i, item := range items {+ _ = h.Emit(ctx, item)+ _ = h.Checkpoint(ctx, ingestAckCursor(i+1))+ }+ return next, nil+}++type ingestAckKnowledgeService struct {+ *sweepFakeKS+ failure error+ stored map[string]bool+ attempted []string+}++func (s *ingestAckKnowledgeService) CreateKnowledgeFromFile(+ _ context.Context, _ string, _ *multipart.FileHeader, metadata map[string]string,+ _ *bool, _ string, _ []string, _ string, _ *types.KnowledgeProcessOverrides,+) (*types.Knowledge, error) {+ id := metadata["external_id"]+ s.attempted = append(s.attempted, id)+ if id == "blocked" && s.failure != nil {+ return nil, s.failure+ }+ s.stored[id] = true+ return &types.Knowledge{ID: id}, nil+}++type ingestAckHarness struct {+ *syncDeletionHarness+ connector *ingestAckConnector+ sink *ingestAckKnowledgeService+ task *asynq.Task+}++func newIngestAckHarness(t *testing.T, streaming bool) *ingestAckHarness {+ t.Helper()+ h := newSyncDeletionHarness(t, false, "source-ack", "log-ack", nil, nil)+ h.ds.SyncMode = types.SyncModeIncremental+ cursor, err := ingestAckCursor(0).ToJSON()+ require.NoError(t, err)+ h.ds.LastSyncCursor = cursor+ c := &ingestAckConnector{items: []types.FetchedItem{+ {ExternalID: "first", FileName: "first.md", Content: []byte("first")},+ {ExternalID: "blocked", FileName: "blocked.md", Content: []byte("blocked")},+ {ExternalID: "last", FileName: "last.md", Content: []byte("last")},+ }}+ var connector datasource.Connector = c+ if streaming {+ connector = &ingestAckStream{c}+ }+ require.NoError(t, h.svc.connectorRegistry.Register(connector))+ sink := &ingestAckKnowledgeService{+ sweepFakeKS: &sweepFakeKS{repo: &deletionLookupKnowledgeRepo{}}, stored: map[string]bool{},+ }+ h.svc.knowledgeService = sink+ payload, err := json.Marshal(types.DataSourceSyncPayload{+ DataSourceID: h.ds.ID, TenantID: h.ds.TenantID, SyncLogID: h.syncLogID,+ })+ require.NoError(t, err)+ return &ingestAckHarness{h, c, sink, asynq.NewTask(types.TypeDataSourceSync, payload)}+}diff --git a/internal/application/service/datasource_ingest_ack_test.go b/internal/application/service/datasource_ingest_ack_test.gonew file mode 100644index 000000000..cca0d7cac--- /dev/null+++ b/internal/application/service/datasource_ingest_ack_test.go@@ -0,0 +1,165 @@+package service++import (+ "context"+ "errors"+ "testing"++ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestProcessSyncIngestFailureRetainsRetryCursor(t *testing.T) {+ for _, streaming := range []bool{false, true} {+ name := "batch"+ if streaming {+ name = "streaming"+ }+ t.Run(name, func(t *testing.T) {+ h := newIngestAckHarness(t, streaming)+ failure := errors.New("private storage diagnostic")+ h.sink.failure = failure+ err := h.svc.ProcessSync(context.Background(), h.task)+ require.ErrorIs(t, err, failure)+ log := h.syncLogRepo.logs[h.syncLogID]+ assert.Equal(t, types.SyncLogStatusFailed, log.Status)+ assert.Equal(t, 1, log.ItemsFailed)+ assert.NotContains(t, log.ErrorMessage, failure.Error())+ cursor, parseErr := h.ds.ParseSyncCursor()+ require.NoError(t, parseErr)+ wantOffset := 0+ if streaming {+ wantOffset = 1+ }+ assert.Equal(t, wantOffset, ingestAckOffset(cursor))+ assert.True(t, h.sink.stored["first"])+ assert.False(t, h.sink.stored["blocked"])+ assert.Equal(t, !streaming, h.sink.stored["last"])++ h.sink.failure = nil+ require.NoError(t, h.svc.ProcessSync(context.Background(), h.task))+ assert.Equal(t, []int{0, wantOffset}, h.connector.starts)+ assert.Len(t, h.sink.stored, 3)+ assert.Equal(t, types.SyncLogStatusSuccess, h.syncLogRepo.logs[h.syncLogID].Status)+ cursor, parseErr = h.ds.ParseSyncCursor()+ require.NoError(t, parseErr)+ assert.Equal(t, 3, ingestAckOffset(cursor))+ require.NoError(t, h.svc.ProcessSync(context.Background(), h.task))+ assert.Zero(t, h.syncLogRepo.logs[h.syncLogID].ItemsTotal)+ })+ }+}++func TestStreamIngestFailureCannotBeCheckpointed(t *testing.T) {+ h := newIngestAckHarness(t, true)+ failure := errors.New("storage unavailable")+ h.sink.failure = failure+ handler := newStreamHandler(h.svc, h.ds, &types.SyncResult{}, h.syncLogRepo.logs[h.syncLogID])+ require.NoError(t, handler.Emit(context.Background(), h.connector.items[0]))+ require.NoError(t, handler.Checkpoint(context.Background(), ingestAckCursor(1)))+ require.ErrorIs(t, handler.Emit(context.Background(), h.connector.items[1]), failure)+ require.ErrorIs(t, handler.Checkpoint(context.Background(), ingestAckCursor(2)), failure)+ require.ErrorIs(t, handler.Emit(context.Background(), h.connector.items[2]), failure)+ cursor, err := h.ds.ParseSyncCursor()+ require.NoError(t, err)+ assert.Equal(t, 1, ingestAckOffset(cursor))+ assert.Equal(t, []string{"first", "blocked"}, h.sink.attempted)+}++func TestStreamIngestAcknowledgementPreservesSoftOutcomes(t *testing.T) {+ tests := []struct {+ name string+ item types.FetchedItem+ createErr error+ skipped, failed int+ }{+ {+ name: "fetch failure",+ item: types.FetchedItem{Metadata: map[string]string{"error": "fetch unavailable"}},+ failed: 1,+ },+ {name: "empty", item: types.FetchedItem{}, skipped: 1},+ {+ name: "duplicate",+ item: types.FetchedItem{Content: []byte("doc"), FileName: "doc.md"},+ createErr: &types.DuplicateKnowledgeError{Message: "duplicate"},+ skipped: 1,+ },+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ h := newIngestAckHarness(t, true)+ h.svc.knowledgeService = &sweepFakeKS{repo: &deletionLookupKnowledgeRepo{}, createErr: tt.createErr}+ result := &types.SyncResult{}+ handler := newStreamHandler(h.svc, h.ds, result, h.syncLogRepo.logs[h.syncLogID])+ require.NoError(t, handler.Emit(context.Background(), tt.item))+ require.NoError(t, handler.Checkpoint(context.Background(), ingestAckCursor(1)))+ assert.Equal(t, tt.skipped, result.Skipped)+ assert.Equal(t, tt.failed, result.Failed)+ })+ }+}++func TestProcessSyncIngestErrorCannotBeIgnoredByConnector(t *testing.T) {+ h := newIngestAckHarness(t, true)+ failure := errors.New("private storage diagnostic")+ h.sink.failure = failure+ require.NoError(t, h.svc.connectorRegistry.Register(&ignoringIngestAckStream{h.connector}))+ require.ErrorIs(t, h.svc.ProcessSync(context.Background(), h.task), failure)+ cursor, err := h.ds.ParseSyncCursor()+ require.NoError(t, err)+ assert.Equal(t, 1, ingestAckOffset(cursor))+ assert.Equal(t, []string{"first", "blocked"}, h.sink.attempted)+ log := h.syncLogRepo.logs[h.syncLogID]+ assert.Equal(t, types.SyncLogStatusFailed, log.Status)+ assert.NotContains(t, log.ErrorMessage, failure.Error())+}++func TestProcessSyncIngestAcknowledgementKeepsFetchFailuresPartial(t *testing.T) {+ for _, streaming := range []bool{false, true} {+ h := newIngestAckHarness(t, streaming)+ h.connector.items[1] = types.FetchedItem{+ ExternalID: "blocked", Metadata: map[string]string{"error": "fetch failed"},+ }+ require.NoError(t, h.svc.ProcessSync(context.Background(), h.task))+ log := h.syncLogRepo.logs[h.syncLogID]+ assert.Equal(t, types.SyncLogStatusPartial, log.Status)+ assert.Equal(t, 2, log.ItemsCreated)+ assert.Equal(t, 1, log.ItemsFailed)+ cursor, err := h.ds.ParseSyncCursor()+ require.NoError(t, err)+ assert.Equal(t, 3, ingestAckOffset(cursor))+ }+}++func TestStreamIngestFailureIndependentOfErrorSampleLimit(t *testing.T) {+ h := newIngestAckHarness(t, true)+ failure := errors.New("storage unavailable")+ h.sink.failure = failure+ result := &types.SyncResult{Errors: make([]types.SyncItemError, maxSyncResultErrors)}+ handler := newStreamHandler(h.svc, h.ds, result, h.syncLogRepo.logs[h.syncLogID])+ require.ErrorIs(t, handler.Emit(context.Background(), h.connector.items[1]), failure)+ require.ErrorIs(t, handler.Checkpoint(context.Background(), ingestAckCursor(2)), failure)+ assert.Len(t, result.Errors, maxSyncResultErrors)+ assert.Equal(t, 1, result.Failed)+}++func TestStreamEmbeddedImageFailureRetainsCursor(t *testing.T) {+ h := newIngestAckHarness(t, true)+ failure := errors.New("image storage unavailable")+ h.svc.knowledgeService = &sweepFakeKS{repo: &deletionLookupKnowledgeRepo{}, createErr: failure}+ result := &types.SyncResult{}+ handler := newStreamHandler(h.svc, h.ds, result, h.syncLogRepo.logs[h.syncLogID])+ item := types.FetchedItem{+ Content: []byte("image"), FileName: "image.png",+ Metadata: map[string]string{"embedded_image": "true"},+ }+ require.ErrorIs(t, handler.Emit(context.Background(), item), failure)+ require.ErrorIs(t, handler.Checkpoint(context.Background(), ingestAckCursor(1)), failure)+ require.Equal(t, 1, result.Failed)+ require.Zero(t, result.Skipped)+ cursor, err := h.ds.ParseSyncCursor()+ require.NoError(t, err)+ require.Zero(t, ingestAckOffset(cursor))+}diff --git a/internal/application/service/datasource_ingest_error.go b/internal/application/service/datasource_ingest_error.gonew file mode 100644index 000000000..4d2b2e748--- /dev/null+++ b/internal/application/service/datasource_ingest_error.go@@ -0,0 +1,15 @@+package service++// dataSourceIngestError preserves the cause for retries without exposing storage+// diagnostics in the user-facing sync log. Details are logged at the ingest site.+type dataSourceIngestError struct {+ cause error+}++func (e *dataSourceIngestError) Error() string {+ return "Ingest failed; see server logs"+}++func (e *dataSourceIngestError) Unwrap() error {+ return e.cause+}diff --git a/internal/application/service/datasource_ingest_rejection_test.go b/internal/application/service/datasource_ingest_rejection_test.gonew file mode 100644index 000000000..f74a08bc9--- /dev/null+++ b/internal/application/service/datasource_ingest_rejection_test.go@@ -0,0 +1,119 @@+package service++import (+ "context"+ "errors"+ "fmt"+ "testing"++ werrors "github.com/Tencent/WeKnora/internal/errors"+ "github.com/Tencent/WeKnora/internal/types"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestProcessSyncPermanentRejectionsAdvanceCursor(t *testing.T) {+ cases := []struct {+ streaming, onlyRejected bool+ extension string+ }{+ {false, false, "mp4"},+ {false, true, "mp4"},+ {true, false, "mp4"},+ {true, true, "mp4"},+ {false, false, "unsupported"},+ {false, true, "unsupported"},+ {true, false, "unsupported"},+ {true, true, "unsupported"},+ }+ for _, tc := range cases {+ name := fmt.Sprintf("stream=%v/onlyRejected=%v/%s", tc.streaming, tc.onlyRejected, tc.extension)+ t.Run(name, func(t *testing.T) {+ h := newIngestAckHarness(t, tc.streaming)+ h.connector.items[1].FileName = "blocked." + tc.extension+ if tc.onlyRejected {+ h.connector.items = h.connector.items[1:2]+ }+ require.NoError(t, h.svc.ProcessSync(context.Background(), h.task))+ log := h.syncLogRepo.logs[h.syncLogID]+ assert.Equal(t, types.SyncLogStatusPartial, log.Status)+ assert.Equal(t, 1, log.ItemsFailed)+ assert.Equal(t, len(h.connector.items)-1, log.ItemsCreated)+ assert.Contains(t, string(log.Result), "unsupported_file_type")+ assert.Equal(t, types.DataSourceStatusActive, h.ds.Status)+ assert.False(t, h.sink.stored["blocked"])+ cursor, err := h.ds.ParseSyncCursor()+ require.NoError(t, err)+ assert.Equal(t, len(h.connector.items), ingestAckOffset(cursor))+ require.NoError(t, h.svc.ProcessSync(context.Background(), h.task))+ assert.Zero(t, h.syncLogRepo.logs[h.syncLogID].ItemsTotal)+ })+ }+}++func TestProcessSyncRecoverableRejectionsRetainCursor(t *testing.T) {+ failures := []error{+ werrors.NewBadRequestError("storage configuration missing"),+ errors.New("storage quota exhausted"),+ errors.New("database unavailable"),+ errors.New("network timeout"),+ }+ for _, streaming := range []bool{false, true} {+ for _, failure := range failures {+ t.Run(fmt.Sprintf("stream=%v/%s", streaming, failure), func(t *testing.T) {+ h := newIngestAckHarness(t, streaming)+ h.connector.items = h.connector.items[1:2]+ h.sink.failure = failure+ require.ErrorIs(t, h.svc.ProcessSync(context.Background(), h.task), failure)+ cursor, err := h.ds.ParseSyncCursor()+ require.NoError(t, err)+ assert.Zero(t, ingestAckOffset(cursor))+ h.sink.failure = nil+ require.NoError(t, h.svc.ProcessSync(context.Background(), h.task))+ assert.True(t, h.sink.stored["blocked"])+ })+ }+ }+}++func TestProcessSyncWrappedUnsupportedRejection(t *testing.T) {+ for _, streaming := range []bool{false, true} {+ h := newIngestAckHarness(t, streaming)+ h.connector.items = h.connector.items[1:2]+ h.sink.failure = fmt.Errorf("import rejected: %w", ErrInvalidFileType)+ require.NoError(t, h.svc.ProcessSync(context.Background(), h.task))+ assert.Equal(t, types.SyncLogStatusPartial, h.syncLogRepo.logs[h.syncLogID].Status)+ cursor, err := h.ds.ParseSyncCursor()+ require.NoError(t, err)+ assert.Equal(t, 1, ingestAckOffset(cursor))+ }+}++func TestProcessSyncPermanentRejectionsDoNotHideFetchFailures(t *testing.T) {+ for _, streaming := range []bool{false, true} {+ h := newIngestAckHarness(t, streaming)+ h.connector.items = []types.FetchedItem{+ {ExternalID: "unsupported", FileName: "video.mp4", Content: []byte("video")},+ {ExternalID: "failed", Metadata: map[string]string{"error": "fetch failed"}},+ }+ require.ErrorContains(t, h.svc.ProcessSync(context.Background(), h.task), "all fetched items failed")+ assert.Equal(t, types.SyncLogStatusFailed, h.syncLogRepo.logs[h.syncLogID].Status)+ }+}++func TestProcessSyncPermanentRejectionsBeyondErrorSampleLimit(t *testing.T) {+ for _, streaming := range []bool{false, true} {+ h := newIngestAckHarness(t, streaming)+ h.connector.items = make([]types.FetchedItem, maxSyncResultErrors+1)+ for i := range h.connector.items {+ h.connector.items[i] = types.FetchedItem{+ ExternalID: fmt.Sprint(i), FileName: "video.mp4", Content: []byte("video"),+ }+ }+ require.NoError(t, h.svc.ProcessSync(context.Background(), h.task))+ assert.Equal(t, len(h.connector.items), h.syncLogRepo.logs[h.syncLogID].ItemsFailed)+ cursor, err := h.ds.ParseSyncCursor()+ require.NoError(t, err)+ assert.Equal(t, len(h.connector.items), ingestAckOffset(cursor))+ }+}diff --git a/internal/application/service/datasource_service.go b/internal/application/service/datasource_service.goindex 660aaf5c6..9ce20f44b 100644--- a/internal/application/service/datasource_service.go+++ b/internal/application/service/datasource_service.go@@ -790,13 +790,26 @@ func (s *DataSourceService) ProcessSync(ctx context.Context, task *asynq.Task) e// Auto-tag: find or create a tag for this data source so synced items are easily identifiableautoTagIDs := s.resolveAutoTagIDs(ctx, ds)+ var ingestErr error+ permanentFailures := 0for _, item := range items {item := item- s.applyFetchedItem(withKBActivitySuppressed(ctx), ds, &item, autoTagIDs, result)+ err := s.applyFetchedItem(withKBActivitySuppressed(ctx), ds, &item, autoTagIDs, result)+ if errors.Is(err, ErrInvalidFileType) {+ permanentFailures+++ } else if err != nil && ingestErr == nil {+ ingestErr = err+ }}resultJSON, _ := result.ToJSON()- if err := allFetchedItemsFailedError(result); err != nil {+ if ingestErr != nil {+ // Keep the previous cursor so a retry can recover items the sink did not accept.+ s.updateSyncRunResult(ctx, ds, syncLog, result, resultJSON,+ types.SyncLogStatusFailed, ingestErr.Error(), wasPaused)+ return ingestErr+ }+ if err := allFetchedItemsFailedError(result); err != nil && result.Failed != permanentFailures {logger.Errorf(ctx, "data source sync failed while processing fetched items: %v", err)s.updateSyncRunResult(ctx, ds, syncLog, result, resultJSON, types.SyncLogStatusFailed, err.Error(), wasPaused)return err@@ -894,20 +907,21 @@ func fetchFailureSyncError(item *types.FetchedItem, rawMsg string) types.SyncIte// applyFetchedItem writes a single fetched item into the knowledge base and// updates result counters. It is the shared core of the batch loop and the// streaming handler so item classification (deleted / empty / ingest outcome)-// stays identical across both fetch paths.+// stays identical across both fetch paths. Unexpected ingestion errors are+// returned so callers do not acknowledge a cursor beyond an unaccepted item.func (s *DataSourceService) applyFetchedItem(ctx context.Context, ds *types.DataSource, item *types.FetchedItem,tagIDs []string, result *types.SyncResult,-) {+) error {if item.IsDeleted {if !ds.SyncDeletions {// Sync deletion disabled: neither count nor delete.- return+ return nil}if item.ExternalID == "" {logger.Warnf(ctx, "skipping deletion for item %q: empty external_id", item.Title)result.Skipped++- return+ return nil}// Perform real KB deletion, scoped to items owned by this data source// so identical external IDs from different data sources cannot collide.@@ -925,13 +939,13 @@ func (s *DataSourceService) applyFetchedItem(Code: "deletion_lookup_failed",Message: "Failed to look up the item before deletion; see server logs",})- return+ return nil}if existing == nil {// Deletion is idempotent: the source item may already have been// removed manually or by an earlier sync.result.Skipped++- return+ return nil}if deleteErr := s.knowledgeService.DeleteKnowledge(ctx, existing.ID); deleteErr != nil {// The cursor is already past this item, so a failed deletion normally@@ -946,7 +960,7 @@ func (s *DataSourceService) applyFetchedItem(Code: "deletion_failed",Message: "Deletion failed; see server logs",})- return+ return nil}if herr := repo.HardDeleteKnowledge(ctx, ds.TenantID, existing.ID); herr != nil {result.Failed++@@ -958,10 +972,10 @@ func (s *DataSourceService) applyFetchedItem(Code: "deletion_failed",Message: "Deletion failed; see server logs",})- return+ return nil}result.Deleted++- return+ return nil}if len(item.Content) == 0 && item.URL == "" {@@ -974,7 +988,7 @@ func (s *DataSourceService) applyFetchedItem(logger.Infof(ctx, "skipping item %q (external_id=%s): no content or URL", item.Title, item.ExternalID)result.Skipped++}- return+ return nil}isUpdate, err := s.ingestItem(ctx, ds, item, tagIDs)@@ -985,6 +999,12 @@ func (s *DataSourceService) applyFetchedItem(// Duplicate file/URL is not a failure — count as skipped.logger.Infof(ctx, "item %q (external_id=%s) already exists, skipping", item.Title, item.ExternalID)result.Skipped+++ case errors.Is(err, ErrInvalidFileType):+ result.Failed+++ recordSyncError(result, types.SyncItemError{+ Title: item.Title, Code: "unsupported_file_type", Message: "Unsupported file type",+ })+ return errdefault:logger.Warnf(ctx, "failed to ingest item %q (external_id=%s): %v", item.Title, item.ExternalID, err)result.Failed++@@ -993,12 +1013,14 @@ func (s *DataSourceService) applyFetchedItem(Code: "ingest_failed",Message: "Ingest failed; see server logs",})+ return &dataSourceIngestError{cause: err}}} else if isUpdate {result.Updated++} else {result.Created++}+ return nil}// streamStartCursor decides which cursor a streaming fetch should resume from.@@ -1078,30 +1100,43 @@ func (s *DataSourceService) clearResyncMarker(ctx context.Context, ds *types.Dat// Emit ingests each item as it arrives (bounding memory) and Checkpoint persists// the connector cursor plus live progress counts at page boundaries.type streamSyncHandler struct {- svc *DataSourceService- ds *types.DataSource- tagIDs []string- result *types.SyncResult- syncLog *types.SyncLog+ svc *DataSourceService+ ds *types.DataSource+ tagIDs []string+ result *types.SyncResult+ syncLog *types.SyncLog+ ingestErr error+ // Count separately from the capped error samples; permanent rejections may+ // advance a cursor even when every item in this round is unsupported.+ permanentFailures int}-// Emit ingests one streamed item. A canceled context aborts the stream so the-// connector stops fetching; per-item ingest failures are recorded in result and-// do NOT abort (matching the batch loop, which never fails the whole sync for-// one bad document).+// Emit ingests one streamed item. Unexpected ingestion errors abort the stream+// before the connector can checkpoint past the failed item.func (h *streamSyncHandler) Emit(ctx context.Context, item types.FetchedItem) error {+ if h.ingestErr != nil {+ return h.ingestErr+ }if err := ctx.Err(); err != nil {return err}h.result.Total++- h.svc.applyFetchedItem(withKBActivitySuppressed(ctx), h.ds, &item, h.tagIDs, h.result)- return nil+ err := h.svc.applyFetchedItem(withKBActivitySuppressed(ctx), h.ds, &item, h.tagIDs, h.result)+ if errors.Is(err, ErrInvalidFileType) {+ h.permanentFailures+++ return nil+ }+ h.ingestErr = err+ return h.ingestErr}// Checkpoint persists the connector cursor onto the data source and mirrors the// running counts into the sync log so progress survives a crash and the UI can// reflect a long sync mid-flight instead of jumping from 0 to done.func (h *streamSyncHandler) Checkpoint(ctx context.Context, cursor *types.SyncCursor) error {+ if h.ingestErr != nil {+ return h.ingestErr+ }if cursor == nil {return nil}@@ -1203,6 +1238,10 @@ func (s *DataSourceService) processSyncStreaming(}nextCursor, fetchErr := streamingFetch(ctx, sc, config, forceFull, startCursor, fullBaseline, handler)+ if handler.ingestErr != nil {+ // Do not publish a final cursor even if the connector ignored an Emit error.+ fetchErr = handler.ingestErr+ }if fetchErr != nil {// Progress so far is already checkpointed onto ds.LastSyncCursor; leave// it in place so the Asynq retry resumes from there. Persist counts.@@ -1214,7 +1253,7 @@ func (s *DataSourceService) processSyncStreaming(}resultJSON, _ := result.ToJSON()- if err := allFetchedItemsFailedError(result); err != nil {+ if err := allFetchedItemsFailedError(result); err != nil && result.Failed != handler.permanentFailures {logger.Errorf(ctx, "streaming sync failed while processing fetched items: %v", err)s.updateSyncRunResult(ctx, ds, syncLog, result, resultJSON, types.SyncLogStatusFailed, err.Error(), wasPaused)return err@@ -1382,6 +1421,12 @@ func (s *DataSourceService) validateDataSourceConfig(ctx context.Context, ds *ty//// Returns (isUpdate, error) — isUpdate is true when an existing item was replaced.func (s *DataSourceService) ingestItem(ctx context.Context, ds *types.DataSource, item *types.FetchedItem, tagIDs []string) (bool, error) {+ // Reject unsupported source files before replacing an existing document.+ // Do not classify generic BadRequest errors: missing storage configuration+ // also uses that type and must remain retryable.+ if len(item.Content) > 0 && (IsVideoType(getFileType(item.FileName)) || !isValidFileType(item.FileName)) {+ return false, ErrInvalidFileType+ }// Channel decides the knowledge "source" label shown in the UI. Prefer the// connector-supplied metadata["channel"] (e.g. Feishu Drive sets it to// "feishu" so Drive docs share the wiki's "飞书" label instead of showing