Repository navigation
feat: wiki incremental Mode A/B with durable rewrite barrier - #18122
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe change adds nullable wiki planning configuration, deterministic and LLM-based planning modes, related-page linking, variant-aware wiki persistence, wiki-specific deduplication, and dataset rebuild coordination with claim fencing. ChangesWiki compilation and planning
Estimated code review effort: 5 (Critical) | ~120 minutes Sequence Diagram(s)sequenceDiagram
participant User
participant CompilationForm
participant KnowledgeCompiler
participant Scheduler
participant Consumer
participant Writer
User->>CompilationForm: Set plan mode
CompilationForm->>KnowledgeCompiler: Submit compilation configuration
KnowledgeCompiler->>Scheduler: Publish compilation documents
Consumer->>Scheduler: Claim documents with token
Consumer->>Writer: Write merged pages and graph rows under dataset lock
Possibly related PRs
Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 9
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/ingestion/knowledge_compile/writer.go (1)
189-218: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winPersist wiki sections with
wiki_section.Line 189 always calls
compileKwdForVariant(p.Variant). ForVariantWiki, that function always returnswiki_page. A product withMeta["kind"] == "section"therefore storeskc_kind=sectionbutcompile_kwd=wiki_page.This breaks the new page-versus-section storage contract and makes
compileKwdWikiSectionunreachable for newly written rows. Add a product-level compile-keyword helper. Use it in bothWriteMergedtelemetry andmergedChunkMap. Add a test for a merged section product.Proposed fix
+func compileKwdForProduct(p kccommon.Product) string { + if p.Variant == kccommon.VariantWiki && metaString(p.Meta, "kind") == "section" { + return compileKwdWikiSection + } + return compileKwdForVariant(p.Variant) +} + - byKwd[compileKwdForVariant(p.Variant)]++ + byKwd[compileKwdForProduct(p)]++ - "compile_kwd": compileKwdForVariant(p.Variant), + "compile_kwd": compileKwdForProduct(p),🤖 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/ingestion/knowledge_compile/writer.go` around lines 189 - 218, Add a product-level compile-keyword helper that selects the wiki section keyword when the product metadata kind is section and otherwise preserves existing variant behavior. Use this helper in both WriteMerged telemetry and mergedChunkMap instead of calling compileKwdForVariant directly. Add a test covering a merged section product and asserting it stores the section compile keyword.
🧹 Nitpick comments (11)
web/src/pages/agent/form/compilation-form/index.tsx (1)
5-5: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winUse
useTranslationdirectly.Replace
useTranslate('setting')withuseTranslation('translation', { keyPrefix: 'setting' }). The project rule prohibits the wrapped hook for this use.As per coding guidelines: “Prefer useTranslation from react-i18next over project-wrapped utilities such as useTranslate.”
Also applies to: 37-37
🤖 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 `@web/src/pages/agent/form/compilation-form/index.tsx` at line 5, Replace the useTranslate hook usage in the form component with useTranslation from react-i18next, passing the translation namespace and setting keyPrefix; update the import accordingly and preserve the existing translation calls.Source: Coding guidelines
internal/ingestion/component/knowledge_compiler/common/types.go (1)
179-183: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove migration-history notes from runtime comments.
Keep the current behavior explanation. Remove task identifiers, port notes, and migration-history references.
internal/ingestion/component/knowledge_compiler/common/types.go#L179-L183: remove thewiki_incremental port (T1)history.internal/ingestion/component/knowledge_compiler/wiki/wiki.go#L812-L818: remove thewiki_incremental port (O2)history.internal/ingestion/knowledge_compile/writer.go#L199-L213: remove thewiki_incremental porthistory.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/ingestion/component/knowledge_compiler/common/types.go` around lines 179 - 183, Remove migration-history references while preserving the current behavior explanations in internal/ingestion/component/knowledge_compiler/common/types.go:179-183, internal/ingestion/component/knowledge_compiler/wiki/wiki.go:812-818, and internal/ingestion/knowledge_compile/writer.go:199-213. Specifically delete the wiki_incremental port/task identifiers and related historical wording at all three sites; no runtime logic changes are needed.Source: Coding guidelines
internal/ingestion/component/knowledge_compiler/wiki/wiki.go (1)
2475-2478: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace deprecated
strings.TitleThe module targets Go 1.26.4. Replace this call with
golang.org/x/text/casesor keep the slug-derived label without title casing.🤖 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/ingestion/component/knowledge_compiler/wiki/wiki.go` around lines 2475 - 2478, Replace the deprecated strings.Title call in the label fallback with golang.org/x/text/cases title casing, or retain the slug-derived label without title casing. Keep the existing pageTitles lookup and lastPathSlug/strings.ReplaceAll fallback behavior unchanged.Source: Coding guidelines
internal/ingestion/knowledge_compile/reader_test.go (1)
87-87: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDrop the review-history reference.
"added in the 8th review" describes process history, not behavior. State the contract instead, for example: "SelectFields must include the round-trip columns."
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/ingestion/knowledge_compile/reader_test.go` at line 87, Update the comment near SelectFields to remove the review-history reference and describe only the current contract: SelectFields must include the round-trip columns.Source: Coding guidelines
internal/ingestion/knowledge_compile/writer_test.go (1)
168-182: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winTurn the
wiki_sectionnote into an assertion.Lines 168-172 describe that a
wiki_sectionrow satisfies aVariantWikiquery, but no case checks it. Add the case so the stated contract is locked by the test.💚 Proposed addition
+ // wiki_section maps to VariantWiki (page and section share the wiki + // variant); the page/section distinction lives in Meta.kind and is enforced + // by filterWikiPageCandidates, NOT by the variant dirty-row check. + section := map[string]interface{}{} + for k, v := range base { + section[k] = v + } + section["compile_kwd"] = compileKwdWikiSection + if _, ok := productFromChunkMap(section, "t1", kccommon.VariantWiki); !ok { + t.Errorf("wiki_section row should satisfy VariantWiki query") + }🤖 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/ingestion/knowledge_compile/writer_test.go` around lines 168 - 182, Extend the test around productFromChunkMap to create a wiki_section row from base, set its compile keyword appropriately, and assert that it is accepted for kccommon.VariantWiki. Keep the existing clean wiki_page assertion unchanged and ensure the new assertion locks in the documented shared-variant behavior.internal/ingestion/knowledge_compile/consumer.go (2)
254-273: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAlign the
RebuildDatasetdoc comment with the code.Two mismatches:
- Line 281 lists
Bumpas a failure point. No generation bump exists in this function.- The step list ends at 5, but Line 328 starts with "6. resweep". Renumber to 5.
As per coding guidelines: "keep package and doc comments aligned with the current runtime path rather than migration history."
Also applies to: 328-333
🤖 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/ingestion/knowledge_compile/consumer.go` around lines 254 - 273, Update the RebuildDataset doc comment to remove the nonexistent generation “Bump” failure point and renumber the later “resweep” step from 6 to 5. Keep the comment aligned with the function’s current runtime behavior and preserve the existing step descriptions.Source: Coding guidelines
35-38: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffConsider passing the DB handle instead of a package-level variable.
kcDBis written byProvisioninservice.goat Line 126 and read bydefaultDocLister. Tests that provision concurrently, or a secondProvisioncall, would race on this global. AWithDBoption onConsumer(the same pattern asdocLister) removes the shared mutable state.Also applies to: 339-344
🤖 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/ingestion/knowledge_compile/consumer.go` around lines 35 - 38, Replace the package-level kcDB state with a Consumer-level database dependency: add a WithDB option and store the handle on Consumer, update Provision and defaultDocLister to use that instance field, and remove all reads and writes of the global variable. Preserve the existing no-DB behavior where document listing returns no documents.internal/ingestion/knowledge_compile/fake_engine_test.go (1)
29-48: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueAdd a compile-time interface assertion and note the concurrency limit.
Two small improvements:
- Add
var _ engine.DocEngine = (*fakeEngine)(nil)so an interface change fails at this file rather than at each call site.SearchandDeleteChunkswrite the recorded fields without a mutex. The consumer KNN path fans outSearchSimilaracross the compiler pool. If a later test drives that path with this fake under-race, it will report a race. State the single-goroutine constraint in the type comment, or guard the fields with async.Mutex.🤖 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/ingestion/knowledge_compile/fake_engine_test.go` around lines 29 - 48, Add a compile-time assertion that fakeEngine implements engine.DocEngine. Update fakeEngine’s type comment to state that its recording fields require single-goroutine use, or add mutex protection around Search and DeleteChunks field writes to make concurrent use race-safe.internal/ingestion/knowledge_compile/reader.go (1)
343-358: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the duplicated comment block.
Lines 343-347 and Lines 350-355 state the same rule twice. Keep one.
♻️ Proposed cleanup
- // The KNN Filter scopes compile_kwd, but a foreign/legacy row that slipped - // past it must not poison the merge candidate. Reject by the raw compile_kwd - // (wiki_page vs wiki_section are distinct keywords even though both map to - // VariantWiki); the page/section distinction is resolved downstream by - // Meta.kind (see productFromChunkMap). expectKwd := compileKwdForVariant(variant) for _, c := range res.Chunks {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/ingestion/knowledge_compile/reader.go` around lines 343 - 358, Remove the duplicated explanatory comment in the loop over res.Chunks, keeping a single concise comment that documents the compile_kwd pre-filter and downstream validation. Leave the expectKwd assignment and filtering logic unchanged.Source: Coding guidelines
internal/ingestion/knowledge_compile/wiki_merge.go (1)
40-43: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTwo redundant statements.
- Lines 42-43:
mergedis already a copy ofexisting, so both assignments are no-ops. Keep the intent in the comment and drop the code.- Line 137:
distinctis never appended to. Assignnildirectly at Line 149.Also applies to: 137-149
🤖 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/ingestion/knowledge_compile/wiki_merge.go` around lines 40 - 43, The merge logic already copies existing identity fields, so remove the redundant merged.ID and merged.DocID assignments while retaining the explanatory comment. In the distinct-handling flow around distinct and its later assignment, remove the unused variable and assign nil directly where the result is initialized.internal/ingestion/knowledge_compile/scheduler.go (1)
206-208: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueInline the
publishhelpers intoPublish. No other callers use them, so the private wrappers add only an internal indirection.🤖 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/ingestion/knowledge_compile/scheduler.go` around lines 206 - 208, Inline the logic currently delegated by mysqlScheduler.Publish into Publish, removing the private publish helper and its wrapper-only indirection. Preserve the existing arguments, context handling, and returned error behavior.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/ingestion/component/knowledge_compiler/wiki/prompt.go`:
- Around line 230-231: Prevent unresolved RelatedKB targets from becoming broken
links or graph outlinks: in
internal/ingestion/component/knowledge_compiler/wiki/prompt.go:230-231, remove
the instruction allowing links outside the available-page list; in
internal/ingestion/component/knowledge_compiler/wiki/wiki.go:2452-2491, resolve
each target against the current page index and render unresolved targets as
plain text or omit them without appending to outlinks; in
internal/ingestion/component/knowledge_compiler/wiki/wiki.go:812-819, ensure
unresolved RelatedKB targets are not preserved as graph outlinks.
In `@internal/ingestion/component/knowledge_compiler/wiki/wiki.go`:
- Around line 2485-2491: Update the existing-heading branch around seeAlsoRe so
bullets are inserted immediately after the matched “See also” heading rather
than appended to the document end. Preserve all content following that heading,
placing the joined bullets before the next same- or higher-level section while
retaining the current new-section behavior when no heading matches.
In `@internal/ingestion/knowledge_compile/consumer.go`:
- Around line 353-364: Update filterWikiPageCandidates to allocate a new output
slice instead of using candidates[:0], preserving the caller’s incoming backing
array and contents. Append matching candidates to the new slice while retaining
the existing filtering rules and return behavior.
In `@internal/ingestion/knowledge_compile/dedup.go`:
- Around line 120-135: Fix structIdx construction in DecideBatch by recording
the original groups index gi rather than len(structGroups), so structure fold
results are written back to their corresponding entries in groups. Preserve the
existing structGroups ordering for batching, and add a DecideBatch test covering
wiki and structure groups in mixed order, verifying each result remains
associated with its original group.
In `@internal/ingestion/knowledge_compile/reader.go`:
- Around line 192-201: Normalize compile_kwd through the shared asString helper
before calling kwdToVariant in productFromChunkMap, matching LoadDocProducts and
the SearchSimilar pre-filter. Extend or reuse that helper so list-wrapped
keyword values from the engine are normalized correctly, while preserving the
existing dirty-row rejection and kc_kind wiki fallback behavior.
In `@internal/ingestion/knowledge_compile/scheduler.go`:
- Around line 117-124: Complete the CancelInflight documentation sentence by
stating the outcome of reclaiming the dropped pending batch, specifically that
it is re-checked during subsequent processing.
- Around line 275-306: Refactor WithDatasetLock so per-dataset serialization
does not keep a MySQL transaction or SELECT ... FOR UPDATE lock open while fn
performs DocEngine I/O such as WriteMerged, ProjectWikiGraph, or DeleteMerged.
Preserve claim-token validation and exclusive same-dataset execution using a
non-transactional lock mechanism, and add explicit recovery or compensation for
partial DocEngine side effects when fn or scheduler persistence fails.
In `@internal/ingestion/knowledge_compile/wiki_merge.go`:
- Around line 57-61: Update the unionWikiProvenance documentation to accurately
state that only identity and creation-time fields come from the existing row,
while kind, slug, page_type, title, summary, entity_names, related_kb_pages, and
outlinks come from candidate b; retain the existing description of
provenance-array unioning and deduplication.
- Around line 34-55: Update wikiReplace to copy candidate.Vector alongside
candidate.Content so the merged product’s persisted embedding matches the
replacement Markdown; add a regression test verifying the candidate vector is
retained by the merged result.
---
Outside diff comments:
In `@internal/ingestion/knowledge_compile/writer.go`:
- Around line 189-218: Add a product-level compile-keyword helper that selects
the wiki section keyword when the product metadata kind is section and otherwise
preserves existing variant behavior. Use this helper in both WriteMerged
telemetry and mergedChunkMap instead of calling compileKwdForVariant directly.
Add a test covering a merged section product and asserting it stores the section
compile keyword.
---
Nitpick comments:
In `@internal/ingestion/component/knowledge_compiler/common/types.go`:
- Around line 179-183: Remove migration-history references while preserving the
current behavior explanations in
internal/ingestion/component/knowledge_compiler/common/types.go:179-183,
internal/ingestion/component/knowledge_compiler/wiki/wiki.go:812-818, and
internal/ingestion/knowledge_compile/writer.go:199-213. Specifically delete the
wiki_incremental port/task identifiers and related historical wording at all
three sites; no runtime logic changes are needed.
In `@internal/ingestion/component/knowledge_compiler/wiki/wiki.go`:
- Around line 2475-2478: Replace the deprecated strings.Title call in the label
fallback with golang.org/x/text/cases title casing, or retain the slug-derived
label without title casing. Keep the existing pageTitles lookup and
lastPathSlug/strings.ReplaceAll fallback behavior unchanged.
In `@internal/ingestion/knowledge_compile/consumer.go`:
- Around line 254-273: Update the RebuildDataset doc comment to remove the
nonexistent generation “Bump” failure point and renumber the later “resweep”
step from 6 to 5. Keep the comment aligned with the function’s current runtime
behavior and preserve the existing step descriptions.
- Around line 35-38: Replace the package-level kcDB state with a Consumer-level
database dependency: add a WithDB option and store the handle on Consumer,
update Provision and defaultDocLister to use that instance field, and remove all
reads and writes of the global variable. Preserve the existing no-DB behavior
where document listing returns no documents.
In `@internal/ingestion/knowledge_compile/fake_engine_test.go`:
- Around line 29-48: Add a compile-time assertion that fakeEngine implements
engine.DocEngine. Update fakeEngine’s type comment to state that its recording
fields require single-goroutine use, or add mutex protection around Search and
DeleteChunks field writes to make concurrent use race-safe.
In `@internal/ingestion/knowledge_compile/reader_test.go`:
- Line 87: Update the comment near SelectFields to remove the review-history
reference and describe only the current contract: SelectFields must include the
round-trip columns.
In `@internal/ingestion/knowledge_compile/reader.go`:
- Around line 343-358: Remove the duplicated explanatory comment in the loop
over res.Chunks, keeping a single concise comment that documents the compile_kwd
pre-filter and downstream validation. Leave the expectKwd assignment and
filtering logic unchanged.
In `@internal/ingestion/knowledge_compile/scheduler.go`:
- Around line 206-208: Inline the logic currently delegated by
mysqlScheduler.Publish into Publish, removing the private publish helper and its
wrapper-only indirection. Preserve the existing arguments, context handling, and
returned error behavior.
In `@internal/ingestion/knowledge_compile/wiki_merge.go`:
- Around line 40-43: The merge logic already copies existing identity fields, so
remove the redundant merged.ID and merged.DocID assignments while retaining the
explanatory comment. In the distinct-handling flow around distinct and its later
assignment, remove the unused variable and assign nil directly where the result
is initialized.
In `@internal/ingestion/knowledge_compile/writer_test.go`:
- Around line 168-182: Extend the test around productFromChunkMap to create a
wiki_section row from base, set its compile keyword appropriately, and assert
that it is accepted for kccommon.VariantWiki. Keep the existing clean wiki_page
assertion unchanged and ensure the new assertion locks in the documented
shared-variant behavior.
In `@web/src/pages/agent/form/compilation-form/index.tsx`:
- Line 5: Replace the useTranslate hook usage in the form component with
useTranslation from react-i18next, passing the translation namespace and setting
keyPrefix; update the import accordingly and preserve the existing translation
calls.
🪄 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: 5945af86-ccf8-4e25-8b91-2f4f865b5b99
📒 Files selected for processing (21)
internal/ingestion/component/knowledge_compiler/common/types.gointernal/ingestion/component/knowledge_compiler/component.gointernal/ingestion/component/knowledge_compiler/component_test.gointernal/ingestion/component/knowledge_compiler/wiki/prompt.gointernal/ingestion/component/knowledge_compiler/wiki/wiki.gointernal/ingestion/knowledge_compile/consumer.gointernal/ingestion/knowledge_compile/consumer_test.gointernal/ingestion/knowledge_compile/dedup.gointernal/ingestion/knowledge_compile/fake_engine_test.gointernal/ingestion/knowledge_compile/reader.gointernal/ingestion/knowledge_compile/reader_test.gointernal/ingestion/knowledge_compile/scheduler.gointernal/ingestion/knowledge_compile/service.gointernal/ingestion/knowledge_compile/wiki_graph_test.gointernal/ingestion/knowledge_compile/wiki_merge.gointernal/ingestion/knowledge_compile/writer.gointernal/ingestion/knowledge_compile/writer_test.goweb/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/agent/constant/pipeline.tsxweb/src/pages/agent/form/compilation-form/index.tsx
💤 Files with no reviewable changes (1)
- internal/ingestion/knowledge_compile/consumer_test.go
| // CancelInflight drops the live claim for a dataset back into the backlog so | ||
| // a rewrite can start from a clean index. The token is intentionally NOT | ||
| // checked: this is the rewrite's authoritative cancel. Workers verify their | ||
| // claim token inside the dataset write lock before every destructive write, so | ||
| // a cancelled worker cannot write after the rebuild clears storage. It is a safe no-op when | ||
| // there is no live lease (the dataset is idle or already drained). The dropped | ||
| // batch is re-marked pending (not deleted) so it is reclaimed and re-checked | ||
| CancelInflight(ctx context.Context, datasetID, token string) error |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Complete the truncated doc sentence.
The last sentence stops mid-clause: "The dropped batch is re-marked pending (not deleted) so it is reclaimed and re-checked". Finish it.
📝 Proposed fix
- // batch is re-marked pending (not deleted) so it is reclaimed and re-checked
+ // batch is re-marked pending (not deleted) so it is reclaimed and re-checked
+ // after the rebuild republishes the dataset documents.
CancelInflight(ctx context.Context, datasetID, token string) error📝 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.
| // CancelInflight drops the live claim for a dataset back into the backlog so | |
| // a rewrite can start from a clean index. The token is intentionally NOT | |
| // checked: this is the rewrite's authoritative cancel. Workers verify their | |
| // claim token inside the dataset write lock before every destructive write, so | |
| // a cancelled worker cannot write after the rebuild clears storage. It is a safe no-op when | |
| // there is no live lease (the dataset is idle or already drained). The dropped | |
| // batch is re-marked pending (not deleted) so it is reclaimed and re-checked | |
| CancelInflight(ctx context.Context, datasetID, token string) error | |
| // CancelInflight drops the live claim for a dataset back into the backlog so | |
| // a rewrite can start from a clean index. The token is intentionally NOT | |
| // checked: this is the rewrite's authoritative cancel. Workers verify their | |
| // claim token inside the dataset write lock before every destructive write, so | |
| // a cancelled worker cannot write after the rebuild clears storage. It is a safe no-op when | |
| // there is no live lease (the dataset is idle or already drained). The dropped | |
| // batch is re-marked pending (not deleted) so it is reclaimed and re-checked | |
| // after the rebuild republishes the dataset documents. | |
| CancelInflight(ctx context.Context, datasetID, token string) 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/ingestion/knowledge_compile/scheduler.go` around lines 117 - 124,
Complete the CancelInflight documentation sentence by stating the outcome of
reclaiming the dropped pending batch, specifically that it is re-checked during
subsequent processing.
| // WithDatasetLock executes fn under an exclusive per-dataset row lock. It locks | ||
| // the dataset row (SELECT ... FOR UPDATE) and runs fn inside the same | ||
| // transaction, so the row lock is held for the entire duration of fn and any | ||
| // concurrent WithDatasetLock on the same dataset blocks until fn returns. This | ||
| // is what makes a worker's claim-token check + destructive write atomic against | ||
| // a concurrent RebuildDataset. | ||
| // | ||
| // The claim token passed to fn is read within this transaction, so the check in | ||
| // fn does not need (and must not attempt) a separate DB read that would deadlock | ||
| // against the held row lock. fn runs inside the transaction; if it returns an | ||
| // error the transaction is rolled back | ||
| // and the error is propagated unchanged (any DB write performed inside fn is | ||
| // rolled back, so no partial side effect persists on an aborted write). | ||
| func (s *mysqlScheduler) WithDatasetLock(ctx context.Context, datasetID string, fn func(claimToken string) error) error { | ||
| if s.db == nil { | ||
| // No DB (test/no-op scheduler): nothing to serialize against. | ||
| return fn("") | ||
| } | ||
| return s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { | ||
| row := entity.KnowledgeCompileDataset{ | ||
| DatasetID: datasetID, | ||
| BacklogDocIDs: "[]", | ||
| InflightDocIDs: "[]", | ||
| } | ||
| if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}). | ||
| Where("dataset_id = ?", datasetID). | ||
| FirstOrCreate(&row).Error; err != nil { | ||
| return err | ||
| } | ||
| return fn(row.ClaimToken) | ||
| }) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Check DB pool sizing and any timeout applied around the locked write path.
rg -n 'SetMaxOpenConns|SetConnMaxLifetime|innodb_lock_wait_timeout|GET_LOCK' --type=go
rg -n -C3 'WithDatasetLock' --type=goRepository: infiniflow/ragflow
Length of output: 156
🏁 Script executed:
#!/bin/bash
set -u
printf '%s\n' '--- scheduler definitions and callers ---'
rg -n -C 12 'WithDatasetLock|func \(.*\) (Publish|publish)|func \(.*\) CancelInflight' internal/ingestion/knowledge_compile/scheduler.go
rg -n -C 10 'WithDatasetLock' internal/ingestion/knowledge_compile --glob '*.go'
printf '%s\n' '--- DocEngine calls in consumer.go ---'
rg -n -C 8 'WriteMerged|ProjectWikiGraph|DeleteDocLevelForDocs|StripMergedSources|DeleteMerged|DropWikiGraph' internal/ingestion/knowledge_compile/consumer.go
printf '%s\n' '--- pool and timeout configuration ---'
rg -n -C 4 'SetMaxOpenConns|SetMaxIdleConns|SetConnMaxLifetime|SetConnMaxIdleTime|innodb_lock_wait_timeout|wait_timeout|GET_LOCK|WithContext\(ctx\).*Transaction|Transaction\(func' --glob '*.go' .
printf '%s\n' '--- relevant file sizes ---'
wc -l internal/ingestion/knowledge_compile/scheduler.go internal/ingestion/knowledge_compile/consumer.goRepository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -u
printf '%s\n' '--- writer interface and implementations ---'
rg -n -C 8 'type .*Writer|WriteMerged|ProjectWikiGraph|DeleteMerged|DropWikiGraph|DeleteDocLevelForDocs|StripMergedSources' internal/ingestion/knowledge_compile --glob '*.go' --glob '!consumer.go'
printf '%s\n' '--- engine calls and context handling ---'
rg -n -C 6 'WriteMerged|ProjectWikiGraph|DeleteMerged|DropWikiGraph|DeleteDocLevelForDocs|StripMergedSources' internal --glob '*.go' | head -n 500
printf '%s\n' '--- database initialization and pool configuration ---'
rg -n -C 8 'sqlDB|DB\(\)|gorm.Open|SetMaxOpenConns|SetMaxIdleConns|SetConnMaxLifetime|SetConnMaxIdleTime' internal/dao internal --glob '*.go' | head -n 500
printf '%s\n' '--- timeout configuration outside Go ---'
rg -n -C 3 'innodb_lock_wait_timeout|wait_timeout|GET_LOCK|lock_wait_timeout|SetMaxOpenConns|SetConnMaxLifetime' --glob '!*.go' .Repository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -u
printf '%s\n' '--- exact engine-write paths ---'
sed -n '35,75p' internal/ingestion/knowledge_compile/writer.go
sed -n '85,170p' internal/ingestion/knowledge_compile/writer.go
sed -n '270,330p' internal/ingestion/knowledge_compile/writer.go
sed -n '601,663p' internal/ingestion/knowledge_compile/writer.go
printf '%s\n' '--- database setup candidates ---'
fd -i -t f '.*(db|database|dao).*\.go$' internal | head -n 100
rg -l 'gorm.Open|SetMaxOpenConns|SetMaxIdleConns|SetConnMaxLifetime|SetConnMaxIdleTime' internal --glob '*.go' | head -n 100
printf '%s\n' '--- context deadlines in the compile path ---'
rg -n -C 4 'context\.With(Timeout|Deadline)|WithTimeout|WithDeadline|RebuildDataset\(|withWriteLock\(' internal/ingestion/knowledge_compile --glob '*.go'
printf '%s\n' '--- read-only structural check: callbacks contain engine writes ---'
python3 - <<'PY'
from pathlib import Path
p = Path("internal/ingestion/knowledge_compile/consumer.go")
s = p.read_text()
needles = [
"c.writer.DeleteMerged(ctx, tenant, kb)",
"c.writer.DropWikiGraph(ctx, tenant, kb)",
"c.writer.DeleteDocLevelForDocs(ctx, tenant, kb, delIDs)",
"c.writer.StripMergedSources(ctx, tenant, kb, delIDs)",
"c.writer.WriteMerged(ctx, tenant, kb, mergedFinal)",
"c.writer.ProjectWikiGraph(ctx, tenant, kb)",
]
for needle in needles:
pos = s.find(needle)
print(f"{needle}: {'found' if pos >= 0 else 'missing'}")
if pos >= 0:
start = s.rfind("WithDatasetLock", 0, pos)
start = max(start, s.rfind("withWriteLock", 0, pos))
print(" nearest lock wrapper:", s[start:s.find("\n", start)] if start >= 0 else "none")
PYRepository: infiniflow/ragflow
Length of output: 20644
Keep DocEngine writes outside the MySQL transaction
WithDatasetLock holds a SELECT ... FOR UPDATE lock and a MySQL connection while fn calls DocEngine operations such as WriteMerged, ProjectWikiGraph, and DeleteMerged.
A slow or failed DocEngine call can block rebuilds and workers, consume pool connections, and cause transaction failure. If a DocEngine write succeeds before the transaction fails, scheduler state and DocEngine state can diverge.
Retain per-dataset serialization, but do not hold the database transaction across DocEngine I/O. Use a lock mechanism that does not keep a transaction open, and define recovery for partial DocEngine side effects.
🤖 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/ingestion/knowledge_compile/scheduler.go` around lines 275 - 306,
Refactor WithDatasetLock so per-dataset serialization does not keep a MySQL
transaction or SELECT ... FOR UPDATE lock open while fn performs DocEngine I/O
such as WriteMerged, ProjectWikiGraph, or DeleteMerged. Preserve claim-token
validation and exclusive same-dataset execution using a non-transactional lock
mechanism, and add explicit recovery or compensation for partial DocEngine side
effects when fn or scheduler persistence fails.
Port the wiki_incremental dataset-level merge and make its rewrite barrier durable and concurrency-safe: - Wiki pages merge via replace-only (wikiMerge), not JSON LLM merge; sections are filtered before in-memory dedup. - productFromChunkMap takes an expect variant and rejects dirty/unknown compile_kwd rows; SearchSimilar uses compileKwdForVariant. - Dataset rewrite persists a monotonic numeric EventID generation (BumpEventID/CurrentEventID) instead of an opaque UUID + process-local map, so the barrier stays correct across restarts. - parseEventIDGen rejects malformed (non-numeric) persisted values instead of treating them as generation 0, and BumpEventID normalizes legacy UUIDs. - Scheduler-backed per-dataset write/rebuild lock (WithDatasetLock) makes a worker's generation check + destructive write atomic against a rebuild's clear, closing the cross-process TOCTOU window. - DropStale clears the claim lease when inflight empties so a rewrite's fresh backlog is claimable immediately. - Stale/paused claims and mid-batch aborts use DropStale (never plain Ack), and RebuildDataset clears rebuildPause on every return path. fix fix
c6a3ed1 to
298ff04
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
docker/docker-compose-base.yml (1)
259-259: 🩺 Stability & Availability | 🔵 TrivialConfirm deployment memory headroom for the new limit.
--maxmemorylimits Redis data, not all Valkey memory. Theredisservice has nomem_limit, so allocator overhead, connections, persistence buffers, and rebuild bursts can push process memory above512mb. If deployments were sized for the previous128mbvalue, this change increases host OOM risk.Validate deployment memory budgets before merge. Add an explicit service resource limit or update deployment sizing when required.
🤖 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 `@docker/docker-compose-base.yml` at line 259, Review the redis service resource configuration alongside its command and validate that deployments have sufficient headroom for the 512mb maxmemory setting plus allocator, connection, persistence, and rebuild overhead. Add an explicit service-level memory limit or update the deployment sizing configuration as needed, ensuring the configured budget exceeds Redis data memory and preserves safe operation.
🤖 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 `@docker/docker-compose-base.yml`:
- Line 259: Update the Redis service command configuration to prevent eviction
of ConnectorLock keys used by the connector/knowledge-base sync locks, replacing
volatile-lru with a no-eviction policy or routing these locks to a dedicated
no-eviction Redis instance. Preserve the existing password and memory-limit
settings, and ensure the selected approach maintains the 24-hour SETNX lock
contract under full-memory conditions.
---
Nitpick comments:
In `@docker/docker-compose-base.yml`:
- Line 259: Review the redis service resource configuration alongside its
command and validate that deployments have sufficient headroom for the 512mb
maxmemory setting plus allocator, connection, persistence, and rebuild overhead.
Add an explicit service-level memory limit or update the deployment sizing
configuration as needed, ensuring the configured budget exceeds Redis data
memory and preserves safe operation.
🪄 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: c2efcc48-29a8-491e-bff4-1777b01009d1
📒 Files selected for processing (7)
docker/docker-compose-base.ymlinternal/ingestion/component/knowledge_compiler/common/types.gointernal/ingestion/component/knowledge_compiler/component.gointernal/ingestion/component/knowledge_compiler/component_test.gointernal/ingestion/component/knowledge_compiler/wiki/wiki.gointernal/ingestion/pipeline/pipeline_knowledge_compiler_dsl_test.goweb/src/locales/en.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- web/src/locales/en.ts
- internal/ingestion/component/knowledge_compiler/wiki/wiki.go
| # swr.cn-north-4.myhuaweicloud.com/ddn-k8s/docker.io/valkey/valkey:8 | ||
| image: valkey/valkey:8 | ||
| command: ["redis-server", "--requirepass", "${REDIS_PASSWORD}", "--maxmemory", "128mb", "--maxmemory-policy", "volatile-lru"] | ||
| command: ["redis-server", "--requirepass", "${REDIS_PASSWORD}", "--maxmemory", "512mb", "--maxmemory-policy", "volatile-lru"] |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
rg -n -C 5 \
'SetNX|SETNX|PEXPIRE|Expire|EXPIRE|Acquire.*[Ll]ock|[Ll]ock.*[Dd]ataset|claim' \
internal
rg -n -C 4 \
'maxmemory|maxmemory-policy|mem_limit|MEM_LIMIT|resources:|memory:' \
dockerRepository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- compose Redis service ---'
sed -n '235,270p' docker/docker-compose-base.yml
printf '%s\n' '--- Redis references in coordination code ---'
rg -n -C 3 'redis|Redis|SetNX|SETNX|PEXPIRE|EXPIRE|WithDatasetLock|ClaimExpiresAt|claim_expires_at' \
internal/ingestion/knowledge_compile internal | head -n 500
printf '%s\n' '--- Redis memory and container limits ---'
rg -n -C 3 'maxmemory|maxmemory-policy|mem_limit|memory:|resources:' docker
printf '%s\n' '--- scheduler ownership and persistence model ---'
sed -n '275,345p' internal/ingestion/knowledge_compile/scheduler.go
sed -n '494,615p' internal/ingestion/knowledge_compile/scheduler.go
rg -n -C 3 'type KnowledgeCompileDataset|ClaimExpiresAt|ClaimToken|BacklogDocIDs|InflightDocIDs' internalRepository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- Redis distributed-lock implementation ---'
fd -i '.*redis.*(go|yaml|yml|template)$' internal docker | sort
rg -n -C 6 'type DistributedLock|NewDistributedLock|connectorLockTTL|Acquire\(|Renew|Expire|PEXPIRE|SETNX|SetNX|Watch|DEL|Delete' \
internal/engine/redis internal/syncer
printf '%s\n' '--- ConnectorLock callers and dataset scope ---'
rg -n -C 5 'NewConnectorLock|TryLock\(|Release\(|connectorLockKey|ConnectorLock' internal/syncer internal
printf '%s\n' '--- Redis database configuration and compiler construction ---'
rg -n -C 4 'REDIS_DB|database:|DB[[:space:]]*=|redis.*[Dd]b|knowledge_compile|newScheduler|NewConnectorLock' \
docker internal | head -n 600Repository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- Redis configuration ---'
rg -n -C 8 'type RedisConfig|RedisConfig\{|DB[[:space:]]*:|Database|database|REDIS_DB|REDIS_DATABASE' \
internal config docker | head -n 300
printf '%s\n' '--- Exact lock and worker paths ---'
sed -n '28,110p' internal/syncer/connector_lock.go
sed -n '100,145p' internal/syncer/task_worker.go
sed -n '850,918p' internal/engine/redis/redis.go
printf '%s\n' '--- Coordination ownership ---'
rg -n -C 5 'WithDatasetLock|RebuildDataset|TryLock\(taskContext\.Connector\.ID|syncer:connector-lock' \
internal/ingestion internal/syncer
printf '%s\n' '--- Static behavioral verifier ---'
python3 - <<'PY'
from pathlib import Path
lock = Path("internal/syncer/connector_lock.go").read_text()
redis = Path("internal/engine/redis/redis.go").read_text()
compose = Path("docker/docker-compose-base.yml").read_text()
assert "connectorLockTTL = 24 * time.Hour" in lock
assert "redis.NewDistributedLock(key, l.holder, connectorLockTTL, 0)" in lock
assert "return l.client.SetNX(ctx, l.lockKey, l.lockValue, l.timeout)" in redis
assert '"--maxmemory-policy", "volatile-lru"' in compose
print("connector/KB lock: Redis-backed")
print("lock expiration: 24 hours")
print("acquisition: SETNX with expiration")
print("Compose policy: volatile-lru")
print("Conclusion: the Redis connector/KB lock is an expiring key eligible for volatile eviction")
PYRepository: infiniflow/ragflow
Length of output: 18346
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- Redis config declarations ---'
rg -n -C 6 'type RedisConfig|RedisConfig|REDIS_DB|REDIS_DATABASE|DB[[:space:]]*:' internal docker --glob '*.go' --glob '*.yml' --glob '*.yaml' --glob '*.template' | head -n 300
printf '%s\n' '--- Static lock-policy verifier ---'
python3 - <<'PY'
from pathlib import Path
lock = Path("internal/syncer/connector_lock.go").read_text()
redis = Path("internal/engine/redis/redis.go").read_text()
compose = Path("docker/docker-compose-base.yml").read_text()
checks = {
"connector lock uses Redis": "redis.NewDistributedLock(key, l.holder, connectorLockTTL, 0)" in lock,
"connector lock TTL is 24 hours": "const connectorLockTTL = 24 * time.Hour" in lock,
"distributed lock uses SETNX with timeout": "return l.client.SetNX(ctx, l.lockKey, l.lockValue, l.timeout)" in redis,
"compose uses volatile-lru": '"--maxmemory-policy", "volatile-lru"' in compose,
}
for name, ok in checks.items():
print(f"{name}: {'yes' if ok else 'no'}")
assert all(checks.values())
print("Conclusion: the syncer connector/KB lock is a volatile Redis key and is eligible for volatile eviction.")
PYRepository: infiniflow/ragflow
Length of output: 19807
Protect Redis connector/KB locks from eviction.
ConnectorLock stores syncer:connector-lock:<connectorID>:<kbID> with a 24-hour expiration through SETNX. volatile-lru can evict this lock when Redis reaches 512mb, allowing concurrent sync tasks for the same connector and knowledge base.
Use a no-eviction Redis instance for these locks, or add a tested full-memory path that preserves the lock contract.
🤖 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 `@docker/docker-compose-base.yml` at line 259, Update the Redis service command
configuration to prevent eviction of ConnectorLock keys used by the
connector/knowledge-base sync locks, replacing volatile-lru with a no-eviction
policy or routing these locks to a dedicated no-eviction Redis instance.
Preserve the existing password and memory-limit settings, and ensure the
selected approach maintains the 24-hour SETNX lock contract under full-memory
conditions.
- wiki_merge: wikiReplace now copies the candidate vector so the persisted embedding matches the replacement Markdown (fixes stale-embedding KNN hits). - dedup: splitWikiGroups records the original batch index in structIdx so structure results fold back to the correct group when wiki groups precede them (was writing to the wrong groups). Extracted the split for a regression test. - consumer: filterWikiPageCandidates allocates a fresh slice instead of reusing candidates[:0], preserving the caller's incoming backing array. - reader: normalize compile_kwd via the shared asString helper (unwrapping single-element keyword lists) in productFromChunkMap and the SearchSimilar pre-filter, matching LoadDocProducts. - wiki: resolve RelatedKB targets against the available-page index before rendering "See also" links; unresolved targets are omitted and never added to outlinks, so no broken artifact link or phantom graph edge is persisted. The prompt now only links pages in the available list. - docker: drop the unrelated Redis maxmemory bump so the PR no longer touches Redis policy (reverts to upstream).
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/ingestion/knowledge_compile/wiki_merge_test.go (1)
25-29: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove review-history text from test comments.
Document the current contract. Do not retain CodeRabbit severity labels or descriptions of prior faulty implementations.
internal/ingestion/knowledge_compile/wiki_merge_test.go#L25-L29: replace the comment with the current wiki replacement contract.internal/ingestion/knowledge_compile/dedup_test.go#L100-L105: replace the comment with the current original-index mapping contract.internal/ingestion/knowledge_compile/dedup_test.go#L134-L135: remove the prior-bug explanation because the positive assertions already define the required behavior.As per coding guidelines, remove stale documentation and recovery notes, and keep Go 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/ingestion/knowledge_compile/wiki_merge_test.go` around lines 25 - 29, Remove review-history and prior-bug wording from the comments at internal/ingestion/knowledge_compile/wiki_merge_test.go:25-29, internal/ingestion/knowledge_compile/dedup_test.go:100-105, and internal/ingestion/knowledge_compile/dedup_test.go:134-135. Update the wiki merge comment to state only the current wiki replacement contract, update the original-index comment to state only the current mapping contract, and remove the redundant prior-bug explanation at the final site while preserving the positive assertions.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.
Nitpick comments:
In `@internal/ingestion/knowledge_compile/wiki_merge_test.go`:
- Around line 25-29: Remove review-history and prior-bug wording from the
comments at internal/ingestion/knowledge_compile/wiki_merge_test.go:25-29,
internal/ingestion/knowledge_compile/dedup_test.go:100-105, and
internal/ingestion/knowledge_compile/dedup_test.go:134-135. Update the wiki
merge comment to state only the current wiki replacement contract, update the
original-index comment to state only the current mapping contract, and remove
the redundant prior-bug explanation at the final site while preserving the
positive assertions.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 278fc24c-208c-400f-a82b-c25090909cee
📒 Files selected for processing (8)
internal/ingestion/component/knowledge_compiler/wiki/prompt.gointernal/ingestion/component/knowledge_compiler/wiki/wiki.gointernal/ingestion/knowledge_compile/consumer.gointernal/ingestion/knowledge_compile/dedup.gointernal/ingestion/knowledge_compile/dedup_test.gointernal/ingestion/knowledge_compile/reader.gointernal/ingestion/knowledge_compile/wiki_merge.gointernal/ingestion/knowledge_compile/wiki_merge_test.go
🚧 Files skipped from review as they are similar to previous changes (6)
- internal/ingestion/component/knowledge_compiler/wiki/prompt.go
- internal/ingestion/knowledge_compile/dedup.go
- internal/ingestion/component/knowledge_compiler/wiki/wiki.go
- internal/ingestion/knowledge_compile/wiki_merge.go
- internal/ingestion/knowledge_compile/consumer.go
- internal/ingestion/knowledge_compile/reader.go
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@internal/ingestion/pipeline/template/ingestion_pipeline_knowledge_compiler.json`:
- Around line 190-192: Set a non-empty template selector in the compilation
template configuration alongside llm_id so component-scoped Doc.ParserConfig can
compile successfully. Update the relevant load path and add a test covering a
valid selector, ensuring ParseParam accepts the resulting compiler
configuration.
🪄 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: 08b13c96-0460-4776-b5ca-5e7ab78b6bcb
📒 Files selected for processing (3)
agent/templates/compiler.jsoninternal/ingestion/pipeline/template/ingestion_pipeline_knowledge_compiler.jsoninternal/ingestion/task/pipeline_executor_defaults_test.go
| "compilation_template_group_id": "", | ||
| "llm_id": "", | ||
| "variant": "structure", | ||
| "language": "English" | ||
| "plan": false |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
rg -n -C 12 'ParseParam\(' internal/ingestion --glob '*.go'
rg -n -C 8 'compilation_template_(id|group_id)' internal/ingestion agent --glob '*.go' --glob '*.json'Repository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- candidate pipeline/template consumers ---'
rg -n -C 8 'ingestion_pipeline_knowledge_compiler|pipeline/template|NewPipelineFromDSL|default.*pipeline|pipeline.*default|template.*pipeline' internal agent --glob '*.go' --glob '*.json' --glob '*.py' --glob '*.ts' --glob '*.tsx' | head -n 500
printf '%s\n' '--- relevant pipeline loading and parameter binding symbols ---'
rg -n -C 12 'func (NewPipelineFromDSL|.*Pipeline.*DSL)|json.Unmarshal|params|ComponentFactory|DefaultFactory' internal/ingestion/pipeline --glob '*.go' | head -n 500
printf '%s\n' '--- all references to the exact template filename or compiler node ---'
rg -n -C 10 'ingestion_pipeline_knowledge_compiler\.json|Compiler:KnownSwiftLions|KnownSwiftLions' . --glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' | head -n 400Repository: infiniflow/ragflow
Length of output: 50377
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- exact references ---'
rg -n 'ingestion_pipeline_knowledge_compiler\.json|KnownSwiftLions|compilation_template_group_id.*=' . \
--glob '!node_modules/**' --glob '!dist/**' --glob '!build/**' \
--glob '*.go' --glob '*.py' --glob '*.ts' --glob '*.tsx' --glob '*.json' \
| head -n 300
printf '%s\n' '--- pipeline parser implementation ---'
rg -n -C 20 'func NewPipelineFromDSL|NewPipelineFromDSL\(' internal/ingestion/pipeline --glob '*.go'
printf '%s\n' '--- compiler-related template tests ---'
rg -n -C 20 'template.*Compiler|Compiler.*template|templateUsesComponent|knowledge_compiler' internal/ingestion/pipeline --glob '*_test.go' | head -n 500
printf '%s\n' '--- exact JSON parameter shape ---'
python3 - <<'PY'
import json
from pathlib import Path
p = Path("internal/ingestion/pipeline/template/ingestion_pipeline_knowledge_compiler.json")
data = json.loads(p.read_text())
for name, node in data.get("components", {}).items():
if node.get("obj", {}).get("component_name") == "Compiler":
print(name, node["obj"].get("params"))
PYRepository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- NewPipelineFromDSL construction path ---'
sed -n '140,260p' internal/ingestion/pipeline/pipeline.go
printf '%s\n' '--- knowledge compiler template test ---'
sed -n '1,110p' internal/ingestion/pipeline/pipeline_knowledge_compiler_test.go
printf '%s\n' '--- compiler parameter injection and execution call sites ---'
rg -n -C 15 'ParseParam|DefaultFactory|ExtractAllComponentParams|parser_config|compilation_template_group_id|knowledge_compiler' internal/ingestion internal/service api rag \
--glob '*.go' --glob '*.py' | grep -v 'pipeline_executor_defaults_test.go' | head -n 700
printf '%s\n' '--- service tests for compiler parameters ---'
sed -n '1,180p' internal/service/component_scoped_parser_config_test.go
sed -n '90,145p' internal/service/dataset/create_test.goRepository: infiniflow/ragflow
Length of output: 50376
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- pipeline compilation and component factory calls ---'
rg -n -C 18 'Compile\(|buildNodeBody|WithComponentFactory|factory\(' internal/ingestion/pipeline internal/agent/runtime --glob '*.go' | head -n 500
printf '%s\n' '--- component-scoped configuration implementation ---'
rg -n -C 30 'func ApplyComponentScopedParserConfig|ApplyComponentScopedParserConfig' internal/service --glob '*.go'
rg -n -C 20 'func LoadPipelineDSL|LoadPipelineDSL|BuildParserConfig' internal/service internal/ingestion/pipeline --glob '*.go'
printf '%s\n' '--- document/task runtime override construction ---'
rg -n -C 20 'override_params|ParserConfig.*pipeline|PipelineID|LoadPipelineDSL' internal/service internal/ingestion/task --glob '*.go' | head -n 700Repository: infiniflow/ragflow
Length of output: 50375
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' '--- complete component-scoped configuration ---'
cat -n internal/service/component_scoped_parser_config.go
printf '%s\n' '--- pipeline execution entry points ---'
rg -n -C 20 'NewPipelineFromDSL|\.Run\(.*override|overrideParams|WithComponentFactory' internal/ingestion/task internal/service --glob '*.go' | grep -E 'pipeline|Pipeline|override|Run|NewPipeline|WithComponent' | head -n 500
printf '%s\n' '--- parser configuration builders and defaults ---'
rg -n -C 18 'ResolveComponentParamsDefaults|BuildParserConfig|ExtractAllComponentParams|ComponentParamsDefaults' internal/ingestion internal/service --glob '*.go' | head -n 500Repository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
sed -n '390,535p' internal/ingestion/task/pipeline_executor.go
printf '%s\n' '--- all parser_config mutations in pipeline executor ---'
rg -n -C 10 'parserConfig|overrideParams|BuildParserPageCapOverride' internal/ingestion/task/pipeline_executor.go
printf '%s\n' '--- dataset creation parser config source ---'
sed -n '70,145p' internal/service/dataset/crud.go
sed -n '275,310p' internal/service/dataset/update.goRepository: infiniflow/ragflow
Length of output: 14643
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
python3 - <<'PY'
import json
from pathlib import Path
template = json.loads(Path("internal/ingestion/pipeline/template/ingestion_pipeline_knowledge_compiler.json").read_text())
compiler = [
node["obj"]["params"]
for node in template["components"].values()
if node.get("obj", {}).get("component_name") == "Compiler"
]
assert len(compiler) == 1, compiler
params = compiler[0]
selectors = {
key: params.get(key)
for key in ("compilation_template_id", "compilation_template_group_id")
if key in params
}
print("compiler_params:", params)
print("selectors:", selectors)
print("has_nonempty_selector:", any(isinstance(v, str) and v.strip() for v in selectors.values()))
executor = Path("internal/ingestion/task/pipeline_executor.go").read_text()
assert "pipe.Run(ctx, inputs, parserConfig)" in executor
assert "parserConfig := map[string]interface{}(s.taskCtx.Doc.ParserConfig)" in executor
print("executor_passes_doc_parser_config_as_override:", True)
scoped = Path("internal/service/component_scoped_parser_config.go").read_text()
compiler_case = scoped[scoped.index('case strings.HasPrefix(cpnLower, "compiler:")'):scoped.index("\n\t\t}", scoped.index('case strings.HasPrefix(cpnLower, "compiler:")'))]
print("compiler_scoped_override:", "llm_id" if "params[\"llm_id\"]" in compiler_case else "none")
print("compiler_scoped_override_sets_template_selector:",
"compilation_template_id" in compiler_case or
"compilation_template_group_id" in compiler_case)
PYRepository: infiniflow/ragflow
Length of output: 252
🏁 Script executed:
#!/usr/bin/env bash
set -euo pipefail
python3 - <<'PY'
import json
from pathlib import Path
raw = json.loads(Path("internal/ingestion/pipeline/template/ingestion_pipeline_knowledge_compiler.json").read_text())
template = raw.get("dsl", raw)
compiler = [
node["obj"]["params"]
for node in template["components"].values()
if node.get("obj", {}).get("component_name") == "Compiler"
]
assert len(compiler) == 1, compiler
params = compiler[0]
selectors = {
key: params.get(key)
for key in ("compilation_template_id", "compilation_template_group_id")
if key in params
}
print("compiler_params:", params)
print("selectors:", selectors)
print("has_nonempty_selector:", any(isinstance(v, str) and v.strip() for v in selectors.values()))
executor = Path("internal/ingestion/task/pipeline_executor.go").read_text()
assert "pipe.Run(ctx, inputs, parserConfig)" in executor
assert "parserConfig := map[string]interface{}(s.taskCtx.Doc.ParserConfig)" in executor
print("executor_passes_doc_parser_config_as_override:", True)
scoped = Path("internal/service/component_scoped_parser_config.go").read_text()
start = scoped.index('case strings.HasPrefix(cpnLower, "compiler:")')
end = scoped.index("\n\t\t}", start)
compiler_case = scoped[start:end]
print("compiler_scoped_override_sets_llm_id:", 'params["llm_id"]' in compiler_case)
print("compiler_scoped_override_sets_template_selector:",
"compilation_template_id" in compiler_case or
"compilation_template_group_id" in compiler_case)
PYRepository: infiniflow/ragflow
Length of output: 468
Provide a non-empty template selector before compilation.
This template cannot run without a selector in component-scoped Doc.ParserConfig. The existing overlay injects only llm_id, so ParseParam rejects the compiler. Add a load-path test with a valid selector.
🤖 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/ingestion/pipeline/template/ingestion_pipeline_knowledge_compiler.json`
around lines 190 - 192, Set a non-empty template selector in the compilation
template configuration alongside llm_id so component-scoped Doc.ParserConfig can
compile successfully. Update the relevant load path and add a test covering a
valid selector, ensuring ParseParam accepts the resulting compiler
configuration.
Port the wiki_incremental dataset-level merge and make its rewrite barrier durable and concurrency-safe. Wiki pages merge replace-only; the barrier persists a monotonic numeric generation, and a scheduler-backed per-dataset lock closes the cross-process TOCTOU window. Adds the Compiler Plan toggle (frontend) with Mode A grouping.