8000 [Bug]: Dataset mind map gets stuck retrying once the dataset is large · Issue #22626 · infiniflow/ragflow · GitHub
[go: up one dir, main page]

Skip to content

[Bug]: Dataset mind map gets stuck retrying once the dataset is large #22626

Open

Description

@thirstyraven

Self Checks

  • I have searched for existing issues search for existing issues, including closed ones.
  • I confirm that I am using English to submit this report (Language Policy).
  • Non-english title submitions will be closed directly ( 非英文标题的提交将会被直接关闭 ) (Language Policy).
  • Please do not modify this template :) and fill in all the required fields.

RAGFlow workspace code commit ID

91c702e

RAGFlow image version

91c702e(v1.0.0~274)

Other environment information

- Hardware parameters: 6 vCPU, 7 GB RAM (test VM)
- OS type: Fedora Linux, Docker
- Others: MySQL 8.0.40 (innodb_lock_wait_timeout 50), Infinity 0.7.5, Go 1.27.4

Actual behavior

Once a dataset's mind map gets large, merging a newly parsed document into it never finishes: the merge restarts every few minutes, Infinity stays busy, and documents that finish parsing in the meantime never get their merge queued. On our dataset (about 180k dataset-level rows) one merge was retried 650+ times over three days.

Before writing, the structure merge reads every dataset-level row of the dataset, 500 at a time:

const pageSize = 500
stale := map[string]bool{}
for offset := 0; ; offset += pageSize {
res, err := eng.Search(ctx, &types.SearchRequest{
IndexNames: []string{baseName},
KbIDs: []string{kb},
SelectFields: []string{
"id", "compile_kwd", "compilation_template_ids", "compilation_template_kind_kwd",
"type_kwd", "knowledge_graph_kwd", "name_kwd", "entity_type_kwd", "from_entity_kwd", "to_entity_kwd",
"content_with_weight", "source_doc_ids", "source_chunk_ids",
},
Filter: map[string]interface{}{
"kb_id": kb,
"scope_kwd": "dataset",
"compile_kwd": compileKinds,
"knowledge_graph_kwd": []string{"entity", "relation"},
},
Offset: offset,
Limit: pageSize,
})

That read runs inside withWriteLock:

if err := c.withWriteLock(ctx, kb, token, func() error {
return c.mergeStructureDataset(ctx, tenant, kb, incoming)
}); err != nil {

which holds SELECT ... FOR UPDATE on the dataset's knowledge_compile_docs row for the whole read:

return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
row := entity.KnowledgeCompileDataset{
DatasetID: datasetID,
}
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
Where("dataset_id = ?", datasetID).
FirstOrCreate(&row).Error; err != nil {
return err
}
return fn(row.ClaimToken)

The heartbeat updates that same row, so it waits for the lock and fails after innodb_lock_wait_timeout (50 s):

func (s *mysqlScheduler) TouchClaim(ctx context.Context, datasetID, token string, ttl time.Duration) (bool, error) {
if s.db == nil {
return false, nil
}
res := s.db.WithContext(ctx).Model(&entity.KnowledgeCompileDataset{}).
Where("dataset_id = ? AND claim_token = ?", datasetID, token).
Update("claim_expires_at", time.Now().Add(ttl))

The worker then treats the lease as lost, drops the batch without acking, and the sweeper runs it again:

case <-hbFailed:
close(stopHb)
<-done
if err := c.finishDatasetCompileLog(context.WithoutCancel(ctx), cr.Token, logTaskTypes, common.STOPPED, "Knowledge compilation lease was lost and will be retried", -1); err != nil {
common.Warn("knowledge_compile: failed to finalize stopped dataset ingestion log",
zap.String("dataset_id", datasetID), zap.Error(err))
}
return // lease lost: do not ack; sweeper/redelivery reprocesses (idempotent)

Expected behavior

Merging one document should take seconds however large the dataset's mind map is, and finish on the first try.

Steps to reproduce

1. Create a dataset on Infinity whose ingestion pipeline has a Compiler step with a mind_map template, with MySQL at its default innodb_lock_wait_timeout (50 s).
2. Let the dataset-level mind map grow until reading it takes longer than about 70 s (about 180k rows on our server, about 400k on an idle Infinity).
3. Parse one more document.
4. The heartbeat fails 50 s into the merge, "reclaimed expired inflight lease" is logged when the 2-minute lease runs out, and the merge starts again, every time.

Additional information

Reproduced on 91c702e with an integration test that runs the real Consumer, mysqlScheduler and engineWriter against MySQL 8.0.40 and Infinity holding 400,930 dataset-level rows, merging one document. Unpatched, the heartbeat fails with Error 1205 and the batch runs again:

    repro_structure_lease_test.go:234: [t+  2.1s] WriteMergedStructure #1 start: 40 buckets
    repro_structure_lease_test.go:234: [t+ 72.0s] TouchClaim after 50.008s: alive=false err=Error 1205 (HY000): Lock wait timeout exceeded; try restarting transaction
    repro_structure_lease_test.go:234: [t+280.4s] WriteMergedStructure #1 end after 4m38.263s, err=<nil>
2026-11-21 13:38:49.788-08:00	warn	repro	knowledge_compile: reclaimed expired inflight lease	{"pid": 58976, "dataset_id": "reprokb", "tenant_id": "reprotenant", "reclaimed_entries": 1}
    repro_structure_lease_test.go:234: [t+280.9s] WriteMergedStructure #2 start: 40 buckets
    repro_structure_lease_test.go:234: [t+282.3s] RESULT expect=bug acked=false WriteMergedStructure calls=2 TouchClaim failures=1

Looking up only the rows the incoming buckets can match, by their dataset-level id, fixes it. On the same data the merge takes 2.2 s, is acked once, and existing rows keep their source documents (no duplicates):

    repro_structure_lease_test.go:234: [t+  2.3s] WriteMergedStructure #1 start: 40 buckets
    repro_structure_lease_test.go:234: [t+  4.5s] WriteMergedStructure #1 end after 2.205s, err=<nil>
    repro_structure_lease_test.go:234: [t+  6.0s] RESULT expect=fixed acked=true WriteMergedStructure calls=1 TouchClaim failures=0
diff --git a/internal/ingestion/knowledge_compile/writer.go b/internal/ingestion/knowledge_compile/writer.go
index 70cd35f..88d685d 100644
--- a/internal/ingestion/knowledge_compile/writer.go
+++ b/internal/ingestion/knowledge_compile/writer.go
@@ -802,9 +802,16 @@ func mergeExistingStructureBuckets(ctx context.Context, eng engine.DocEngine, ba
 		return nil, nil
 	}
 
+	candidateIDs := make([]string, 0, len(buckets))
+	for i := range buckets {
+		b := buckets[i]
+		candidateIDs = common.AppendUnique(candidateIDs, []string{datasetLevelStructureID(tenant, kb, structureTemplateIdentity(b.TemplateID, b.TemplateKind), b.Name, b.Type, b.CompileKwd, b.RelationType)})
+	}
+
 	const pageSize = 500
 	stale := map[string]bool{}
-	for offset := 0; ; offset += pageSize {
+	for start := 0; start < len(candidateIDs); start += pageSize {
+		ids := candidateIDs[start:min(start+pageSize, len(candidateIDs))]
 		res, err := eng.Search(ctx, &types.SearchRequest{
 			IndexNames: []string{baseName},
 			KbIDs:      []string{kb},
@@ -818,9 +825,9 @@ func mergeExistingStructureBuckets(ctx context.Context, eng engine.DocEngine, ba
 				"scope_kwd":           "dataset",
 				"compile_kwd":         compileKinds,
 				"knowledge_graph_kwd": []string{"entity", "relation"},
+				"id":                  ids,
 			},
-			Offset: offset,
-			Limit:  pageSize,
+			Limit: len(ids),
 		})
 		if err != nil {
 			return nil, fmt.Errorf("structure merge load existing rows: %w", err)
@@ -851,9 +858,6 @@ func mergeExistingStructureBuckets(ctx context.Context, eng engine.DocEngine, ba
 				stale[id] = true
 			}
 		}
-		if len(res.Chunks) < pageSize {
-			break
-		}
 	}
 	ids := make([]string, 0, len(stale))
 	for id := range stale {

The diff applies to main and v1.0.0. It no longer finds rows stored under an older id, so older datasets may need a one-time rebuild. Two related gaps: TouchClaim errors are never logged, and a doc_completed publish that hits the same lock wait is logged once and never retried:

if err := knowledge_compile.PublishCompleted(ctx, event.tenantID, task.DatasetID, task.DocumentID, event.variants, event.taskTypes); err != nil {
common.Logger.Warn(fmt.Sprintf("knowledge_compile: publish doc_completed for %s failed: %v", task.DocumentID, err))

Related: #19649 (the same full read on Elasticsearch).

Activity

  1. added
    🐞 bug
    on Nov 21, 2026
  2. fxia0018 commented on Nov 22, 2026

    @fxia0018

    Thanks for the detailed report and the reproduction — the root cause is clear: mergeExistingStructureBuckets reads every dataset-level row (500 at a time) while withWriteLock holds the SELECT ... FOR UPDATE on knowledge_compile_docs, so the TouchClaim heartbeat blocks past innodb_lock_wait_timeout and the lease is reclaimed. Your targeted-read idea is the right direction.

    One issue with the proposed diff worth flagging before anyone lands it: the id IN (...) filter also effectively disables the stale-row cleanup in the same loop.

    In the current code the full scan is what finds stale rows — a row whose identity still matches a bucket but whose id no longer equals the freshly computed datasetLevelStructureID(...) (e.g. after a bucket's name/type/relation changed, or rows written under an older id scheme). Those get collected into stale and DeleteChunks-ed in WriteMergedStructure.

    With the diff, the query only fetches rows whose id is already one of the candidateIDs (= the new datasetLevelStructureID for each bucket), so id != newID is never true and stale stays empty. As you noted, older datasets would then need a one-time rebuild — but the same gap also applies going forward whenever a bucket's identity inputs change, not just to legacy rows. Rows orphaned by a rename/retype would silently accumulate.

    A couple of ways to keep the fix without losing the cleanup:

    1. Keep the targeted read for the merge (source_doc_ids/source_chunk_ids/type fold-in), and do the stale sweep as a separate, cheaper pass that still enumerates matching rows by identity (or run the stale sweep outside the write lock so the heartbeat isn't held up).
    2. Add an id scheme/version marker to the row so old-scheme rows can be found and rebuilt without a full manual rebuild.

    Happy to help verify either direction against the Infinity engine if a maintainer wants to weigh in on the intended behavior for stale cleanup.

  3. ccclucky commented on Nov 22, 2026

    @ccclucky
    Contributor

    Opened #22639 for this, following the keyed-lookup direction from @fxia0018.

    It fetches the rows a batch can match by the current deterministic id first, then sweeps entity rows by name_kwd and relation rows by from_entity_kwd + to_entity_kwd (keeping the old kb_id / scope_kwd / compile_kwd / knowledge_graph_kwd filters and the id != newID identity check). So the stale cleanup still covers rows written under an older id scheme, while the read no longer touches every dataset-level row inside the write lock.

    One trade-off to be aware of: a historical row whose identity fields were stored with different spelling/whitespace than the bucket can no longer be matched by the sweep — current rows are always found by id, so this only concerns legacy rows.

    I did not change TouchClaim logging or the doc_completed publish retry you also mentioned; those are outside the read path and could be follow-ups.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    🐞 bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      0