Repository navigation
feat(go): port knowledge compilation template/group + wiki artifact/nav/skill REST APIs from Python - #17656
Conversation
Port the knowledge compilation template/group REST APIs to Go: groups full CRUD with nested child templates, templates expose GET builtins + GET wiki-presets. Includes gorm DAO, services, handlers, router wiring, and orphan/invalid-template cleanup matching Python behavior. Co-authored-by: Zhichang Yu <[email protected]>
|
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:
📝 WalkthroughWalkthroughAdds compilation-template validation and group CRUD, dataset-artifact APIs, page-edit audit commits with parent linking, provider identifier updates, and server/router registration. ChangesCompilation template management
Dataset artifact APIs
File commit audit
Provider route parameter migration
Server and router integration
Estimated code review effort: 4 (Complex) | ~75 minutes Sequence Diagram(s)sequenceDiagram
participant Client
participant CompilationTemplateGroupHandler
participant CompilationTemplateGroupService
participant CompilationTemplateGroupDAO
participant Database
Client->>CompilationTemplateGroupHandler: POST/PUT group request
CompilationTemplateGroupHandler->>CompilationTemplateGroupService: CreateGroup or UpdateGroup
CompilationTemplateGroupService->>CompilationTemplateGroupService: Validate request
CompilationTemplateGroupService->>CompilationTemplateGroupDAO: Create or Update
CompilationTemplateGroupDAO->>Database: Insert or Update record
Database-->>CompilationTemplateGroupDAO: Result
CompilationTemplateGroupDAO-->>CompilationTemplateGroupService: Persisted entity
CompilationTemplateGroupService->>CompilationTemplateGroupService: Convert to response
CompilationTemplateGroupService-->>CompilationTemplateGroupHandler: GroupListItem
CompilationTemplateGroupHandler-->>Client: Standardized response
sequenceDiagram
participant Client
participant DatasetArtifactHandler
participant DatasetArtifactService
participant DocumentEngine
participant FileCommitService
Client->>DatasetArtifactHandler: Authenticated artifact request
DatasetArtifactHandler->>DatasetArtifactService: Execute artifact operation
DatasetArtifactService->>DocumentEngine: Search or update artifacts
alt Content update
DatasetArtifactService->>FileCommitService: RecordPageEdit with old/new content
FileCommitService->>FileCommitService: Generate unified diff
end
DocumentEngine-->>DatasetArtifactService: Artifact result
DatasetArtifactService-->>DatasetArtifactHandler: Response model
DatasetArtifactHandler-->>Client: Standardized response
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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: 5
🧹 Nitpick comments (7)
internal/service/compilation_template_group_service.go (1)
356-365: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the unused
seenparameter.
insertChildrennever readsseen. The only caller at Line 132 passesnil. The doc comment describes behavior that the function does not implement.Delete the parameter and correct the comment.
♻️ Proposed refactor
-// insertChildren inserts new child templates. usedForReconcile controls whether -// the duplicate-name guard applies (create always; reconcile passes seen set). -func (s *CompilationTemplateGroupService) insertChildren(ctx context.Context, tenantID, groupID string, templates []*GroupTemplate, seen map[string]struct{}) error { +// insertChildren inserts new child templates and rejects duplicate names +// inside the group. +func (s *CompilationTemplateGroupService) insertChildren(ctx context.Context, tenantID, groupID string, templates []*GroupTemplate) error {- if err := s.insertChildren(ctx, tenantID, group.ID, req.Templates, nil); err != nil { + if err := s.insertChildren(ctx, tenantID, group.ID, req.Templates); err != nil {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/compilation_template_group_service.go` around lines 356 - 365, Remove the unused seen parameter from insertChildren, update its documentation to describe only the duplicate-name validation it performs, and adjust the caller to use the new signature.internal/handler/compilation_template_group.go (3)
152-157: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winMap service errors to distinct response codes.
Both branches return
common.CodeDataErrorfor every error.CreateGroupandUpdateGroupreturn*service.GroupValidationErrorfor payload problems and plain DB errors for infrastructure failures. A database outage therefore reports a client data error.Use
errors.Asto detect*service.GroupValidationError, and returncommon.CodeExceptionErrorfor the remaining errors.Also applies to: 196-200
🤖 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/handler/compilation_template_group.go` around lines 152 - 157, Update the error handling in the CreateGroup and UpdateGroup handlers to use errors.As for *service.GroupValidationError; return common.CodeDataError for validation errors and common.CodeExceptionError for all other service errors, while preserving the existing error message and early-return behavior.
143-151: 🗄️ Data Integrity & Integration | 🔵 TrivialAdd a unique constraint for the group name.
The check-then-create sequence is not atomic. Two concurrent requests with the same name both pass
NameExistsand both create a group. Add a unique index on(tenant_id, name)for valid rows, and handle the duplicate-key error in the create path.🤖 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/handler/compilation_template_group.go` around lines 143 - 151, Make compilation template group names unique at the database level by adding a partial unique index on (tenant_id, name) for valid rows. Update the create path around NameExists and the subsequent creation call to recognize duplicate-key violations and return the existing duplicate-name response, while retaining NameExists for early validation.
72-90: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy liftPagination happens after the full result set is materialized.
ListSavedreturns every group for the tenant.buildGroupItemininternal/service/compilation_template_group_service.goLines 241-257 runs oneListByGroupquery per group, andfillConfigDefaultLLMruns one tenant query per child. The handler then discards the rows outside the requested page. The query count grows with the total group and child count, not withpage_size.Push
pageandpage_sizeinto the DAO query. Load the children for the returned page only, and resolve the tenant default model once per request.🤖 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/handler/compilation_template_group.go` around lines 72 - 90, The compilation template group listing currently materializes all groups and child data before slicing in the handler. Update the flow centered on ListSaved, buildGroupItem, and fillConfigDefaultLLM so page and page_size are applied in the DAO query, only returned-page groups load children, and the tenant default model is resolved once per request; remove the handler-side full-result pagination while preserving total-count reporting.internal/service/compilation_template_service.go (3)
149-181: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winConsider caching the preset files.
LoadWikiPresetsreads the directory and every YAML file on each request. The endpoint atinternal/handler/compilation_template.goLines 66-78 is authenticated but otherwise unbounded, so each call performs filesystem I/O on the request thread. The data is static content shipped with the deployment.Load the presets once and reuse the parsed result. Also log the skipped files at Lines 167 and 171, because a malformed YAML file currently disappears without a signal.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/compilation_template_service.go` around lines 149 - 181, Update CompilationTemplateService.LoadWikiPresets to cache the successfully parsed preset slice and reuse it on subsequent calls instead of rereading the directory and YAML files; protect initialization for concurrent requests and avoid caching failed directory reads. Add logging for files skipped after os.ReadFile failures and YAML unmarshalling failures, including the filename and error details, while preserving the existing behavior of ignoring invalid files.
302-346: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winReport seeding failures instead of discarding them.
seedBuiltinsreturnsnilfor everyos.ReadDirerror at Line 306, and it discards eachupsertBuiltinerror at Line 343. A misconfigured directory or a failing write then produces an empty built-in palette with no diagnostic.Log the discarded errors, and return the
os.ReadDirerror when it is notos.IsNotExist.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/compilation_template_service.go` around lines 302 - 346, Update seedBuiltins to return the os.ReadDir error unless os.IsNotExist(err), while preserving the nil result for an absent directory. Capture errors returned by upsertBuiltin and log them with sufficient context instead of discarding them.
36-39: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the migration-history references from the doc comments. The new files document each symbol by naming its Python counterpart ("mirrors Python …", "mirroring the Python …"). The coding guidelines require doc comments that describe the current runtime path, not the migration source. Describe the Go behavior instead.
internal/service/compilation_template_service.go#L36-L39: describe the lazy default-LLM fill without the Python function name; apply the same edit to the comments at Lines 70-71, 82-83, 92-93, 116-118, 147-148, 183-185, 285-286, and 299-301.internal/dao/compilation_template.go#L207-L211: state the purge behavior and drop the_purge_stale_invalid_childrenreference; apply the same edit at Lines 127-129, 141-142, and 154-156.internal/dao/compilation_template_group.go#L36-L38: drop thelist_saved()reference; apply the same edit at Lines 78-79 and 104.internal/service/compilation_template_group_service.go#L391-L393: describe the reconciliation rules directly; apply the same edit at Lines 61-62, 78-79, 90-91, 110-111, 138-139, 181-182, 220-223, 269-270, 293, 311-312, and 466-467.internal/handler/compilation_template.go#L26-L27: remove the blueprint reference from the type comment.internal/handler/compilation_template_group.go#L28-L29: remove the blueprint reference from the type comment.As per coding guidelines: "keep package and doc comments aligned with the current runtime path rather than migration history" and "remove stale superseded comments and documentation".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/compilation_template_service.go` around lines 36 - 39, Remove migration-history and Python/blueprint references from the affected doc comments, rewriting them to describe current Go runtime behavior. Update internal/service/compilation_template_service.go lines 36-39, 70-71, 82-83, 92-93, 116-118, 147-148, 183-185, 285-286, and 299-301 to describe lazy default-LLM filling; internal/dao/compilation_template.go lines 207-211, 127-129, 141-142, and 154-156 to describe purge behavior; internal/dao/compilation_template_group.go lines 36-38, 78-79, and 104 to describe current listing behavior; and internal/service/compilation_template_group_service.go lines 391-393, 61-62, 78-79, 90-91, 110-111, 138-139, 181-182, 220-223, 269-270, 293, 311-312, and 466-467 to describe reconciliation rules directly. Also remove blueprint references from the type comments in internal/handler/compilation_template.go lines 26-27 and internal/handler/compilation_template_group.go lines 28-29.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/dao/compilation_template.go`:
- Around line 207-217: Update HardDeleteOrphansByName to scope the deletion to
the relevant group, adding the caller’s group_id to its predicate and method
inputs, or alternatively change it to accept and delete the specific
soft-deleted template ID. Update the call in the compilation template group
service so only the child just soft-deleted is purged, while preserving the
existing tenant, name, built-in, and invalid-status filters.
In `@internal/service/compilation_template_group_service.go`:
- Around line 112-136: Wrap the persistence operations in CreateGroup and
UpdateGroup in a single GORM transaction, including group creation or field
updates and all insertChildren/reconcileChildren calls. Propagate any validation
or write error from the transaction callback so GORM rolls back the group and
every child write, and only call GetSaved after a successful commit.
- Around line 406-459: Update the positional fallback in the template-processing
loop to skip entries whose IDs are already present in retained, selecting the
next unretained current template instead of blindly using current[index].
Preserve explicit child.ID matching and ensure each submitted child binds to a
distinct existing row, preventing an unselected row from being deleted.
In `@internal/service/compilation_template_service.go`:
- Around line 348-359: Update upsertBuiltin to call Save only when
templateDAO.GetByID returns gorm.ErrRecordNotFound; propagate all other errors
immediately, and retain the existing update path when a record is found. Add the
required gorm.io/gorm import.
- Around line 219-279: Missing field keys are converted to "<nil>" and
incorrectly satisfy required-field validation. In the compilation template
validation loop and the claim/concept checks, replace every direct
fmt.Sprint(fm["..."]) field read with the existing nil-safe helper, including
type, description, rule, statement, subject, term, and definition_excerpt, while
preserving the current trimming, length, and duplicate checks.
---
Nitpick comments:
In `@internal/handler/compilation_template_group.go`:
- Around line 152-157: Update the error handling in the CreateGroup and
UpdateGroup handlers to use errors.As for *service.GroupValidationError; return
common.CodeDataError for validation errors and common.CodeExceptionError for all
other service errors, while preserving the existing error message and
early-return behavior.
- Around line 143-151: Make compilation template group names unique at the
database level by adding a partial unique index on (tenant_id, name) for valid
rows. Update the create path around NameExists and the subsequent creation call
to recognize duplicate-key violations and return the existing duplicate-name
response, while retaining NameExists for early validation.
- Around line 72-90: The compilation template group listing currently
materializes all groups and child data before slicing in the handler. Update the
flow centered on ListSaved, buildGroupItem, and fillConfigDefaultLLM so page and
page_size are applied in the DAO query, only returned-page groups load children,
and the tenant default model is resolved once per request; remove the
handler-side full-result pagination while preserving total-count reporting.
In `@internal/service/compilation_template_group_service.go`:
- Around line 356-365: Remove the unused seen parameter from insertChildren,
update its documentation to describe only the duplicate-name validation it
performs, and adjust the caller to use the new signature.
In `@internal/service/compilation_template_service.go`:
- Around line 149-181: Update CompilationTemplateService.LoadWikiPresets to
cache the successfully parsed preset slice and reuse it on subsequent calls
instead of rereading the directory and YAML files; protect initialization for
concurrent requests and avoid caching failed directory reads. Add logging for
files skipped after os.ReadFile failures and YAML unmarshalling failures,
including the filename and error details, while preserving the existing behavior
of ignoring invalid files.
- Around line 302-346: Update seedBuiltins to return the os.ReadDir error unless
os.IsNotExist(err), while preserving the nil result for an absent directory.
Capture errors returned by upsertBuiltin and log them with sufficient context
instead of discarding them.
- Around line 36-39: Remove migration-history and Python/blueprint references
from the affected doc comments, rewriting them to describe current Go runtime
behavior. Update internal/service/compilation_template_service.go lines 36-39,
70-71, 82-83, 92-93, 116-118, 147-148, 183-185, 285-286, and 299-301 to describe
lazy default-LLM filling; internal/dao/compilation_template.go lines 207-211,
127-129, 141-142, and 154-156 to describe purge behavior;
internal/dao/compilation_template_group.go lines 36-38, 78-79, and 104 to
describe current listing behavior; and
internal/service/compilation_template_group_service.go lines 391-393, 61-62,
78-79, 90-91, 110-111, 138-139, 181-182, 220-223, 269-270, 293, 311-312, and
466-467 to describe reconciliation rules directly. Also remove blueprint
references from the type comments in internal/handler/compilation_template.go
lines 26-27 and internal/handler/compilation_template_group.go lines 28-29.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: a5e61349-aefd-460d-83ba-5265282694b1
📒 Files selected for processing (8)
cmd/ragflow_server.gointernal/dao/compilation_template.gointernal/dao/compilation_template_group.gointernal/handler/compilation_template.gointernal/handler/compilation_template_group.gointernal/router/router.gointernal/service/compilation_template_group_service.gointernal/service/compilation_template_service.go
…APIs Add dataset artifact, structure/graph, navigation and skill REST endpoints backed by the document engine, plus rename providers route path params provider_name/instance_name to provider_id_or_name/instance_id_or_name (JSON body contract unchanged). Co-authored-by: Zhichang Yu <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 11
🧹 Nitpick comments (4)
internal/service/dataset_artifact_service.go (4)
646-674: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCollapse the duplicate navigation types.
NavChildItemhas the same fields and JSON tags asNavigationItem, andListNavChildrendiffers fromListNavClustersonly in the extranav_cluster_kwdfilter and thenav_child_kwdselect field. Keep one type and one parse loop.Based on the coding guideline "collapse duplicate implementations".
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/dataset_artifact_service.go` around lines 646 - 674, Remove the duplicate NavChildItem type and reuse NavigationItem for child results. Refactor ListNavChildren and the shared navigation parsing flow around ListNavClusters so both methods use one parse loop, preserving the child-specific nav_cluster_kwd filter and nav_child_kwd selected field while retaining the existing JSON output and counts.Source: Coding guidelines
342-345: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winDrop the redundant
from_kwdterm list.
fromKwdsrepeats every entity slug, up to 1000 terms, in the relation filter. The relations are already scoped to the same dataset andcompile_kwd, so the term list mainly enlarges the query. It also silently drops relations whose source entity fell outside the 1000-entity cap. Query the relations bycompile_kwdalone, then discard the relations whosefrom_kwdis not in the entity set in Go.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/dataset_artifact_service.go` around lines 342 - 345, Update the relation lookup in the fromKwds branch of the surrounding dataset artifact service method to filter only by CompileKwdWikiRelation, removing the from_kwd term list from searchCompiled. After retrieval, retain only relations whose from_kwd belongs to the loaded entity set before processing them, so relations outside the capped entity collection are discarded in Go.
32-42: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove unused compile-keyword constants.
CompileKwdSkill,CompileKwdRaptorGraph,CompileKwdStructureIndex,CompileKwdStructureEntity,CompileKwdStructureRelation, andCompileKwdStructureCommunityare only declared and have no repository consumers. Delete them and keep the public surface minimal.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/dataset_artifact_service.go` around lines 32 - 42, Remove the unused constants CompileKwdSkill, CompileKwdRaptorGraph, CompileKwdStructureIndex, CompileKwdStructureEntity, CompileKwdStructureRelation, and CompileKwdStructureCommunity from the compile-keyword declarations, while retaining CompileKwdSkillAll, CompileKwdDatasetNav, and CompileKwdStructure.Source: Coding guidelines
61-64: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReuse the tenant search index-name helper instead of hardcoding the prefix.
wikiIndexName(tenantID)returns the search index used by searches, updates, and deletes. A package-level helper likeinternal/service/toc_enhancer.go’sgetIndexNamealready encapsulatesragflow_+tenantID; use that helper or add a shared helper instead of keeping this prefix local towikiIndexName.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/dataset_artifact_service.go` around lines 61 - 64, Update wikiIndexName to reuse the existing tenant index-name helper, such as getIndexName, rather than formatting the ragflow_ prefix locally; if needed, move the logic into a shared package-level helper and use it consistently for searches, updates, and deletes.
🤖 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/handler/dataset_artifact.go`:
- Around line 84-91: Update the query-parameter normalization around pageSize in
the dataset artifact handler to clamp values above the supported maximum, in
addition to the existing lower-bound fallback. Reuse an existing page-size limit
constant or define the handler’s intended maximum, ensuring the value passed to
the engine search limit can never exceed it.
- Around line 42-55: Update DatasetArtifactHandler.datasetOwner to return only
the successful tenant ID and an ok status, and call common.ErrorWithCode(c,
code, msg) on every failure path. Preserve GetUser’s unauthorized code, map
missing or lookup-failed knowledgebases to common.CodeNotFound, and use
common.CodePermissionError for inaccessible datasets so callers no longer return
an empty HTTP 200.
In `@internal/handler/providers.go`:
- Line 134: Update ShowProvider, ListModels, and ShowModel to resolve
provider_id_or_name through the database-backed provider record before calling
name-only ProviderManager methods, or restrict the route to provider names.
Apply the same ID/name resolution to ListProviderInstances and DeleteProvider
before passing the value to service methods that expect provider_name.
In `@internal/service/dataset_artifact_service.go`:
- Around line 5-9: The Apache license headers are corrupted in both new files.
Update internal/service/dataset_artifact_service.go lines 5-9 to restore “in
compliance with the License” and “either express or implied,” and update
internal/handler/dataset_artifact.go line 9 to “either express or implied.”
- Around line 24-26: Update doc comments in
internal/service/dataset_artifact_service.go at lines 24-26 and 51-53 by
removing the Python-origin and endpoint-mirroring sentences. At lines 205-208,
replace the migration-history explanation with documentation describing the
partial field update and refreshed page return; correct the misspelled
“knowledge” reference if any remains.
- Around line 327-341: The numeric field parsing in
internal/service/dataset_artifact_service.go#L327-L341, `#L578-L581`, `#L663-L666`,
and `#L698-L704` should use one shared intValue helper instead of float64-only
assertions. Implement intValue to handle supported numeric types, strings, and
list-valued inputs, then apply it to weight_int in GetWikiGraph, count_int in
ListNavClusters and ListNavChildren, and outlinks_int/inlinks_int in
GetSkillTree.
- Around line 73-76: Update the filter merge in the dataset artifact service so
caller entries are copied first, then assign the dataset-scoped kb_id value
afterward. Ensure the final kb_id scope always wins, matching the scalar-value
behavior used by GetDocumentGraph and DeleteDocumentGraph.
- Around line 506-513: Update the filter construction in searchCompiled and
DeleteDocumentGraph to use []string for doc_id, and remove the kb_id entry so
the dataset scope established by searchCompiled is preserved. Keep the existing
compiled_graph_kwd and optional FieldGraphType filters unchanged.
- Around line 387-392: Update the WikiAlteration construction in the affected
service method: either compute and populate Removed, NewlyUploaded,
RemovedDocIDs, and NewlyUploadedDocIDs, or explicitly represent the operation as
unimplemented while preserving that distinction. Always initialize all response
slices to non-nil empty slices when no values exist, and sort the map-derived
ids before assigning InvolvedDocIDs and EligibleDocIDs so output order is
deterministic.
- Around line 227-243: Validate the chunk id before constructing the update
condition in the surrounding dataset artifact service flow: replace the
discarded assertion on chunks[0]["id"] with checked validation and return an
error when the field is missing or not a string (including an empty value). Only
call docEngine.UpdateChunks after a valid id has been established, preserving
the existing update payload behavior.
- Around line 261-287: Update the topic aggregation around searchCompiled so the
returned total equals the number of aggregated topics, not the engine chunk
total. Remove or otherwise account for the 1000-chunk cap so PageCount and
topics include the full dataset. Before returning, sort items deterministically
(for example by Topic) instead of relying on metas map iteration order.
---
Nitpick comments:
In `@internal/service/dataset_artifact_service.go`:
- Around line 646-674: Remove the duplicate NavChildItem type and reuse
NavigationItem for child results. Refactor ListNavChildren and the shared
navigation parsing flow around ListNavClusters so both methods use one parse
loop, preserving the child-specific nav_cluster_kwd filter and nav_child_kwd
selected field while retaining the existing JSON output and counts.
- Around line 342-345: Update the relation lookup in the fromKwds branch of the
surrounding dataset artifact service method to filter only by
CompileKwdWikiRelation, removing the from_kwd term list from searchCompiled.
After retrieval, retain only relations whose from_kwd belongs to the loaded
entity set before processing them, so relations outside the capped entity
collection are discarded in Go.
- Around line 32-42: Remove the unused constants CompileKwdSkill,
CompileKwdRaptorGraph, CompileKwdStructureIndex, CompileKwdStructureEntity,
CompileKwdStructureRelation, and CompileKwdStructureCommunity from the
compile-keyword declarations, while retaining CompileKwdSkillAll,
CompileKwdDatasetNav, and CompileKwdStructure.
- Around line 61-64: Update wikiIndexName to reuse the existing tenant
index-name helper, such as getIndexName, rather than formatting the ragflow_
prefix locally; if needed, move the logic into a shared package-level helper and
use it consistently for searches, updates, and deletes.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 94e2368b-791f-4b30-8678-fff789b351b7
📒 Files selected for processing (5)
cmd/ragflow_server.gointernal/handler/dataset_artifact.gointernal/handler/providers.gointernal/router/router.gointernal/service/dataset_artifact_service.go
🚧 Files skipped from review as they are similar to previous changes (1)
- cmd/ragflow_server.go
|
|
||
| func (h *ProviderHandler) ShowProvider(c *gin.Context) { | ||
| providerName := c.Param("provider_name") | ||
| providerName := c.Param("provider_id_or_name") |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
ast-grep outline internal/handler/providers.go \
--items all \
--type function \
--match 'ShowProvider|ListModels|ShowModel|CreateProviderInstance|ListProviderInstances|ShowProviderInstance|ShowInstanceBalance|CheckConnection|CheckInstanceConnection|ListTasks|ShowTask|AlterProviderInstance|DropProviderInstance|ListInstanceModels|AlterModel|DropInstanceModels'
rg -n -C 8 --glob '*.go' \
'func .*GetProviderByName|func .*GetModelByName|func .*FindProvider|GetProviderByName\(|GetModelByName\(|FindProvider\(|provider_id_or_name|instance_id_or_name' .
if rg -n --glob '*.go' \
'c\.Param\("(provider_name|instance_name)"\)' \
internal/handler/providers.go internal/router/router.go
then
echo "Legacy provider or instance route parameter access remains." >&2
exit 1
fiRepository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== locate relevant files =="
fd -a 'providers\.go|router\.go|model.*\.go|model.*dao' internal | sed 's#^\./##' | head -100
echo
echo "== handler snippets =="
sed -n '120,180p' internal/handler/providers.go
sed -n '210,245p' internal/handler/providers.go
echo
echo "== router provider route definitions =="
sed -n '1,260p' internal/router/router.go | grep -n -C 5 'provider_id_or_name\|provider_name\|instance_id_or_name\|instance_name'
echo
echo "== targeted provider/provider manager definitions =="
rg -n -C 10 --glob '*.go' \
'func\s+(GetProviderByName|FindProvider|GetModelByName|GetByTenantIDAndProviderName|GetByTenantIDAndProviderID)' internalRepository: infiniflow/ragflow
Length of output: 5606
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== providers handler relevant slices =="
sed -n '1,110p' internal/handler/providers.go
sed -n '130,180p' internal/handler/providers.go
sed -n '220,240p' internal/handler/providers.go
sed -n '300,370p' internal/handler/providers.go
sed -n '440,520p' internal/handler/providers.go
echo
echo "== router provider route definitions =="
rg -n -C 5 --glob '*.go' 'provider_id_or_name|instance_id_or_name|provider_name|instance_name' internal/router/router.go internal/handler/providers.go || true
echo
echo "== relevant DAO/provider manager method definitions =="
rg -n -C 10 --glob '*.go' \
'func\s+\(.*GetModelProviderManager\(\)\)\s+(FindProvider|GetProviderByName|GetProviderByID|ListModels|GetModelByName)|func\s+GetModelProviderManager\s*\(' internal/internal internal | sed -n '1,260p' || true
echo
echo "== tenant provider model DAO methods =="
rg -n -C 8 --glob '*.go' \
'func\s+\([^)]+\)\s+(GetByTenantIDAndProvider|GetByID|GetByProviderIDAndInstance)|func\s+(GetByTenantIDAndProvider|GetByID|GetByProviderIDAndInstance)\(' internal/dao internal/service/model_service.go | sed -n '1,260p' || trueRepository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== ProviderManager type and symbol locations =="
rg -n --glob '*.go' 'type ProviderManager|func \(.*ProviderManager\)|func GetProviderManager\(' internal | sed -n '1,160p'
echo
echo "== GetProviderByName and FindProvider definitions =="
rg -n --glob '*.go' 'func \([^)]*\) GetProviderByName|func GetProviderByName\(|func \([^)]*\) FindProvider\(' internal | sed -n '1,80p'
for sym in \
'func GetModelProviderManager' \
'type ProviderManager struct' \
'func \([^)]*\) GetProviderByName' \
'func FindProvider' \
'func GetProviderByName'; do
echo "--- $sym ---"
rg -n --glob '*.go' "$sym" internal | sed -n '1,40p' || true
done
echo
echo "== targeted ProviderManager methods from candidate files =="
for f in \
internal/dao/database.go \
internal/entity/models/model.go \
internal/entity/models/base_model.go \
internal/service/model_service.go \
internal/router/router.go
do
if [ -f "$f" ]; then
echo "--- $f ---"
rg -n -C 8 'GetProviderByName|FindProvider|ListModels|GetModelByName|provider_id_or_name|instance_id_or_name' "$f" | sed -n '1,220p' || true
fi
doneRepository: infiniflow/ragflow
Length of output: 19682
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== provider table/provider name storage =="
rg -n -C 10 --glob '*.go' 'TenantModelProvider|tenant_model_providers|ProviderName|provider_name|provider_id' internal/dao internal/entity | sed -n '1,260p'
echo
echo "== ShowProviderInstance ShowInstanceBalance service implementation =="
rg -n -C 12 'func \(m \*ModelProviderService\) ShowProviderInstance|func \(m \*ModelProviderService\) ShowInstanceBalance|func \(m \*ModelProviderService\) Get.*Provider.*ID|GetByTenantIDAndProviderID|GetByTenantIDAndProviderName' internal/service/model_service.go internal/dao/tenant_model_provider.go internal/dao/tenant_model_instance.go internal/dao/tenant_model.go | sed -n '1,300p'
echo
echo "== remaining provider_id_or_name handler/service call sites in providers.go =="
rg -n -C 5 --glob '*.go' 'c\.Param\("provider_id_or_name"\)|providerName, instanceName|providerName, .*userID|providerName, apiKey' internal/handler/providers.go internal/service/model_service.go | sed -n '1,320p'Repository: infiniflow/ragflow
Length of output: 50374
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== ProviderManager field and resolver behavior probe =="
python3 - <<'PY'
from pathlib import Path
p = Path('internal/entity/models/model.go')
text = p.read_text()
for needle in [
'func (pm *ProviderManager) GetProviderByName',
'func (pm *ProviderManager) ListModels',
'func (pm *ProviderManager) GetModelByName',
'func (pm *ProviderManager) FindProvider',
'type Provider struct',
'ProviderID',
]:
idx = text.find(needle)
print(f'{needle}: {idx}')
if idx >= 0:
start = max(0, text.rfind('\n', 0, idx-400)) if idx > 400 else 0
end = text.find('\n}', idx)
print(text[start:end][:2200])
print('---')
print('contains ProviderID field:', 'ProviderID' in text)
print('contains ID-based provider lookup methods nearby:', 'ID' in text[text.find('type ProviderManager'):text.find('func (pm *ProviderManager) ListProviders'),text.find('func (pm *ProviderManager) ListProviders')+2500]))
PY
echo
echo "== GetProviderByName ID/name implementation detail =="
sed -n '450,470p' internal/entity/models/model.go
sed -n '787,795p' internal/entity/models/model.go
echo
echo "== ListProviderInstances service implementation =="
rg -n -C 12 'func \(m \*ModelProviderService\) ListProviderInstances|CreateNameOnlyProviderInstance' internal/service/model_service.go | sed -n '1,220p'
echo
echo "== remaining unresolved provider_id_or_name service entry points =="
rg -n --glob '*.go' 'providerName = c\.Param\("provider_id_or_name"\)|ListProviderInstances\(|DeleteModelProvider\(|CreateProviderInstance\(/' internal/handler/providers.go internal/service/model_service.go | sed -n '1,200p'Repository: infiniflow/ragflow
Length of output: 717
Resolve provider IDs before calling name-only manager lookups.
ShowProvider, ListModels, and ShowModel use provider_id_or_name, but ProviderManager.FindProvider compares only Provider.Name, so catalog requests that pass a provider ID return not found. Use an ID/name resolver through the database-backed provider record before calling these methods, or keep this route name-only. Also update ListProviderInstances/DeleteProvider, which pass the same value directly to service methods that resolve tenant providers by provider_name.
🤖 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/handler/providers.go` at line 134, Update ShowProvider, ListModels,
and ShowModel to resolve provider_id_or_name through the database-backed
provider record before calling name-only ProviderManager methods, or restrict
the route to provider names. Apply the same ID/name resolution to
ListProviderInstances and DeleteProvider before passing the value to service
methods that expect provider_name.
| return &WikiAlteration{ | ||
| Removed: 0, | ||
| NewlyUploaded: 0, | ||
| InvolvedDocIDs: ids, | ||
| EligibleDocIDs: ids, | ||
| }, nil |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
The alteration response is a stub and emits null slices.
Removed and NewlyUploaded are hardcoded to 0, and RemovedDocIDs and NewlyUploadedDocIDs stay nil. Clients cannot tell "no alterations" from "not computed", and the nil slices serialize as JSON null instead of []. The ids order is also nondeterministic, because the code iterates a map.
Compute the removed and newly uploaded sets, or make the unimplemented state explicit. Initialize the slices either way.
🐛 Proposed fix for the empty slices and the order
ids := make([]string, 0, len(involved))
for d := range involved {
ids = append(ids, d)
}
+ sort.Strings(ids)
return &WikiAlteration{
Removed: 0,
NewlyUploaded: 0,
+ RemovedDocIDs: []string{},
+ NewlyUploadedDocIDs: []string{},
InvolvedDocIDs: ids,
EligibleDocIDs: ids,
}, nilDo you want me to open an issue to track the missing removed and newly-uploaded computation?
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/service/dataset_artifact_service.go` around lines 387 - 392, Update
the WikiAlteration construction in the affected service method: either compute
and populate Removed, NewlyUploaded, RemovedDocIDs, and NewlyUploadedDocIDs, or
explicitly represent the operation as unimplemented while preserving that
distinction. Always initialize all response slices to non-nil empty slices when
no values exist, and sort the map-derived ids before assigning InvolvedDocIDs
and EligibleDocIDs so output order is deterministic.
| filter := map[string]interface{}{ | ||
| "doc_id": documentID, | ||
| "kb_id": datasetID, | ||
| "compiled_graph_kwd": []string{"graph"}, | ||
| } | ||
| if graphType != "" { | ||
| filter[FieldGraphType] = []string{graphType} | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Use consistent filter value types and stop overriding kb_id.
Every other filter in this file passes term values as []string. Here doc_id and kb_id are plain strings. The kb_id entry also replaces the dataset scope that searchCompiled sets, because the merge loop runs after the default. Pass doc_id as a slice and drop kb_id, which searchCompiled already applies. DeleteDocumentGraph at Lines 536-540 needs the same change.
♻️ Proposed fix
filter := map[string]interface{}{
- "doc_id": documentID,
- "kb_id": datasetID,
+ "doc_id": []string{documentID},
"compiled_graph_kwd": []string{"graph"},
}📝 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.
| filter := map[string]interface{}{ | |
| "doc_id": documentID, | |
| "kb_id": datasetID, | |
| "compiled_graph_kwd": []string{"graph"}, | |
| } | |
| if graphType != "" { | |
| filter[FieldGraphType] = []string{graphType} | |
| } | |
| filter := map[string]interface{}{ | |
| "doc_id": []string{documentID}, | |
| "compiled_graph_kwd": []string{"graph"}, | |
| } | |
| if graphType != "" { | |
| filter[FieldGraphType] = []string{graphType} | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/service/dataset_artifact_service.go` around lines 506 - 513, Update
the filter construction in searchCompiled and DeleteDocumentGraph to use
[]string for doc_id, and remove the kb_id entry so the dataset scope established
by searchCompiled is preserved. Keep the existing compiled_graph_kwd and
optional FieldGraphType filters unchanged.
- FileCommitService.RecordPageEdit writes a git-style audit commit (FileCommit + FileCommitItem with unified diff and ES content_after reference) for each wiki/skill page edit, linking to the previous commit for the same page via slug_kwd/page_type_kwd. - DatasetArtifactHandler.UpdateArtifact records the audit commit on content change (best-effort, non-blocking). - FileCommitHandler.ListCommits supports ?slug=+?page_type= page-commit filtering, matching Python list_commits. - DAO adds GetLatestCommitIDBySlug/ListBySlug and ListByIDs; fix providers_test params to provider_id_or_name/instance_id_or_name after route rename. Co-authored-by: Zhichang Yu <[email protected]>
…age-commit tests Review fixes: - datasetOwner now writes a proper 4xx response (401/404/403) instead of silently returning, so artifact/nav/skill endpoints no longer hang with no response when the request is unauthenticated, the dataset is missing, or the user is not allowed to access it. - Add unit tests for RecordPageEdit (commit+item creation, git-style parent chain on second edit) and unifiedDiff (no-change, addition, removal, truncation). - Drop dead code: unused prev LCS table in unifiedDiff and unused TenantID field on PageEditCommitInput. Co-authored-by: Zhichang Yu <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 4
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
internal/handler/file_commit.go (1)
191-256: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winHandle
?slug=...withoutfolder_idand avoid querying by emptypage_type.The slug path is under
/:folder_id/commits;/datasets/:dataset_id/commitsresolvesdataset_idto a folder ID, so callers still need that route parameter even for folder-independent page commits. If this API supports?slug=...withoutpage_type, use a sentinel that makesListBySlugskippage_type_kwd = ?, because an omittedpage_typeis passed as""and currently filters out typed page-commits.🤖 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/handler/file_commit.go` around lines 191 - 256, Update the slug handling in the commit-list handler so requests with slug do not require a non-empty folder_id; perform folder validation only for the folder-based path. When page_type is omitted, pass the established sentinel to ListPageCommits/ListBySlug and ensure that sentinel skips the page_type_kwd filter, preserving typed page commits. Keep normal folder validation and pagination behavior unchanged.
🧹 Nitpick comments (2)
internal/handler/file_commit.go (1)
233-248: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate
entity.CommitResponseconversion loop.The slug branch (lines 233-248) and the folder-based branch (lines 264-279) build
entity.CommitResponsefrom[]*entity.FileCommitwith identical logic. Extract a small helper, e.g.toCommitResponses(commits []*entity.FileCommit) []entity.CommitResponse, and call it from both branches.♻️ Proposed helper extraction
+func toCommitResponses(commits []*entity.FileCommit) []entity.CommitResponse { + var commitList []entity.CommitResponse + for _, commit := range commits { + var ct int64 + if commit.CreateTime != nil { + ct = *commit.CreateTime + } + commitList = append(commitList, entity.CommitResponse{ + ID: commit.ID, + FolderID: commit.FolderID, + ParentID: commit.ParentID, + Message: commit.Message, + AuthorID: commit.AuthorID, + FileCount: commit.FileCount, + CreateTime: &ct, + }) + } + return commitList +}Then replace both inline loops with
commitList := toCommitResponses(commits).🤖 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/handler/file_commit.go` around lines 233 - 248, Extract the duplicated FileCommit-to-CommitResponse mapping into a shared helper such as toCommitResponses(commits []*entity.FileCommit) []entity.CommitResponse, preserving the existing CreateTime nil handling and field mapping. Replace the inline conversion loops in both the slug branch and folder-based branch with calls to this helper.internal/service/file/file_commit.go (1)
333-412: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the unused
prevmatrix and reconsider the 6-line truncation threshold.
previs allocated as a full(len(oldLines)+1) x (len(newLines)+1)matrix (lines 346-349) but is never read; it is only referenced via_ = prev(line 365). This doubles the memory used by the LCS computation for no benefit.Separately,
unifiedDifftruncates any diff with more thanmaxCtx*2(6) changed lines down to the first 3 and last 3, replacing everything else with an omission count. For an audit trail, most real page edits will exceed 6 changed lines, so the stored diff will rarely reflect the actual change. Confirm this truncation threshold is intentional; if so, consider basing it on diff size (bytes) rather than a fixed 6-line count, since 6 is very small for a feature whose stated purpose is recording useful edit history.Also consider whether a well-tested diff library (e.g., a Myers-diff implementation) would be preferable to the hand-rolled O(n·m) time/space LCS here, especially since wiki/skill pages can be large; the current algorithm can become slow and memory-heavy for large
oldContent/newContent.♻️ Proposed fix to drop the unused `prev` matrix
- // Longest common subsequence over lines, then render the diff. - prev := make([][]int, len(oldLines)+1) - for i := range prev { - prev[i] = make([]int, len(newLines)+1) - } - cur := make([][]int, len(oldLines)+1) + // Longest common subsequence over lines, then render the diff. + cur := make([][]int, len(oldLines)+1) for i := range cur { cur[i] = make([]int, len(newLines)+1) } @@ - _ = prev - i, j := 0, 0🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/file/file_commit.go` around lines 333 - 412, Remove the unused prev matrix allocation and the _ = prev statement from unifiedDiff, leaving the cur LCS matrix as the sole computation state. Reconsider the maxCtx*2 truncation policy in unifiedDiff and replace the fixed six-line cutoff with an intentional, size-based limit if truncation is required; preserve useful audit content and ensure the omission count remains accurate. Evaluate the hand-rolled LCS approach for large inputs and use an established efficient diff implementation if appropriate.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/dao/file_commit.go`:
- Around line 114-149: Replace the MySQL-specific, string-concatenated FIELD
ordering in FileCommitDAO.ListByIDs with a parameterized, cross-backend ordering
approach such as an ordered join or CASE expression. Preserve the incoming
commitIDs order, pagination behavior, and total count without interpolating IDs
into SQL.
In `@internal/handler/dataset_artifact.go`:
- Around line 126-130: The update flow around GetWikiPage and RecordPageEdit
must not record an audit diff unless the prior wiki page was read successfully.
Preserve the retrieved before.ContentMd value only on a successful, non-nil
read; when that read fails or returns no page, skip or defer RecordPageEdit
after UpdateWikiPage rather than treating oldContent as empty, including the
analogous logic at the later referenced flow.
In `@internal/service/file/file_commit.go`:
- Around line 237-310: Scope page commit records and lookups by dataset: add a
dataset-scoped identifier field to FileCommitItem, populate it from
PageEditCommitInput.DatasetID in RecordPageEdit, and update
GetLatestCommitIDBySlug and ListBySlug in internal/dao/file_commit.go to include
that identifier in their filters. Ensure parent resolution and listing cannot
cross dataset boundaries.
- Around line 237-310: Update RecordPageEdit and the related
GetLatestCommitIDBySlug/ListPageCommits flows to scope page commits by the
knowledgebase and derived _wiki_file_id(kb_id, slug), not slug and page type
alone. Store the knowledgebase scope via folder_id and use the derived page file
key instead of setting FileCommitItem.FileID to the ES storage marker. Ensure
parent lookup and history reads apply the same file_id/folder_id scope so
identical slugs in different knowledgebases remain isolated.
---
Outside diff comments:
In `@internal/handler/file_commit.go`:
- Around line 191-256: Update the slug handling in the commit-list handler so
requests with slug do not require a non-empty folder_id; perform folder
validation only for the folder-based path. When page_type is omitted, pass the
established sentinel to ListPageCommits/ListBySlug and ensure that sentinel
skips the page_type_kwd filter, preserving typed page commits. Keep normal
folder validation and pagination behavior unchanged.
---
Nitpick comments:
In `@internal/handler/file_commit.go`:
- Around line 233-248: Extract the duplicated FileCommit-to-CommitResponse
mapping into a shared helper such as toCommitResponses(commits
[]*entity.FileCommit) []entity.CommitResponse, preserving the existing
CreateTime nil handling and field mapping. Replace the inline conversion loops
in both the slug branch and folder-based branch with calls to this helper.
In `@internal/service/file/file_commit.go`:
- Around line 333-412: Remove the unused prev matrix allocation and the _ = prev
statement from unifiedDiff, leaving the cur LCS matrix as the sole computation
state. Reconsider the maxCtx*2 truncation policy in unifiedDiff and replace the
fixed six-line cutoff with an intentional, size-based limit if truncation is
required; preserve useful audit content and ensure the omission count remains
accurate. Evaluate the hand-rolled LCS approach for large inputs and use an
established efficient diff implementation if appropriate.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 26b82fb2-7573-46f0-85b8-25c82546500a
📒 Files selected for processing (7)
cmd/ragflow_server.gointernal/dao/file_commit.gointernal/handler/dataset_artifact.gointernal/handler/file_commit.gointernal/handler/file_commit_test.gointernal/handler/providers_test.gointernal/service/file/file_commit.go
🚧 Files skipped from review as they are similar to previous changes (1)
- cmd/ragflow_server.go
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
internal/service/file/file_commit_page_test.go (1)
89-123: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd coverage for
ListPageCommits.The new tests do not call
ListPageCommits. Add records for the target page and for a differentslugorpageType. Assert that the method returns only target-page commits, reports the correct total, and applies pagination.As per coding guidelines, “Preserve still-valid behavior with focused tests.”
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/file/file_commit_page_test.go` around lines 89 - 123, Add focused tests for ListPageCommits alongside TestRecordPageEdit_SecondEditLinksParent: create multiple commits for the target page and at least one with a different slug or pageType, then assert only target-page commits are returned, the total count is correct, and pagination limits and offsets results as expected.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/handler/dataset_artifact.go`:
- Around line 54-56: Update the GetKnowledgebaseByID error handling in the
dataset handler to distinguish missing records from lookup failures: use
dao.IsNotFoundErr(err) (and the nil knowledgebase case) for common.CodeNotFound,
while mapping other non-nil errors to common.CodeServerError. Preserve the
existing “dataset not found” response for genuinely missing datasets.
---
Nitpick comments:
In `@internal/service/file/file_commit_page_test.go`:
- Around line 89-123: Add focused tests for ListPageCommits alongside
TestRecordPageEdit_SecondEditLinksParent: create multiple commits for the target
page and at least one with a different slug or pageType, then assert only
target-page commits are returned, the total count is correct, and pagination
limits and offsets results as expected.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 862bc846-6989-4fdb-80c2-b37d630fc2c6
📒 Files selected for processing (3)
internal/handler/dataset_artifact.gointernal/service/file/file_commit.gointernal/service/file/file_commit_page_test.go
💤 Files with no reviewable changes (1)
- internal/service/file/file_commit.go
Security & correctness: - Guard the wiki page chunk id before UpdateChunks (dataset_artifact_service) - Apply the dataset kb_id scope after caller filters so it always wins - Scope page-edit commits by dataset via a derived page file key, fixing cross- knowledgebase history collisions; parent lookup and listing use the same key - Replace MySQL-only FIELD() ORDER BY interpolation with a parameterized CASE expression in FileCommitDAO.ListByIDs - Only record an audit diff when the prior page was read successfully - Accept <nil> missing field keys in template validation via yamlStr instead of fmt.Sprint producing "<nil>" (which passed required checks) - upsertBuiltin treats only gorm.ErrRecordNotFound as a missing row Data integrity & correctness: - Wrap CreateGroup/UpdateGroup (group row + child writes) in a single transaction - Skip already-retained rows in the positional reconcile fallback so a mixed ID/positional payload cannot bind two entries to one row - Scope HardDeleteOrphansByName to the group so same-named templates in other groups are untouched - Add an intValue helper for engine numeric fields (float64/int/int64/json.Number/ string/list) used by wiki graph, nav clusters/children, and skill tree - Return topic count and deterministic order from ListWikiTopics; make the alteration response emit non-nil slices and a sorted id order - Use []string for doc_id filters and drop redundant kb_id in document graph - Clamp page_size to 100 in the artifact list handler - Restore corrupted Apache license headers and drop Python-origin doc comments Tests: - Add dataset-isolation test for RecordPageEdit parent chains Co-authored-by: Zhichang Yu <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
internal/dao/compilation_template.go (2)
132-141: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winAdd a stable tie-breaker to child ordering.
ListByGrouporders only bycreate_time. Equal timestamps can produce different child orderings. Order byidaftercreate_timeto keep nested group responses deterministic.Proposed fix
- Order("create_time asc"). + Order("create_time asc, id asc").🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/dao/compilation_template.go` around lines 132 - 141, Update CompilationTemplateDAO.ListByGroup so its query orders results first by create_time ascending and then by id ascending, ensuring deterministic ordering when timestamps are equal.
156-171: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winUse atomic database uniqueness for duplicate-name checks.
Both DAOs use a count-before-insert check, so concurrent requests can pass the same validity/name check before either write commits. Add matching unique constraints/indexes and let insert/update failures enforce the duplicate-name policy:
- valid, non-built-in
CompilationTemplaterows in the same tenant/group should not sharename.- valid
CompilationTemplateGrouprows in the same tenant should not sharename.Handle unique-constraint failures as validation/validation errors at the service/DAO boundary.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/dao/compilation_template.go` around lines 156 - 171, Replace the count-before-insert duplicate checks in internal/dao/compilation_template.go:156-171 (NameExistsInGroup) and internal/dao/compilation_template_group.go:78-91 with matching atomic unique constraints/indexes: valid, non-built-in templates must be unique by tenant, group, and name, while valid groups must be unique by tenant and name. Enforce duplicates through insert/update constraint failures and translate those failures into validation errors at the service/DAO boundary; update both affected DAO paths accordingly.
🧹 Nitpick comments (1)
internal/dao/compilation_template.go (1)
194-215: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove migration-history references from Go documentation.
The comments should describe current Go behavior.
internal/dao/compilation_template.go#L194-L215: rewrite the Python cascade and purge references.internal/dao/compilation_template_group.go#L104-L105: rewrite thePython delete_group()reference.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/dao/compilation_template.go` around lines 194 - 215, Remove migration-history references to Python behavior from the documentation comments in two locations. In internal/dao/compilation_template.go at UpdateStatusByGroup and HardDeleteOrphansByName (lines 194-215), rewrite the comments that reference "mirroring Python group delete's child cascade" and "_purge_stale_invalid_children" to instead describe the current Go implementation behavior directly without Python context. Similarly, in internal/dao/compilation_template_group.go at lines 104-105, rewrite any comments referencing "Python delete_group()" to describe the current Go behavior. Keep the core functionality descriptions intact while removing historical migration context.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/dao/file_commit.go`:
- Around line 146-149: The query currently finds all matching commits before
applying pagination, which loads unused rows into memory. Add Offset and Limit
clauses to the query chain before calling Find, applying them conditionally when
page and pageSize are positive. Preserve the existing OrderBy clause and the
Find operation itself, just ensure pagination is part of the query rather than
done on the result set after loading all data.
- Around line 203-211: The GetLatestCommitIDByFileID call in RecordPageEdit
occurs outside the transaction that inserts the new commit, allowing concurrent
edits on the same file_id to select the same parent and create sibling commits.
Integrate the parent selection logic into the same serialized transaction that
performs the insertion, adding per-file locking to ensure atomicity of the
select-and-insert operation. Verify that the first edit case (when no prior
FileCommitItem exists for the file_id) also acquires serialization and executes
correctly. Add a concurrent regression test that verifies two simultaneous edits
on the same file_id create a proper linear commit chain rather than siblings
with identical parents.
---
Outside diff comments:
In `@internal/dao/compilation_template.go`:
- Around line 132-141: Update CompilationTemplateDAO.ListByGroup so its query
orders results first by create_time ascending and then by id ascending, ensuring
deterministic ordering when timestamps are equal.
- Around line 156-171: Replace the count-before-insert duplicate checks in
internal/dao/compilation_template.go:156-171 (NameExistsInGroup) and
internal/dao/compilation_template_group.go:78-91 with matching atomic unique
constraints/indexes: valid, non-built-in templates must be unique by tenant,
group, and name, while valid groups must be unique by tenant and name. Enforce
duplicates through insert/update constraint failures and translate those
failures into validation errors at the service/DAO boundary; update both
affected DAO paths accordingly.
---
Nitpick comments:
In `@internal/dao/compilation_template.go`:
- Around line 194-215: Remove migration-history references to Python behavior
from the documentation comments in two locations. In
internal/dao/compilation_template.go at UpdateStatusByGroup and
HardDeleteOrphansByName (lines 194-215), rewrite the comments that reference
"mirroring Python group delete's child cascade" and
"_purge_stale_invalid_children" to instead describe the current Go
implementation behavior directly without Python context. Similarly, in
internal/dao/compilation_template_group.go at lines 104-105, rewrite any
comments referencing "Python delete_group()" to describe the current Go
behavior. Keep the core functionality descriptions intact while removing
historical migration context.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: b7b32a54-5c26-47c8-8e67-b6d590209431
📒 Files selected for processing (11)
internal/dao/compilation_template.gointernal/dao/compilation_template_group.gointernal/dao/file_commit.gointernal/handler/dataset_artifact.gointernal/handler/file_commit.gointernal/handler/file_commit_test.gointernal/service/compilation_template_group_service.gointernal/service/compilation_template_service.gointernal/service/dataset_artifact_service.gointernal/service/file/file_commit.gointernal/service/file/file_commit_page_test.go
🚧 Files skipped from review as they are similar to previous changes (7)
- internal/handler/file_commit_test.go
- internal/service/file/file_commit.go
- internal/service/compilation_template_service.go
- internal/service/dataset_artifact_service.go
- internal/service/compilation_template_group_service.go
- internal/handler/dataset_artifact.go
- internal/handler/file_commit.go
| // GetLatestCommitIDByFileID returns the most recent commit_id that modified the | ||
| // given wiki page file key, or "" if none. Used to build the parent chain for | ||
| // page-edit commits. | ||
| func (dao *FileCommitItemDAO) GetLatestCommitIDByFileID(ctx context.Context, db *gorm.DB, fileID string) (string, error) { | ||
| var item entity.FileCommitItem | ||
| err := db.WithContext(ctx). | ||
| Where("file_id = ?", fileID). | ||
| Order("create_time DESC"). | ||
| First(&item).Error |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Serialize parent selection with page-commit creation.
RecordPageEdit calls GetLatestCommitIDByFileID before it starts the transaction that inserts the commit and item. Two concurrent edits for one file_id can select the same parent and create sibling commits. Perform parent selection and insertion in one per-file serialized operation. Ensure that the strategy also serializes the first edit when no item exists. Add a concurrent regression test.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/dao/file_commit.go` around lines 203 - 211, The
GetLatestCommitIDByFileID call in RecordPageEdit occurs outside the transaction
that inserts the new commit, allowing concurrent edits on the same file_id to
select the same parent and create sibling commits. Integrate the parent
selection logic into the same serialized transaction that performs the
insertion, adding per-file locking to ensure atomicity of the select-and-insert
operation. Verify that the first edit case (when no prior FileCommitItem exists
for the file_id) also acquires serialization and executes correctly. Add a
concurrent regression test that verifies two simultaneous edits on the same
file_id create a proper linear commit chain rather than siblings with identical
parents.
…n, concurrency) - datasetOwner: distinguish a missing dataset (404) from a lookup failure (CodeServerError) using dao.IsNotFoundErr, instead of mapping every GetKnowledgebaseByID error to 404. - FileCommitDAO.ListByIDs: apply Offset/Limit in the query itself so long commit histories never load the full set into memory before slicing. - FileCommitService.RecordPageEdit: serialize parent selection with insertion using a per-page-file-key in-process mutex, so concurrent edits on the same page cannot read the same parent and fork the commit chain. Add a monotonic seq column to FileCommitItem and order the latest-item lookup by seq DESC so the most recent edit is always selected even when multiple edits share the same create_time millisecond. - Add TestRecordPageEdit_ConcurrentEditsFormLinearChain verifying concurrent edits on one page produce a linear parent chain with no sibling commits. Co-authored-by: Zhichang Yu <[email protected]>
Summary
Port the knowledge compilation management REST APIs from the Python implementation to Go, completing the Go backend surface for knowledge compilation across the board. All endpoints mirror the Python route/response contracts; a few route names follow the actual Python definitions (e.g.
/navigationvs/nav,/artifacts/structurevs/artifacts_structure).Compilation templates & groups
reconcileChildrenchild reconciliation (match by ID, positional fallback for legacy clients with retained-row dedup), soft-delete +_purge_stale_invalid_childrenorphan cleanup scoped to the group.CreateGroup/UpdateGrouprun in a single transaction (group row + child writes are atomic).GET /v1/compilation-templates/builtinsandGET /v1/compilation-templates/wiki-presetswith YAML-backed wiki preset loading;upsertBuiltintreats onlygorm.ErrRecordNotFoundas a missing row; template validation usesyamlStrso missing keys no longer slip past required checks.internal/dao), services (internal/service), gin handlers (internal/handler), router wiring (internal/router/router.go+cmd/ragflow_server.go).Dataset artifacts (wiki / structure / graph / nav / skills)
UpdateWikiPageguards the chunk id and writes a git-style audit commit (unified diff, ES content_after reference, parent chain) when content actually changes.kb_id;intValuehelper tolerates engine numeric field types; deterministic topic ordering; non-nil alteration slices.Page-edit commit audit
FileCommitService.RecordPageEditrecords each wiki/skill page edit as aFileCommit+FileCommitItemwith a unified diff, scoped to the dataset via a derived page file key so page histories never cross knowledgebase boundaries.GET /datasets/{id}/commits?slug=&page_type=filters page-edit audit commits, matching Python'slist_commits.Providers route/param rename
:provider_name→:provider_id_or_name,:instance_name→:instance_id_or_name(JSON body field names unchanged).Files touched
internal/service/compilation_template_service.go,internal/service/compilation_template_group_service.gointernal/service/dataset_artifact_service.go,internal/service/file/file_commit.gointernal/dao/compilation_template.go,internal/dao/compilation_template_group.go,internal/dao/file_commit.gointernal/handler/compilation_template.go,internal/handler/compilation_template_group.go,internal/handler/dataset_artifact.go,internal/handler/file_commit.go,internal/handler/providers.gointernal/router/router.go,cmd/ragflow_server.gointernal/entity/file_commit.go(schema for page-edit commits)Test plan
bash build.sh --gobuilds cleanlybash build.sh --test ./internal/service/... ./internal/dao/... ./internal/handler/... ./internal/router/...passes (incl. new page-commit & dataset-isolation unit tests)Co-authored-by: Zhichang Yu [email protected]