Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(name): unify case-insensitive entity name dedup and rename handling (#20594)

ciel30eedef05311
diff --git a/docs/references/http_api_reference.md b/docs/references/http_api_reference.md
index f0ffd22fe1..d66923bc42 100644
--- a/docs/references/http_api_reference.md
+++ b/docs/references/http_api_reference.md
@@ -583,6 +583,7 @@ curl --request POST \
- Basic Multilingual Plane (BMP) only
- Maximum 128 characters
- Case-insensitive
+ If the name is already taken, the dataset is created with a numbered suffix such as `test_1(1)`, `test_1(2)`, and so on.
- `"avatar"`: (*Body parameter*), `string`
Base64 encoding of the avatar.
@@ -2679,6 +2680,7 @@ curl --request POST \
- `"name"`: (*Body parameter*), `string`, *Required*
The name of the chat assistant.
+ If a chat assistant with the same name already exists, the new one gets a numbered suffix such as `new_chat_1(1)`.
- `"icon"`: (*Body parameter*), `string`
Base64 encoding of the avatar.
- `"dataset_ids"`: (*Body parameter*), `list[string]`
@@ -2787,7 +2789,7 @@ Failure:
```json
{
"code": 102,
- "message": "duplicated chat name"
+ "message": "`name` is required"
}
```
@@ -5332,6 +5334,7 @@ curl --request POST \
- `title`: (*Body parameter*), `string`, *Required*
The title of the agent.
+ If an agent with the same title already exists, the new one gets a numbered suffix such as `Test Agent(1)`.
- `description`: (*Body parameter*), `string`
The description of the agent. Defaults to `None`.
- `dsl`: (*Body parameter*), `object`, *Required*
@@ -5353,8 +5356,8 @@ Failure:
```json
{
- "code": 102,
- "message": "Agent with title test already exists."
+ "code": 101,
+ "message": "no DSL data in request"
}
```
@@ -5419,7 +5422,16 @@ Success:
}
```
-Failure:
+Failure (duplicate title):
+
+```json
+{
+ "code": 102,
+ "message": "Test Agent already exists."
+}
+```
+
+Failure (permission denied):
```json
{
@@ -6856,7 +6868,7 @@ curl --request POST \
##### Request parameters
- `"name"`: (*Body parameter*), `string`, *Required*
- The name of the file or folder to create.
+ The name of the file or folder to create. If the name is already taken in the parent folder, the new entry gets a numbered suffix such as `New Folder(1)`.
- `"parent_id"`: (*Body parameter*), `string`
The parent folder ID. If not specified, the file/folder will be created in the root folder.
- `"type"`: (*Body parameter*), `string`
@@ -6886,8 +6898,8 @@ Failure:
```json
{
- "code": 409,
- "message": "Duplicated folder name in the same folder."
+ "code": 400,
+ "message": "Folder name cannot contain \"/\""
}
```
@@ -7310,6 +7322,15 @@ or
}
```
+or
+
+```json
+{
+ "code": 400,
+ "message": "duplicated file name in the same folder"
+}
+```
+
---
### Links files to datasets and convert to documents
diff --git a/internal/common/app_name.go b/internal/common/app_name.go
index c0eef5d9d3..7d7a70f18c 100644
--- a/internal/common/app_name.go
+++ b/internal/common/app_name.go
@@ -20,85 +20,130 @@ import (
"fmt"
"path"
"regexp"
+ "strconv"
"strings"
)
-// splitNameCounter splits a filename into base name and counter
-// Handles names in format "filename(123)" pattern
-//
-// Parameters:
-// - filename: The filename to split
-//
-// Returns:
-// - string: The base name without counter
-// - *int: The counter value, or nil if no counter exists
+// maxNameRetries bounds how many numbered suffixes UniqueName may try before
+// giving up on a free name.
+const maxNameRetries = 1000
+
+// splitNameCounter splits a name stem (already stripped of its file extension)
+// into its base and a trailing "(N)" counter. The boolean reports whether a
+// trailing counter was present.
//
// Example:
//
-// splitNameCounter("test(5)") returns ("test", 5)
-// splitNameCounter("test") returns ("test", nil)
-func splitNameCounter(filename string) (string, *int) {
- re := regexp.MustCompile(`^(.+)\((\d+)\)$`)
- matches := re.FindStringSubmatch(filename)
- if len(matches) >= 3 {
- counter := -1
- fmt.Sscanf(matches[2], "%d", &counter)
- stem := strings.TrimRight(matches[1], " ")
- return stem, &counter
+// splitNameCounter("test(5)") returns ("test", 5, true)
+// splitNameCounter("test") returns ("test", 0, false)
+func splitNameCounter(stem string) (string, int, bool) {
+ re := regexp.MustCompile(`^(.*)\((\d+)\)$`)
+ matches := re.FindStringSubmatch(stem)
+ if matches == nil {
+ return stem, 0, false
+ }
+ counter, err := strconv.Atoi(matches[2])
+ if err != nil {
+ return stem, 0, false
}
- return filename, nil
+ return strings.TrimRight(matches[1], " "), counter, true
}
-// DuplicateName generates a unique name by appending a counter if the name already exists
-// It tries up to 1000 times to generate a unique name
+// UniqueName returns a non-colliding variant of name by appending "(1)",
+// "(2)", ... to the end of the name. It continues from an existing trailing
+// counter. Use UniqueFileName for file or document names that must keep their
+// extension at the end.
//
-// Parameters:
-// - queryFunc: Function to check if a name already exists (returns true if exists)
-// - name: The original name
-// - tenantID: The tenant ID for name uniqueness check
+// maxLen is the maximum allowed length in bytes for the generated name;
+// maxLen <= 0 falls back to AppNameLimit.
//
-// Returns:
-// - string: A unique name (either original or with counter appended)
+// UniqueName("topic", 0, ...) -> "topic(1)"
+// UniqueName("topic(1)", 0, ...) -> "topic(2)"
+// UniqueName("release v1.2", 0, ...) -> "release v1.2(1)"
//
-// Example:
-//
-// DuplicateName(func(name string, tid string) bool { return false }, "test", "tenant1") returns "test"
-// DuplicateName(func(name string, tid string) bool { return true }, "test", "tenant1") returns "test(1)"
-func DuplicateName(queryFunc func(name string, tenantID string) bool, name string, tenantID string) (string, error) {
- const maxRetries = 1000
+// exists reports whether a candidate already collides. A lookup error is
+// returned to the caller instead of being treated as "free".
+func UniqueName(name string, maxLen int, exists func(candidate string) (bool, error)) (string, error) {
+ return uniqueName(name, maxLen, false, exists)
+}
- originalName := name
- currentName := name
- retries := 0
+// UniqueFileName is UniqueName for file and document names: the suffix is
+// inserted before the file extension instead of at the end of the name.
+//
+// UniqueFileName("report.pdf", 0, ...) -> "report(1).pdf"
+// UniqueFileName("report(1).pdf", 0, ...) -> "report(2).pdf"
+func UniqueFileName(name string, maxLen int, exists func(candidate string) (bool, error)) (string, error) {
+ return uniqueName(name, maxLen, true, exists)
+}
- for retries < maxRetries {
- if !queryFunc(currentName, tenantID) {
- return currentName, nil
+// uniqueName appends an incrementing "(N)" suffix until exists reports the
+// candidate as free. keepExtension inserts the suffix before the file
+// extension instead of at the end of the name.
+func uniqueName(name string, maxLen int, keepExtension bool, exists func(candidate string) (bool, error)) (string, error) {
+ if maxLen <= 0 {
+ maxLen = AppNameLimit
+ }
+ current := name
+ if err := validateNameLimit(current, maxLen); err != nil {
+ return "", err
+ }
+ for i := 0; i < maxNameRetries; i++ {
+ taken, err := exists(current)
+ if err != nil {
+ return "", err
}
-
- stem, counter := splitNameCounter(currentName)
- ext := path.Ext(stem)
- stemBase := strings.TrimSuffix(stem, ext)
-
- newCounter := 1
- if counter != nil {
- newCounter = *counter + 1
+ if !taken {
+ return current, nil
}
- currentName = fmt.Sprintf("%s(%d)%s", stemBase, newCounter, ext)
- retries++
-
- if err := ValidateName(currentName); err != nil {
+ stem := current
+ ext := ""
+ if keepExtension {
+ ext = path.Ext(current)
+ stem = strings.TrimSuffix(current, ext)
+ }
+ base, counter, ok := splitNameCounter(stem)
+ if !ok {
+ base = stem
+ }
+ current = fmt.Sprintf("%s(%d)%s", base, counter+1, ext)
+ if err := validateNameLimit(current, maxLen); err != nil {
return "", err
}
}
- return "", fmt.Errorf("failed to generate unique name after %d attempts, conflict name: %s", maxRetries, originalName)
+ return "", fmt.Errorf("failed to generate a unique name after %d attempts, conflict name: %s", maxNameRetries, name)
+}
+
+// NameAvailable reports whether newName is free to use for a rename.
+//
+// A case-only change (strings.EqualFold) is always allowed and skips the
+// existence check, matching the dataset rename rule. Otherwise the caller's
+// case-insensitive existence check decides.
+//
+// It returns (true, nil) when the name can be used, (false, nil) when it is
+// already taken, and (false, err) when the existence lookup fails.
+func NameAvailable(currentName, newName string, exists func(candidate string) (bool, error)) (bool, error) {
+ if strings.EqualFold(currentName, newName) {
+ return true, nil
+ }
+ taken, err := exists(newName)
+ if err != nil {
+ return false, err
+ }
+ return !taken, nil
}
+// AppNameLimit is the maximum allowed length of a name, in bytes.
const AppNameLimit = 256
+// ValidateName rejects empty names and names longer than AppNameLimit bytes.
func ValidateName(name string) error {
+ return validateNameLimit(name, AppNameLimit)
+}
+
+// validateNameLimit rejects empty names and names longer than maxLen bytes.
+func validateNameLimit(name string, maxLen int) error {
// Validate name is not empty after trimming
trimmedName := strings.TrimSpace(name)
if trimmedName == "" {
@@ -106,8 +151,8 @@ func ValidateName(name string) error {
}
// Validate name length in bytes (not characters) - same as Python len(search_name.encode("utf-8"))
- if len([]byte(name)) > AppNameLimit {
- return fmt.Errorf("name length is %d which is large than %d", len([]byte(name)), AppNameLimit)
+ if len([]byte(name)) > maxLen {
+ return fmt.Errorf("name length is %d which is large than %d", len([]byte(name)), maxLen)
}
return nil
diff --git a/internal/common/app_name_test.go b/internal/common/app_name_test.go
new file mode 100644
index 0000000000..a8bfc7413c
--- /dev/null
+++ b/internal/common/app_name_test.go
@@ -0,0 +1,205 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package common
+
+import (
+ "errors"
+ "strings"
+ "testing"
+)
+
+func TestSplitNameCounter(t *testing.T) {
+ cases := []struct {
+ stem string
+ wantBase string
+ wantCount int
+ wantOK bool
+ }{
+ {"test(5)", "test", 5, true},
+ {"test", "test", 0, false},
+ {"test (5)", "test", 5, true},
+ {"a(1)(2)", "a(1)", 2, true},
+ {"报告(12)", "报告", 12, true},
+ {"(3)", "", 3, true},
+ {"test()", "test()", 0, false},
+ }
+ for _, tc := range cases {
+ base, count, ok := splitNameCounter(tc.stem)
+ if base != tc.wantBase || count != tc.wantCount || ok != tc.wantOK {
+ t.Errorf("splitNameCounter(%q) = (%q, %d, %v), want (%q, %d, %v)",
+ tc.stem, base, count, ok, tc.wantBase, tc.wantCount, tc.wantOK)
+ }
+ }
+}
+
+func TestUniqueName_NoCollision(t *testing.T) {
+ got, err := UniqueName("topic", 0, func(string) (bool, error) { return false, nil })
+ if err != nil {
+ t.Fatalf("UniqueName returned error: %v", err)
+ }
+ if got != "topic" {
+ t.Fatalf("UniqueName = %q, want %q", got, "topic")
+ }
+}
+
+func TestUniqueName_CounterContinuation(t *testing.T) {
+ cases := []struct {
+ name string
+ taken map[string]bool
+ want string
+ }{
+ {"topic", map[string]bool{"topic": true}, "topic(1)"},
+ {"topic", map[string]bool{"topic": true, "topic(1)": true}, "topic(2)"},
+ {"topic(1)", map[string]bool{"topic(1)": true}, "topic(2)"},
+ {"topic(2)", map[string]bool{"topic(2)": true, "topic(3)": true}, "topic(4)"},
+ }
+ for _, tc := range cases {
+ taken := tc.taken
+ got, err := UniqueName(tc.name, 0, func(c string) (bool, error) { return taken[c], nil })
+ if err != nil {
+ t.Fatalf("UniqueName(%q) error: %v", tc.name, err)
+ }
+ if got != tc.want {
+ t.Errorf("UniqueName(%q) = %q, want %q", tc.name, got, tc.want)
+ }
+ }
+}
+
+// Non-file resource names keep their dots: the counter is appended to the end
+// of the whole name instead of being inserted before the last dot.
+func TestUniqueName_AppendsSuffixToDottedResourceName(t *testing.T) {
+ taken := map[string]bool{"release v1.2": true}
+ got, err := UniqueName("release v1.2", 0, func(c string) (bool, error) { return taken[c], nil })
+ if err != nil {
+ t.Fatalf("UniqueName error: %v", err)
+ }
+ if got != "release v1.2(1)" {
+ t.Fatalf("UniqueName = %q, want %q", got, "release v1.2(1)")
+ }
+}
+
+func TestUniqueFileName_PreservesExtension(t *testing.T) {
+ cases := []struct {
+ name string
+ taken map[string]bool
+ want string
+ }{
+ {"report.pdf", map[string]bool{"report.pdf": true}, "report(1).pdf"},
+ {"report.pdf", map[string]bool{"report.pdf": true, "report(1).pdf": true}, "report(2).pdf"},
+ {"report(1).pdf", map[string]bool{"report(1).pdf": true}, "report(2).pdf"},
+ {"archive.tar.gz", map[string]bool{"archive.tar.gz": true}, "archive.tar(1).gz"},
+ }
+ for _, tc := range cases {
+ taken := tc.taken
+ got, err := UniqueFileName(tc.name, 0, func(c string) (bool, error) { return taken[c], nil })
+ if err != nil {
+ t.Fatalf("UniqueFileName(%q) error: %v", tc.name, err)
+ }
+ if got != tc.want {
+ t.Errorf("UniqueFileName(%q) = %q, want %q", tc.name, got, tc.want)
+ }
+ }
+}
+
+func TestUniqueName_PropagatesLookupError(t *testing.T) {
+ wantErr := errors.New("lookup failed")
+ _, err := UniqueName("topic", 0, func(string) (bool, error) { return false, wantErr })
+ if !errors.Is(err, wantErr) {
+ t.Fatalf("UniqueName error = %v, want %v", err, wantErr)
+ }
+}
+
+// The generated candidate must respect the caller's resource-specific limit,
+// even when it is below the generic AppNameLimit.
+func TestUniqueName_EnforcesCallerLimit(t *testing.T) {
+ base := strings.Repeat("a", 128)
+ onlyBaseTaken := func(c string) (bool, error) { return c == base, nil }
+
+ if _, err := UniqueName(base, 128, onlyBaseTaken); err == nil {
+ t.Fatal("expected length validation error for generated name at caller limit")
+ } else if !strings.Contains(err.Error(), "large than") {
+ t.Fatalf("unexpected error: %v", err)
+ }
+
+ got, err := UniqueName(base, 0, onlyBaseTaken)
+ if err != nil {
+ t.Fatalf("UniqueName with default limit error: %v", err)
+ }
+ if want := base + "(1)"; got != want {
+ t.Fatalf("UniqueName = %q, want %q", got, want)
+ }
+}
+
+func TestNameAvailable_CaseOnlyChangeSkipsLookup(t *testing.T) {
+ called := false
+ ok, err := NameAvailable("Foo", "foo", func(string) (bool, error) {
+ called = true
+ return true, nil
+ })
+ if err != nil {
+ t.Fatalf("NameAvailable error: %v", err)
+ }
+ if !ok {
+ t.Fatal("expected case-only change to be available")
+ }
+ if called {
+ t.Fatal("expected case-only change to skip the existence lookup")
+ }
+}
+
+func TestNameAvailable_Taken(t *testing.T) {
+ ok, err := NameAvailable("Original", "Taken", func(string) (bool, error) { return true, nil })
+ if err != nil {
+ t.Fatalf("NameAvailable error: %v", err)
+ }
+ if ok {
+ t.Fatal("expected taken name to be unavailable")
+ }
+}
+
+func TestNameAvailable_Free(t *testing.T) {
+ ok, err := NameAvailable("Original", "Free", func(string) (bool, error) { return false, nil })
+ if err != nil {
+ t.Fatalf("NameAvailable error: %v", err)
+ }
+ if !ok {
+ t.Fatal("expected free name to be available")
+ }
+}
+
+func TestNameAvailable_PropagatesLookupError(t *testing.T) {
+ wantErr := errors.New("lookup failed")
+ ok, err := NameAvailable("Original", "New", func(string) (bool, error) { return false, wantErr })
+ if !errors.Is(err, wantErr) {
+ t.Fatalf("NameAvailable error = %v, want %v", err, wantErr)
+ }
+ if ok {
+ t.Fatal("expected availability to be false on lookup error")
+ }
+}
+
+func TestValidateName(t *testing.T) {
+ if err := ValidateName(" "); err == nil {
+ t.Fatal("expected empty name error")
+ }
+ if err := ValidateName(strings.Repeat("a", AppNameLimit+1)); err == nil {
+ t.Fatal("expected length error")
+ }
+ if err := ValidateName("ok"); err != nil {
+ t.Fatalf("unexpected error for valid name: %v", err)
+ }
+}
diff --git a/internal/dao/chat.go b/internal/dao/chat.go
index 095e2e54a5..56d055b0e4 100644
--- a/internal/dao/chat.go
+++ b/internal/dao/chat.go
@@ -192,20 +192,11 @@ func (dao *ChatDAO) GetByIDAndStatus(ctx context.Context, db *gorm.DB, id string
return &chat, nil
}
-// GetExistingNames gets existing dialog names for a tenant
-func (dao *ChatDAO) GetExistingNames(ctx context.Context, db *gorm.DB, tenantID string, status string) ([]string, error) {
- var names []string
- err := db.WithContext(ctx).Model(&entity.Chat{}).
- Where("tenant_id = ? AND status = ?", tenantID, status).
- Pluck("name", &names).Error
- return names, err
-}
-
// ExistsByNameTenantStatus checks whether a chat with the given name exists.
func (dao *ChatDAO) ExistsByNameTenantStatus(ctx context.Context, db *gorm.DB, name, tenantID, status string) (bool, error) {
var count int64
err := db.WithContext(ctx).Model(&entity.Chat{}).
- Where("name = ? AND tenant_id = ? AND status = ?", name, tenantID, status).
+ Where("LOWER(name) = LOWER(?) AND tenant_id = ? AND status = ?", name, tenantID, status).
Count(&count).Error
return count > 0, err
}
diff --git a/internal/dao/compilation_template.go b/internal/dao/compilation_template.go
index 45fe9385db..748691f77d 100644
--- a/internal/dao/compilation_template.go
+++ b/internal/dao/compilation_template.go
@@ -134,7 +134,7 @@ func (dao *CompilationTemplateDAO) ListByGroup(ctx context.Context, db *gorm.DB,
// Python duplicate-child guard.
func (dao *CompilationTemplateDAO) NameExistsInGroup(ctx context.Context, db *gorm.DB, tenantID, groupID, name, excludeID string) (bool, error) {
q := db.WithContext(ctx).Model(&entity.CompilationTemplate{}).
- Where("tenant_id = ? AND group_id = ? AND name = ? AND is_builtin = ? AND status = ?",
+ Where("tenant_id = ? AND group_id = ? AND LOWER(name) = LOWER(?) AND is_builtin = ? AND status = ?",
tenantID, groupID, name, false, string(entity.StatusValid))
if excludeID != "" {
q = q.Where("id <> ?", excludeID)
diff --git a/internal/dao/compilation_template_group.go b/internal/dao/compilation_template_group.go
index b3890337af..615a35b7df 100644
--- a/internal/dao/compilation_template_group.go
+++ b/internal/dao/compilation_template_group.go
@@ -82,7 +82,7 @@ func (dao *CompilationTemplateGroupDAO) GetSaved(ctx context.Context, db *gorm.D
// tenant, excluding excludeID. Mirrors Python name_exists().
func (dao *CompilationTemplateGroupDAO) NameExists(ctx context.Context, db *gorm.DB, tenantID, name, excludeID string) (bool, error) {
q := db.WithContext(ctx).Model(&entity.CompilationTemplateGroup{}).
- Where("tenant_id = ? AND name = ? AND status = ?", tenantID, name, string(entity.StatusValid))
+ Where("tenant_id = ? AND LOWER(name) = LOWER(?) AND status = ?", tenantID, name, string(entity.StatusValid))
if excludeID != "" {
q = q.Where("id <> ?", excludeID)
}
diff --git a/internal/dao/document.go b/internal/dao/document.go
index 6c86ca9285..430977c68d 100644
--- a/internal/dao/document.go
+++ b/internal/dao/document.go
@@ -577,19 +577,12 @@ func (dao *DocumentDAO) GetParsingStatusByKBID(ctx context.Context, db *gorm.DB,
return result, nil
}
-func (dao *DocumentDAO) GetByNameAndKBID(ctx context.Context, db *gorm.DB, name, kbID string) ([]*entity.Document, error) {
- var docs []*entity.Document
- err := db.WithContext(ctx).Where("name = ? AND kb_id = ?", name, kbID).Find(&docs).Error
- return docs, err
-}
-
-// ListNamesByKbID returns every document name in a dataset, used to compute a
-// non-colliding upload filename (mirrors Python duplicate_name).
-func (dao *DocumentDAO) ListNamesByKbID(ctx context.Context, db *gorm.DB, kbID string) ([]string, error) {
- var names []string
- err := db.WithContext(ctx).Model(&entity.Document{}).Where("kb_id = ?", kbID).Pluck("name", &names).Error
- if err != nil {
- return nil, err
- }
- return names, nil
+// NameExistsInKB reports whether a document with the given name already
+// exists in the dataset, comparing names case-insensitively.
+func (dao *DocumentDAO) NameExistsInKB(ctx context.Context, db *gorm.DB, kbID, name string) (bool, error) {
+ var count int64
+ err := db.WithContext(ctx).Model(&entity.Document{}).
+ Where("LOWER(name) = LOWER(?) AND kb_id = ?", name, kbID).
+ Count(&count).Error
+ return count > 0, err
}
diff --git a/internal/dao/file.go b/internal/dao/file.go
index 0c5113eb84..ca27e1f057 100644
--- a/internal/dao/file.go
+++ b/internal/dao/file.go
@@ -404,6 +404,21 @@ func (dao *FileDAO) Query(ctx context.Context, db *gorm.DB, name string, parentI
return files, nil
}
+// NameExists reports whether a file or folder with the given name already
+// exists under parentID for the tenant, comparing names case-insensitively.
+// excludeID, when non-empty, omits that entry from the check so moving or
+// renaming an entry does not collide with itself.
+func (dao *FileDAO) NameExists(ctx context.Context, db *gorm.DB, name, parentID, tenantID, excludeID string) (bool, error) {
+ q := db.WithContext(ctx).Model(&entity.File{}).
+ Where("LOWER(name) = LOWER(?) AND parent_id = ? AND tenant_id = ?", name, parentID, tenantID)
+ if excludeID != "" {
+ q = q.Where("id <> ?", excludeID)
+ }
+ var count int64
+ err := q.Count(&count).Error
+ return count > 0, err
+}
+
// Delete deletes a file by ID (hard delete)
func (dao *FileDAO) Delete(ctx context.Context, db *gorm.DB, id string) error {
return db.WithContext(ctx).Unscoped().Where("id = ?", id).Delete(&entity.File{}).Error
diff --git a/internal/dao/kb.go b/internal/dao/kb.go
index 5d70fda66d..86d5895291 100644
--- a/internal/dao/kb.go
+++ b/internal/dao/kb.go
@@ -161,6 +161,16 @@ func (dao *KnowledgebaseDAO) GetByName(ctx context.Context, db *gorm.DB, name, t
return &kb, nil
}
+// NameExists reports whether a valid knowledge base with the given name
+// already exists for the tenant, comparing names case-insensitively.
+func (dao *KnowledgebaseDAO) NameExists(ctx context.Context, db *gorm.DB, tenantID, name string) (bool, error) {
+ var count int64
+ err := db.WithContext(ctx).Model(&entity.Knowledgebase{}).
+ Where("LOWER(name) = LOWER(?) AND tenant_id = ? AND status = ?", name, tenantID, string(entity.StatusValid)).
+ Count(&count).Error
+ return count > 0, err
+}
+
// GetByCreatedBy retrieves knowledge bases created by a specific user
func (dao *KnowledgebaseDAO) GetByCreatedBy(ctx context.Context, db *gorm.DB, createdBy string) ([]*entity.Knowledgebase, error) {
var kbs []*entity.Knowledgebase
diff --git a/internal/dao/mcp.go b/internal/dao/mcp.go
index 4651e701dc..15511c3cf7 100644
--- a/internal/dao/mcp.go
+++ b/internal/dao/mcp.go
@@ -61,7 +61,7 @@ func (dao *MCPServerDAO) GetByID(ctx context.Context, db *gorm.DB, id string) (*
func (dao *MCPServerDAO) ExistsByNameAndTenant(ctx context.Context, db *gorm.DB, name, tenantID string) (bool, error) {
var count int64
if err := db.WithContext(ctx).Model(&entity.MCPServer{}).
- Where("name = ? AND tenant_id = ?", name, tenantID).
+ Where("LOWER(name) = LOWER(?) AND tenant_id = ?", name, tenantID).
Count(&count).Error; err != nil {
return false, err
}
diff --git a/internal/dao/memory.go b/internal/dao/memory.go
index 4e35b7f2bc..fd8034a45e 100644
--- a/internal/dao/memory.go
+++ b/internal/dao/memory.go
@@ -170,7 +170,7 @@ func (dao *MemoryDAO) GetByTenantID(ctx context.Context, db *gorm.DB, tenantID s
// - error: Database operation error
func (dao *MemoryDAO) GetByNameAndTenant(ctx context.Context, db *gorm.DB, name string, tenantID string) ([]*entity.Memory, error) {
var memories []*entity.Memory
- err := db.WithContext(ctx).Where("name = ? AND tenant_id = ?", name, tenantID).Find(&memories).Error
+ err := db.WithContext(ctx).Where("LOWER(name) = LOWER(?) AND tenant_id = ?", name, tenantID).Find(&memories).Error
return memories, err
}
diff --git a/internal/dao/search.go b/internal/dao/search.go
index 4bd7033ab7..c2cb97cfd0 100644
--- a/internal/dao/search.go
+++ b/internal/dao/search.go
@@ -192,7 +192,7 @@ func (dao *SearchDAO) GetDetailByID(ctx context.Context, db *gorm.DB, searchID s
// GetByNameAndTenant gets search by name and tenant ID
func (dao *SearchDAO) GetByNameAndTenant(ctx context.Context, db *gorm.DB, name string, tenantID string) ([]*entity.Search, error) {
var searches []*entity.Search
- err := db.WithContext(ctx).Where("name = ? AND tenant_id = ? AND status = ?", name, tenantID, "1").Find(&searches).Error
+ err := db.WithContext(ctx).Where("LOWER(name) = LOWER(?) AND tenant_id = ? AND status = ?", name, tenantID, "1").Find(&searches).Error
return searches, err
}
diff --git a/internal/dao/skill_space.go b/internal/dao/skill_space.go
index c3637c073e..66c4c8ab9a 100644
--- a/internal/dao/skill_space.go
+++ b/internal/dao/skill_space.go
@@ -56,7 +56,7 @@ func (dao *SkillSpaceDAO) GetByTenantID(ctx context.Context, db *gorm.DB, tenant
// GetByTenantAndName retrieves a skills space by tenant ID and name (active only)
func (dao *SkillSpaceDAO) GetByTenantAndName(ctx context.Context, db *gorm.DB, tenantID, name string) (*entity.SkillSpace, error) {
var space entity.SkillSpace
- err := db.WithContext(ctx).Where("tenant_id = ? AND name = ? AND status = ?", tenantID, name, entity.SpaceStatusActive).First(&space).Error
+ err := db.WithContext(ctx).Where("tenant_id = ? AND LOWER(name) = LOWER(?) AND status = ?", tenantID, name, entity.SpaceStatusActive).First(&space).Error
if err != nil {
return nil, err
}
@@ -66,7 +66,7 @@ func (dao *SkillSpaceDAO) GetByTenantAndName(ctx context.Context, db *gorm.DB, t
// GetByTenantAndNameAnyStatus retrieves a skills space by tenant ID and name regardless of status
func (dao *SkillSpaceDAO) GetByTenantAndNameAnyStatus(ctx context.Context, db *gorm.DB, tenantID, name string) (*entity.SkillSpace, error) {
var space entity.SkillSpace
- err := db.WithContext(ctx).Where("tenant_id = ? AND name = ?", tenantID, name).First(&space).Error
+ err := db.WithContext(ctx).Where("tenant_id = ? AND LOWER(name) = LOWER(?)", tenantID, name).First(&space).Error
if err != nil {
return nil, err
}
diff --git a/internal/dao/user_canvas.go b/internal/dao/user_canvas.go
index 2bf3f22b55..209b56b38d 100644
--- a/internal/dao/user_canvas.go
+++ b/internal/dao/user_canvas.go
@@ -212,24 +212,22 @@ func (dao *UserCanvasDAO) DeleteTx(ctx context.Context, tx *gorm.DB, id string)
return tx.WithContext(ctx).Where("id = ?", id).Delete(&entity.UserCanvas{}).Error
}
-// GetByUserAndTitle returns the canvas matching user_id + title (and
-// optional canvas_category), or (nil, nil) when no such canvas exists.
-// Used by service.AgentService.CreateAgent to enforce the "title
-// already exists" rule that the Python agent API mirrors with
-// UserCanvasService.query(user_id=..., title=...).
-func (dao *UserCanvasDAO) GetByUserAndTitle(ctx context.Context, db *gorm.DB, userID, title, canvasCategory string) (*entity.UserCanvas, error) {
- q := db.WithContext(ctx).Where("user_id = ? AND title = ?", userID, title)
+// TitleExists reports whether the user already has a canvas with the given
+// title in the category, comparing titles case-insensitively. excludeID, when
+// non-empty, omits that canvas from the check so a rename can keep its own
+// title while a move into another category is still validated.
+func (dao *UserCanvasDAO) TitleExists(ctx context.Context, db *gorm.DB, userID, canvasCategory, title, excludeID string) (bool, error) {
+ q := db.WithContext(ctx).Model(&entity.UserCanvas{}).
+ Where("user_id = ? AND LOWER(title) = LOWER(?)", userID, title)
if canvasCategory != "" {
q = q.Where("canvas_category = ?", canvasCategory)
}
- var row entity.UserCanvas
- if err := q.First(&row).Error; err != nil {
- if errors.Is(err, gorm.ErrRecordNotFound) {
- return nil, nil
- }
- return nil, err
+ if excludeID != "" {
+ q = q.Where("id <> ?", excludeID)
}
- return &row, nil
+ var count int64
+ err := q.Count(&count).Error
+ return count > 0, err
}
// GetList get canvases list with pagination and filtering
diff --git a/internal/handler/compilation_template_group.go b/internal/handler/compilation_template_group.go
index 629bfef4c7..b9d688741e 100644
--- a/internal/handler/compilation_template_group.go
+++ b/internal/handler/compilation_template_group.go
@@ -142,15 +142,6 @@ func (h *CompilationTemplateGroupHandler) Save(c *gin.Context) {
common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())
return
}
- nameExists, err := h.compilationTemplateGroupService.NameExists(c.Request.Context(), user.ID, req.Name)
- if err != nil {
- common.ResponseWithCodeData(c, common.CodeExceptionError, nil, err.Error())
- return
- }
- if nameExists {
- common.ResponseWithCodeData(c, common.CodeDataError, nil, "Duplicated compilation template group name.")
- return
- }
group, err := h.compilationTemplateGroupService.CreateGroup(c.Request.Context(), user.ID, &req)
if err != nil {
common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())
diff --git a/internal/handler/compilation_template_group_test.go b/internal/handler/compilation_template_group_test.go
new file mode 100644
index 0000000000..b817b9d196
--- /dev/null
+++ b/internal/handler/compilation_template_group_test.go
@@ -0,0 +1,167 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package handler
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/glebarez/sqlite"
+ "gorm.io/gorm"
+
+ "ragflow/internal/common"
+ "ragflow/internal/dao"
+ "ragflow/internal/entity"
+ "ragflow/internal/service"
+)
+
+// setupGroupHandlerDB migrates the minimal schema for the compilation template
+// group handler and pushes it onto dao.DB.
+func setupGroupHandlerDB(t *testing.T) *gorm.DB {
+ t.Helper()
+
+ // A shared-cache memory database keeps the transaction's connection and the
+ // pool's other connections on the same schema.
+ dsn := "file:" + url.QueryEscape(t.Name()) + "?mode=memory&cache=shared"
+ db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{TranslateError: true})
+ if err != nil {
+ t.Fatalf("failed to open sqlite: %v", err)
+ }
+ if err = db.AutoMigrate(
+ &entity.CompilationTemplateGroup{},
+ &entity.CompilationTemplate{},
+ &entity.Tenant{},
+ ); err != nil {
+ t.Fatalf("failed to migrate: %v", err)
+ }
+ origDB := dao.DB
+ dao.DB = db
+ t.Cleanup(func() { dao.DB = origDB })
+ return db
+}
+
+func newCompilationTemplateGroupHandlerRouter() *gin.Engine {
+ gin.SetMode(gin.TestMode)
+ h := NewCompilationTemplateGroupHandler(service.NewCompilationTemplateGroupService())
+ r := gin.New()
+ r.POST("/api/v1/compilation-template-groups", func(c *gin.Context) {
+ c.Set("user", &entity.User{ID: "user-1"})
+ h.Save(c)
+ })
+ r.PUT("/api/v1/compilation-template-groups/:group_id", func(c *gin.Context) {
+ c.Set("user", &entity.User{ID: "user-1"})
+ h.Update(c)
+ })
+ return r
+}
+
+type groupSaveResponse struct {
+ Code int `json:"code"`
+ Message string `json:"message"`
+ Data map[string]interface{} `json:"data"`
+}
+
+func postCompilationTemplateGroup(t *testing.T, r *gin.Engine, body string) groupSaveResponse {
+ t.Helper()
+ resp := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPost, "/api/v1/compilation-template-groups", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ r.ServeHTTP(resp, req)
+
+ var parsed groupSaveResponse
+ if err := json.Unmarshal(resp.Body.Bytes(), &parsed); err != nil {
+ t.Fatalf("unmarshal response: %v body=%s", err, resp.Body.String())
+ }
+ return parsed
+}
+
+// Saving a group whose name is already used by another group of the tenant
+// appends a counter instead of returning "Duplicated compilation template
+// group name.".
+func TestCompilationTemplateGroupHandlerSaveDedupesDuplicateName(t *testing.T) {
+ setupGroupHandlerDB(t)
+ r := newCompilationTemplateGroupHandlerRouter()
+ body := `{"name":"Group A","templates":[{"name":"tpl","kind":"text","config":{}}]}`
+
+ first := postCompilationTemplateGroup(t, r, body)
+ if first.Code != int(common.CodeSuccess) {
+ t.Fatalf("first save code = %d, message = %q", first.Code, first.Message)
+ }
+ if got := first.Data["name"]; got != "Group A" {
+ t.Fatalf("first group name = %v, want %q", got, "Group A")
+ }
+
+ second := postCompilationTemplateGroup(t, r, body)
+ if second.Code != int(common.CodeSuccess) {
+ t.Fatalf("second save code = %d, message = %q", second.Code, second.Message)
+ }
+ if got := second.Data["name"]; got != "Group A(1)" {
+ t.Fatalf("second group name = %v, want %q", got, "Group A(1)")
+ }
+}
+
+func putCompilationTemplateGroup(t *testing.T, r *gin.Engine, id, body string) groupSaveResponse {
+ t.Helper()
+ resp := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodPut, "/api/v1/compilation-template-groups/"+id, strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ r.ServeHTTP(resp, req)
+
+ var parsed groupSaveResponse
+ if err := json.Unmarshal(resp.Body.Bytes(), &parsed); err != nil {
+ t.Fatalf("unmarshal response: %v body=%s", err, resp.Body.String())
+ }
+ return parsed
+}
+
+// After a name fallback the group and its single template share the group name,
+// so an update carrying the template name (what the client submits) is accepted;
+// reusing another group's name is still rejected.
+func TestCompilationTemplateGroupHandlerUpdateAllowsTemplateName(t *testing.T) {
+ setupGroupHandlerDB(t)
+ r := newCompilationTemplateGroupHandlerRouter()
+ body := `{"name":"Group A","templates":[{"name":"tpl","kind":"text","config":{}}]}`
+
+ if first := postCompilationTemplateGroup(t, r, body); first.Code != int(common.CodeSuccess) {
+ t.Fatalf("first save code = %d, message = %q", first.Code, first.Message)
+ }
+ second := postCompilationTemplateGroup(t, r, body)
+ if second.Code != int(common.CodeSuccess) {
+ t.Fatalf("second save code = %d, message = %q", second.Code, second.Message)
+ }
+ id, _ := second.Data["id"].(string)
+ if id == "" {
+ t.Fatalf("second save returned no id: %#v", second.Data)
+ }
+
+ updated := putCompilationTemplateGroup(t, r, id, `{"name":"Group A(1)","templates":[{"name":"Group A(1)","kind":"text","config":{}}]}`)
+ if updated.Code != int(common.CodeSuccess) {
+ t.Fatalf("update code = %d, message = %q", updated.Code, updated.Message)
+ }
+ if got := updated.Data["name"]; got != "Group A(1)" {
+ t.Fatalf("updated group name = %v, want %q", got, "Group A(1)")
+ }
+
+ conflict := putCompilationTemplateGroup(t, r, id, `{"name":"Group A","templates":[{"name":"Group A","kind":"text","config":{}}]}`)
+ if conflict.Code != int(common.CodeDataError) {
+ t.Fatalf("conflicting update code = %d, want %d", conflict.Code, int(common.CodeDataError))
+ }
+}
diff --git a/internal/service/agent.go b/internal/service/agent.go
index 14f647594c..0ef19bed7e 100644
--- a/internal/service/agent.go
+++ b/internal/service/agent.go
@@ -963,11 +963,15 @@ func (s *AgentService) CreateAgent(ctx context.Context, req *CreateAgentRequest)
req.CanvasCategory = "agent_canvas"
}
- if existing, err := s.canvasDAO.GetByUserAndTitle(ctx, dao.DB, req.UserID, title, req.CanvasCategory); err != nil {
+ uniqueTitle, err := common.UniqueName(title, 255, func(candidate string) (bool, error) {
+ return s.canvasDAO.TitleExists(ctx, dao.DB, req.UserID, req.CanvasCategory, candidate, "")
+ })
+ if err != nil {
return nil, common.CodeServerError, fmt.Errorf("check duplicate title: %w", err)
- } else if existing != nil {
- return nil, common.CodeDataError, agentTitleAlreadyExistsError(title)
}
+ title = uniqueTitle
+ req.Title = &title
+
if err := component.ValidateIntegerParameters(req.DSL); err != nil {
return nil, common.CodeArgumentError, fmt.Errorf("create agent: %w", err)
}
@@ -1144,9 +1148,14 @@ func (s *AgentService) UpdateAgent(ctx context.Context, userID, canvasID string,
updates["release"] = release
if title, ok := updatedAgentTitle(canvasInstance, updates); ok {
canvasCategory := updatedAgentCanvasCategory(canvasInstance, updates)
- if existing, err := s.canvasDAO.GetByUserAndTitle(ctx, dao.DB, ownerUserID, title, canvasCategory); err != nil {
+ // Exclude the canvas being updated so keeping or only re-casing its
+ // title does not collide with itself, while a move to a category that
+ // already holds the title is still rejected.
+ exists, err := s.canvasDAO.TitleExists(ctx, dao.DB, ownerUserID, canvasCategory, title, canvasID)
+ if err != nil {
return fmt.Errorf("check duplicate title: %w", err)
- } else if existing != nil && existing.ID != canvasID {
+ }
+ if exists {
return agentTitleAlreadyExistsError(title)
}
}
diff --git a/internal/service/agent_test.go b/internal/service/agent_test.go
index e368e3a4a1..d6d7e3817d 100644
--- a/internal/service/agent_test.go
+++ b/internal/service/agent_test.go
@@ -1730,6 +1730,70 @@ func TestUpdateAgentRejectsCategoryOnlyDuplicateTitleInDestinationCategory(t *te
}
}
+func TestUpdateAgentAllowsCaseOnlyTitleChange(t *testing.T) {
+ setupAgentSessionServiceTest(t)
+ ctx := t.Context()
+
+ if err := dao.DB.WithContext(ctx).Create(&entity.UserCanvas{
+ ID: "canvas-case-only-title",
+ UserID: "user-1",
+ Title: sptr("Case Title"),
+ CanvasCategory: "agent_canvas",
+ DSL: entity.JSONMap{},
+ }).Error; err != nil {
+ t.Fatalf("failed to seed agent: %v", err)
+ }
+
+ if err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-case-only-title", map[string]interface{}{
+ "title": "case title",
+ }); err != nil {
+ t.Fatalf("UpdateAgent failed for case-only title change: %v", err)
+ }
+
+ persisted, err := dao.NewUserCanvasDAO().GetByID(ctx, dao.DB, "canvas-case-only-title")
+ if err != nil {
+ t.Fatalf("failed to reload agent: %v", err)
+ }
+ if persisted.Title == nil || *persisted.Title != "case title" {
+ t.Fatalf("persisted title = %v, want %q", persisted.Title, "case title")
+ }
+}
+
+func TestCreateAgentDedupesDuplicateTitle(t *testing.T) {
+ setupAgentSessionServiceTest(t)
+ ctx := t.Context()
+
+ if err := dao.DB.WithContext(ctx).Create(&entity.UserCanvas{
+ ID: "canvas-dup-title",
+ UserID: "user-1",
+ Title: sptr("Dup Title"),
+ CanvasCategory: "agent_canvas",
+ DSL: entity.JSONMap{},
+ }).Error; err != nil {
+ t.Fatalf("failed to seed agent: %v", err)
+ }
+
+ row, code, err := NewAgentService().CreateAgent(ctx, &CreateAgentRequest{
+ UserID: "user-1",
+ Title: sptr("Dup Title"),
+ DSL: entity.JSONMap{},
+ })
+ if err != nil {
+ t.Fatalf("expected deduped create to succeed, got %v", err)
+ }
+ if code != common.CodeSuccess {
+ t.Fatalf("expected success code, got %d", code)
+ }
+ if row.Title == nil || *row.Title != "Dup Title(1)" {
+ t.Fatalf("created title = %v, want %q", row.Title, "Dup Title(1)")
+ }
+
+ var created entity.UserCanvas
+ if err := dao.DB.WithContext(ctx).Where("user_id = ? AND title = ?", "user-1", "Dup Title(1)").First(&created).Error; err != nil {
+ t.Fatalf("expected a persisted agent named %q: %v", "Dup Title(1)", err)
+ }
+}
+
func TestUpdateAgentPersistsDSLAsJSONMap(t *testing.T) {
setupAgentSessionServiceTest(t)
diff --git a/internal/service/chat.go b/internal/service/chat.go
index 13096a44ac..37f4e86861 100644
--- a/internal/service/chat.go
+++ b/internal/service/chat.go
@@ -338,13 +338,13 @@ func (s *ChatService) Create(ctx context.Context, userID string, req map[string]
applyCreatePromptDefaults(req)
filterCreateChatPersistedFields(req)
- exists, err := s.chatDAO.ExistsByNameTenantStatus(ctx, dao.DB, name, userID, string(entity.StatusValid))
+ name, err = common.UniqueName(name, 255, func(candidate string) (bool, error) {
+ return s.chatDAO.ExistsByNameTenantStatus(ctx, dao.DB, candidate, userID, string(entity.StatusValid))
+ })
if err != nil {
return nil, common.CodeServerError, err
}
- if exists {
- return nil, common.CodeDataError, errors.New("duplicated chat name in creating chat")
- }
+ req["name"] = name
chat := buildCreateChatEntity(req, userID)
if err = s.chatDAO.Create(ctx, dao.DB, chat); err != nil {
@@ -964,16 +964,14 @@ func (s *ChatService) updateChatREST(ctx context.Context, userID, chatID string,
if currentChat.Name != nil {
currentName = *currentChat.Name
}
- if strings.ToLower(name) != strings.ToLower(currentName) {
- existingNames, err := s.chatDAO.GetExistingNames(ctx, dao.DB, userID, string(entity.StatusValid))
- if err != nil {
- return nil, err
- }
- for _, existingName := range existingNames {
- if strings.EqualFold(existingName, name) {
- return nil, errors.New("duplicated chat name")
- }
- }
+ available, err := common.NameAvailable(currentName, name, func(candidate string) (bool, error) {
+ return s.chatDAO.ExistsByNameTenantStatus(ctx, dao.DB, candidate, userID, string(entity.StatusValid))
+ })
+ if err != nil {
+ return nil, err
+ }
+ if !available {
+ return nil, errors.New("duplicated chat name")
}
}
diff --git a/internal/service/chat_rest_update_test.go b/internal/service/chat_rest_update_test.go
index 1af96885a1..2e66c8390b 100644
--- a/internal/service/chat_rest_update_test.go
+++ b/internal/service/chat_rest_update_test.go
@@ -420,21 +420,22 @@ func TestChatServiceCreateValidatesName(t *testing.T) {
}
}
-func TestChatServiceCreateRejectsDuplicateName(t *testing.T) {
+func TestChatServiceCreateDedupesDuplicateName(t *testing.T) {
db := setupChatRESTUpdateServiceTestDB(t)
createChatRESTUpdateServiceTestChat(t, db, "chat-1", "user-1")
svc := NewChatService()
ctx := t.Context()
_, code, err := svc.Create(ctx, "user-1", map[string]interface{}{"name": "chat-chat-1"})
- if err == nil {
- t.Fatal("expected duplicate name error")
+ if err != nil {
+ t.Fatalf("expected deduped create to succeed, got %v", err)
}
- if code != common.CodeDataError {
- t.Fatalf("expected data error code, got %d", code)
+ if code != common.CodeSuccess {
+ t.Fatalf("expected success code, got %d", code)
}
- if !strings.Contains(err.Error(), "duplicated chat name") {
- t.Fatalf("unexpected error: %v", err)
+ var created entity.Chat
+ if err := db.Where("tenant_id = ? AND name = ?", "user-1", "chat-chat-1(1)").First(&created).Error; err != nil {
+ t.Fatalf("expected a chat named %q: %v", "chat-chat-1(1)", err)
}
}
diff --git a/internal/service/compilation_template_group_service.go b/internal/service/compilation_template_group_service.go
index 50714c5a4e..d6d814c097 100644
--- a/internal/service/compilation_template_group_service.go
+++ b/internal/service/compilation_template_group_service.go
@@ -22,6 +22,7 @@ import (
"strings"
"time"
+ "ragflow/internal/common"
"ragflow/internal/dao"
"ragflow/internal/entity"
"ragflow/internal/utility"
@@ -42,6 +43,8 @@ const (
groupScopeDataset = "dataset"
// maxGroupNameLen is the DB column size for compilation_template_group.name.
maxGroupNameLen = 128
+ // maxTemplateNameLen is the DB column size for compilation_template.name.
+ maxTemplateNameLen = 128
)
// GroupTemplate is a child-template entry in a group create/update payload.
@@ -117,6 +120,13 @@ func (s *CompilationTemplateGroupService) CreateGroup(ctx context.Context, tenan
if err := validateGroupPayload(req, true); err != nil {
return nil, err
}
+ // Fall back to a numbered name when the requested one is already taken.
+ groupName, err := common.UniqueName(strings.TrimSpace(req.Name), maxGroupNameLen, func(candidate string) (bool, error) {
+ return s.groupDAO.NameExists(ctx, dao.DB, tenantID, candidate, "")
+ })
+ if err != nil {
+ return nil, err
+ }
scope, err := s.deriveScope(req.Templates)
if err != nil {
return nil, err
@@ -127,7 +137,7 @@ func (s *CompilationTemplateGroupService) CreateGroup(ctx context.Context, tenan
group := &entity.CompilationTemplateGroup{
ID: groupID,
TenantID: tenantID,
- Name: strings.TrimSpace(req.Name),
+ Name: groupName,
Description: strptr(req.Description),
Scope: scope,
Status: strptr(string(entity.StatusValid)),
@@ -135,7 +145,7 @@ func (s *CompilationTemplateGroupService) CreateGroup(ctx context.Context, tenan
if cerr := s.groupDAO.Create(ctx, tx, group); cerr != nil {
return cerr
}
- return s.insertChildren(ctx, tx, tenantID, groupID, req.Templates, nil)
+ return s.insertChildren(ctx, tx, tenantID, groupID, groupName, req.Templates)
}); err != nil {
return nil, err
}
@@ -363,15 +373,24 @@ func validateGroupPayload(req *GroupRequest, requireAll bool) error {
return nil
}
-// 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, db *gorm.DB, tenantID, groupID string, templates []*GroupTemplate, seen map[string]struct{}) error {
+// insertChildren inserts new child templates. A group that holds a single
+// template mirrors the resolved group name onto that template so the two never
+// diverge after the group name falls back to "name(N)"; otherwise a requested
+// name already used in the group falls back to a numbered suffix.
+func (s *CompilationTemplateGroupService) insertChildren(ctx context.Context, db *gorm.DB, tenantID, groupID, groupName string, templates []*GroupTemplate) error {
for _, child := range templates {
- name := strings.TrimSpace(child.Name)
- if exists, err := s.templateDAO.NameExistsInGroup(ctx, dao.DB, tenantID, groupID, name, ""); err != nil {
- return err
- } else if exists {
- return groupValidationErrorf("template name '%s' already exists in this group.", name)
+ // The client submits the template name as the group name, so a single
+ // child must share the (possibly deduped) group name or the update
+ // endpoint would reject it as a duplicate group name.
+ name := groupName
+ if len(templates) != 1 {
+ var err error
+ name, err = common.UniqueName(strings.TrimSpace(child.Name), maxTemplateNameLen, func(candidate string) (bool, error) {
+ return s.templateDAO.NameExistsInGroup(ctx, db, tenantID, groupID, candidate, "")
+ })
+ if err != nil {
+ return err
+ }
}
desc := child.Description
config := fillConfigDefaultLLM(ctx, s.tenantDAO, child.Config, &tenantID)
@@ -401,6 +420,14 @@ func (s *CompilationTemplateGroupService) insertChildren(ctx context.Context, db
// reconcileChildren mirrors the Python update_group child reconciliation:
// existing children (matched by id, or by submitted order for legacy clients)
// are updated in place, new ones inserted, and removed ones soft-deleted.
+//
+// The reconciliation runs in four passes so a rename onto a name that this same
+// update frees (a dropped child, swapped names) is not rejected as a conflict,
+// while a rename onto a name held by a surviving child still fails:
+// 1. resolve each submitted entry to its existing target,
+// 2. soft-delete the children that leave the group,
+// 3. apply the renames and inserts,
+// 4. reject duplicated (case-insensitive) names among the surviving children.
func (s *CompilationTemplateGroupService) reconcileChildren(ctx context.Context, db *gorm.DB, tenantID, groupID string, templates []*GroupTemplate) error {
current, err := s.templateDAO.ListByGroup(ctx, db, groupID)
if err != nil {
@@ -410,9 +437,18 @@ func (s *CompilationTemplateGroupService) reconcileChildren(ctx context.Context,
for _, c := range current {
currentByID[c.ID] = c
}
+
+ type resolvedChild struct {
+ child *GroupTemplate
+ target *entity.CompilationTemplate
+ name string
+ }
seenNames := map[string]struct{}{}
retained := map[string]struct{}{}
+ resolved := make([]resolvedChild, 0, len(templates))
+ // Pass 1: resolve targets before any write so the soft-deletes in pass 2 can
+ // run first.
for index, child := range templates {
name := strings.TrimSpace(child.Name)
if _, dup := seenNames[name]; dup {
@@ -434,33 +470,64 @@ func (s *CompilationTemplateGroupService) reconcileChildren(ctx context.Context,
target = current[index]
}
}
+ if target != nil {
+ retained[target.ID] = struct{}{}
+ }
+ resolved = append(resolved, resolvedChild{child: child, target: target, name: name})
+ }
- config := fillConfigDefaultLLM(ctx, s.tenantDAO, child.Config, &tenantID)
+ // Pass 2: drop the children that leave the group before applying renames, so
+ // a rename onto one of their names is not reported as a conflict.
+ for _, c := range current {
+ if _, keep := retained[c.ID]; keep {
+ continue
+ }
+ if err := s.templateDAO.UpdateStatusByID(ctx, db, c.ID, string(entity.StatusInvalid)); err != nil {
+ return err
+ }
+ // Mirror Python _purge_stale_invalid_children: permanently drop
+ // any stale invalid non-builtin template of the same name, scoped to
+ // this group so a same-named template in another group is untouched.
+ if c.Name != "" && !c.IsBuiltin {
+ if err := s.templateDAO.HardDeleteOrphansByName(ctx, db, tenantID, groupID, c.Name); err != nil {
+ return err
+ }
+ }
+ }
+
+ // Pass 3: apply updates and inserts.
+ for _, item := range resolved {
+ config := fillConfigDefaultLLM(ctx, s.tenantDAO, item.child.Config, &tenantID)
if config == nil {
config = entity.JSONMap{}
}
- desc := child.Description
- if target != nil {
+ desc := item.child.Description
+ if item.target != nil {
updates := map[string]interface{}{
- "name": name, "kind": strings.TrimSpace(child.Kind), "config": config,
+ "name": item.name, "kind": strings.TrimSpace(item.child.Kind), "config": config,
}
if desc != "" {
updates["description"] = desc
}
- if err := s.templateDAO.UpdateFields(ctx, db, target.ID, updates); err != nil {
+ if err := s.templateDAO.UpdateFields(ctx, db, item.target.ID, updates); err != nil {
return err
}
- retained[target.ID] = struct{}{}
continue
}
+ newName, err := common.UniqueName(item.name, maxTemplateNameLen, func(candidate string) (bool, error) {
+ return s.templateDAO.NameExistsInGroup(ctx, db, tenantID, groupID, candidate, "")
+ })
+ if err != nil {
+ return err
+ }
newID := utility.GenerateUUID()
valid := string(entity.StatusValid)
tmpl := &entity.CompilationTemplate{
ID: newID,
TenantID: &tenantID,
GroupID: &groupID,
- Name: name,
- Kind: strings.TrimSpace(child.Kind),
+ Name: newName,
+ Kind: strings.TrimSpace(item.child.Kind),
Config: config,
Status: &valid,
}
@@ -470,22 +537,56 @@ func (s *CompilationTemplateGroupService) reconcileChildren(ctx context.Context,
if err := s.templateDAO.Save(ctx, db, tmpl); err != nil {
return err
}
- retained[newID] = struct{}{}
}
+ // Pass 4: reject the case-insensitive duplicates this update introduces.
+ // Names that this update renames or creates are checked against the final
+ // group, while pre-existing duplicates between untouched names are left alone
+ // so a legacy group stays editable.
+ oldNames := make(map[string]string, len(current))
for _, c := range current {
- if _, keep := retained[c.ID]; !keep {
- if err := s.templateDAO.UpdateStatusByID(ctx, db, c.ID, string(entity.StatusInvalid)); err != nil {
- return err
- }
- // Mirror Python _purge_stale_invalid_children: permanently drop
- // any stale invalid non-builtin template of the same name, scoped to
- // this group so a same-named template in another group is untouched.
- if c.Name != "" && !c.IsBuiltin {
- if err := s.templateDAO.HardDeleteOrphansByName(ctx, db, tenantID, groupID, c.Name); err != nil {
- return err
- }
- }
+ oldNames[c.ID] = c.Name
+ }
+ return s.assertUniqueChildNames(ctx, db, groupID, oldNames)
+}
+
+// assertUniqueChildNames rejects a group whose valid children collide on a
+// case-insensitive name, matching the DAO's duplicate guard which ignores
+// built-in templates. oldNames maps each child id to its name before the
+// update; a collision is only an error when at least one of the colliding rows
+// was renamed or newly created, so pre-existing duplicates between untouched
+// names are tolerated.
+func (s *CompilationTemplateGroupService) assertUniqueChildNames(ctx context.Context, db *gorm.DB, groupID string, oldNames map[string]string) error {
+ children, err := s.templateDAO.ListByGroup(ctx, db, groupID)
+ if err != nil {
+ return err
+ }
+ type bucket struct {
+ count int
+ anyChanged bool
+ name string
+ }
+ buckets := make(map[string]*bucket, len(children))
+ for _, c := range children {
+ if c.IsBuiltin {
+ continue
+ }
+ key := strings.ToLower(strings.TrimSpace(c.Name))
+ b := buckets[key]
+ if b == nil {
+ b = &bucket{}
+ buckets[key] = b
+ }
+ b.count++
+ old, existed := oldNames[c.ID]
+ if !existed || !strings.EqualFold(strings.TrimSpace(old), strings.TrimSpace(c.Name)) {
+ b.anyChanged = true
+ b.name = c.Name
+ }
+ }
+ for _, b := range buckets {
+ if b.count >= 2 && b.anyChanged {
+ return groupValidationErrorf("template name '%s' already exists in this group.", b.name)
}
}
return nil
diff --git a/internal/service/compilation_template_group_service_test.go b/internal/service/compilation_template_group_service_test.go
new file mode 100644
index 0000000000..0d5b56996c
--- /dev/null
+++ b/internal/service/compilation_template_group_service_test.go
@@ -0,0 +1,332 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package service
+
+import (
+ "fmt"
+ "net/url"
+ "strings"
+ "testing"
+
+ "github.com/glebarez/sqlite"
+ "gorm.io/gorm"
+
+ "ragflow/internal/dao"
+ "ragflow/internal/entity"
+)
+
+// setupCompilationGroupTestDB migrates the minimal schema for the group
+// service and pushes it onto dao.DB.
+func setupCompilationGroupTestDB(t *testing.T) *gorm.DB {
+ t.Helper()
+
+ // A shared-cache memory database keeps the transaction's connection and the
+ // pool's other connections on the same schema.
+ dsn := "file:" + url.QueryEscape(t.Name()) + "?mode=memory&cache=shared"
+ db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{TranslateError: true})
+ if err != nil {
+ t.Fatalf("failed to open sqlite: %v", err)
+ }
+ if err = db.AutoMigrate(
+ &entity.CompilationTemplateGroup{},
+ &entity.CompilationTemplate{},
+ &entity.Tenant{},
+ ); err != nil {
+ t.Fatalf("failed to migrate: %v", err)
+ }
+ pushServiceDB(t, db)
+ return db
+}
+
+func seedCompilationGroup(t *testing.T, svc *CompilationTemplateGroupService, tenantID, groupName string, templateNames ...string) *GroupListItem {
+ t.Helper()
+
+ templates := make([]*GroupTemplate, 0, len(templateNames))
+ for _, name := range templateNames {
+ templates = append(templates, &GroupTemplate{Name: name, Kind: "text", Config: entity.JSONMap{}})
+ }
+ group, err := svc.CreateGroup(t.Context(), tenantID, &GroupRequest{Name: groupName, Templates: templates})
+ if err != nil {
+ t.Fatalf("seed group %q: %v", groupName, err)
+ }
+ return group
+}
+
+func templateByName(t *testing.T, group *GroupListItem, name string) *TemplateListItem {
+ t.Helper()
+
+ for _, item := range group.Templates {
+ if item.Name == name {
+ return item
+ }
+ }
+ t.Fatalf("template %q not found in group %#v", name, group.Templates)
+ return nil
+}
+
+// seedLegacyCompilationGroup writes a group and its children straight to the
+// database, bypassing the service's case-insensitive dedupe so tests can model
+// rows created before that guard existed.
+func seedLegacyCompilationGroup(t *testing.T, tenantID, groupID string, names ...string) map[string]string {
+ t.Helper()
+
+ valid := string(entity.StatusValid)
+ if err := dao.DB.Create(&entity.CompilationTemplateGroup{
+ ID: groupID,
+ TenantID: tenantID,
+ Name: "Legacy " + groupID,
+ Status: &valid,
+ }).Error; err != nil {
+ t.Fatalf("seed legacy group: %v", err)
+ }
+
+ ids := make(map[string]string, len(names))
+ for i, name := range names {
+ id := fmt.Sprintf("%s-c%d", groupID, i)
+ ids[name] = id
+ if err := dao.DB.Create(&entity.CompilationTemplate{
+ ID: id,
+ TenantID: &tenantID,
+ GroupID: &groupID,
+ Name: name,
+ Kind: "text",
+ Config: entity.JSONMap{},
+ Status: &valid,
+ }).Error; err != nil {
+ t.Fatalf("seed legacy template %q: %v", name, err)
+ }
+ }
+ return ids
+}
+
+func templateByID(t *testing.T, group *GroupListItem, id string) *TemplateListItem {
+ t.Helper()
+
+ for _, item := range group.Templates {
+ if item.ID == id {
+ return item
+ }
+ }
+ t.Fatalf("template %s not found in group %#v", id, group.Templates)
+ return nil
+}
+
+// CreateGroup must not write the deduped name back into the caller's request,
+// otherwise a reused request would create "Group A(1)(1)" style names.
+func TestCreateGroupDoesNotMutateRequestName(t *testing.T) {
+ setupCompilationGroupTestDB(t)
+ svc := NewCompilationTemplateGroupService()
+ ctx := t.Context()
+
+ req := &GroupRequest{
+ Name: "Group A",
+ Templates: []*GroupTemplate{{Name: "tpl", Kind: "text", Config: entity.JSONMap{}}},
+ }
+
+ first, err := svc.CreateGroup(ctx, "tenant-1", req)
+ if err != nil {
+ t.Fatalf("first CreateGroup: %v", err)
+ }
+ if first.Name != "Group A" {
+ t.Fatalf("first group name = %q, want %q", first.Name, "Group A")
+ }
+ if req.Name != "Group A" {
+ t.Fatalf("CreateGroup mutated req.Name to %q", req.Name)
+ }
+
+ second, err := svc.CreateGroup(ctx, "tenant-1", req)
+ if err != nil {
+ t.Fatalf("second CreateGroup: %v", err)
+ }
+ if second.Name != "Group A(1)" {
+ t.Fatalf("second group name = %q, want %q", second.Name, "Group A(1)")
+ }
+ if req.Name != "Group A" {
+ t.Fatalf("CreateGroup mutated req.Name to %q", req.Name)
+ }
+}
+
+// A child may take the name of a child that leaves the group in the same
+// update; the removed row must not be treated as a surviving conflict.
+func TestReconcileChildrenAllowsRenameOntoRemovedName(t *testing.T) {
+ setupCompilationGroupTestDB(t)
+ svc := NewCompilationTemplateGroupService()
+ ctx := t.Context()
+
+ group := seedCompilationGroup(t, svc, "tenant-1", "Group A", "A", "B")
+ b := templateByName(t, group, "B")
+
+ updated, err := svc.UpdateGroup(ctx, "tenant-1", group.ID, &GroupRequest{
+ Templates: []*GroupTemplate{{ID: b.ID, Name: "A", Kind: "text", Config: entity.JSONMap{}}},
+ })
+ if err != nil {
+ t.Fatalf("UpdateGroup: %v", err)
+ }
+ if len(updated.Templates) != 1 {
+ t.Fatalf("templates = %#v, want exactly one", updated.Templates)
+ }
+ if updated.Templates[0].Name != "A" {
+ t.Fatalf("template name = %q, want %q", updated.Templates[0].Name, "A")
+ }
+}
+
+// Swapping two child names in one update settles on unique names, so it must
+// not be rejected by the duplicate-name guard.
+func TestReconcileChildrenAllowsNameSwap(t *testing.T) {
+ setupCompilationGroupTestDB(t)
+ svc := NewCompilationTemplateGroupService()
+ ctx := t.Context()
+
+ group := seedCompilationGroup(t, svc, "tenant-1", "Group A", "A", "B")
+ a := templateByName(t, group, "A")
+ b := templateByName(t, group, "B")
+
+ updated, err := svc.UpdateGroup(ctx, "tenant-1", group.ID, &GroupRequest{
+ Templates: []*GroupTemplate{
+ {ID: a.ID, Name: "B", Kind: "text", Config: entity.JSONMap{}},
+ {ID: b.ID, Name: "A", Kind: "text", Config: entity.JSONMap{}},
+ },
+ })
+ if err != nil {
+ t.Fatalf("UpdateGroup: %v", err)
+ }
+ if got := templateByID(t, updated, a.ID).Name; got != "B" {
+ t.Fatalf("template %s name = %q, want %q", a.ID, got, "B")
+ }
+ if got := templateByID(t, updated, b.ID).Name; got != "A" {
+ t.Fatalf("template %s name = %q, want %q", b.ID, got, "A")
+ }
+}
+
+// Two surviving children must not end up with names that differ only by case.
+func TestReconcileChildrenRejectsDuplicateSurvivingName(t *testing.T) {
+ setupCompilationGroupTestDB(t)
+ svc := NewCompilationTemplateGroupService()
+ ctx := t.Context()
+
+ group := seedCompilationGroup(t, svc, "tenant-1", "Group A", "A", "B")
+ a := templateByName(t, group, "A")
+ b := templateByName(t, group, "B")
+
+ _, err := svc.UpdateGroup(ctx, "tenant-1", group.ID, &GroupRequest{
+ Templates: []*GroupTemplate{
+ {ID: a.ID, Name: "b", Kind: "text", Config: entity.JSONMap{}},
+ {ID: b.ID, Name: "B", Kind: "text", Config: entity.JSONMap{}},
+ },
+ })
+ if err == nil || !strings.Contains(err.Error(), "already exists in this group") {
+ t.Fatalf("UpdateGroup error = %v, want duplicate-name error", err)
+ }
+}
+
+// A group that already carries case-variant duplicate child names (created
+// before the case-insensitive guard, on a case-sensitive collation) must stay
+// editable as long as the update does not touch those names.
+func TestReconcileChildrenAllowsLegacyCaseVariantDuplicates(t *testing.T) {
+ setupCompilationGroupTestDB(t)
+ svc := NewCompilationTemplateGroupService()
+ ctx := t.Context()
+
+ ids := seedLegacyCompilationGroup(t, "tenant-1", "legacy-group", "A", "a")
+
+ updated, err := svc.UpdateGroup(ctx, "tenant-1", "legacy-group", &GroupRequest{
+ Templates: []*GroupTemplate{
+ {ID: ids["A"], Name: "A", Kind: "text", Config: entity.JSONMap{}},
+ {ID: ids["a"], Name: "a", Kind: "text", Config: entity.JSONMap{}},
+ },
+ })
+ if err != nil {
+ t.Fatalf("UpdateGroup with legacy case-variant names: %v", err)
+ }
+ if len(updated.Templates) != 2 {
+ t.Fatalf("templates = %#v, want two", updated.Templates)
+ }
+}
+
+// A rename that lands on an untouched legacy name is a real collision and must
+// still be rejected.
+func TestReconcileChildrenRejectsRenameOntoUnchangedLegacyName(t *testing.T) {
+ setupCompilationGroupTestDB(t)
+ svc := NewCompilationTemplateGroupService()
+ ctx := t.Context()
+
+ ids := seedLegacyCompilationGroup(t, "tenant-1", "legacy-group-2", "A", "a", "B")
+
+ _, err := svc.UpdateGroup(ctx, "tenant-1", "legacy-group-2", &GroupRequest{
+ Templates: []*GroupTemplate{
+ {ID: ids["A"], Name: "b", Kind: "text", Config: entity.JSONMap{}},
+ {ID: ids["a"], Name: "a", Kind: "text", Config: entity.JSONMap{}},
+ {ID: ids["B"], Name: "B", Kind: "text", Config: entity.JSONMap{}},
+ },
+ })
+ if err == nil || !strings.Contains(err.Error(), "already exists in this group") {
+ t.Fatalf("UpdateGroup error = %v, want duplicate-name error", err)
+ }
+}
+
+// A single-template group mirrors the fallback group name onto its child, so the
+// client-submitted template name (which it also sends as the group name) does not
+// collide with a sibling group on update.
+func TestCreateGroupSingleTemplateSharesFallbackName(t *testing.T) {
+ setupCompilationGroupTestDB(t)
+ svc := NewCompilationTemplateGroupService()
+ ctx := t.Context()
+
+ first := seedCompilationGroup(t, svc, "tenant-1", "Group A", "tpl")
+ if first.Templates[0].Name != "Group A" {
+ t.Fatalf("first template name = %q, want %q", first.Templates[0].Name, "Group A")
+ }
+
+ second := seedCompilationGroup(t, svc, "tenant-1", "Group A", "tpl")
+ if second.Name != "Group A(1)" {
+ t.Fatalf("second group name = %q, want %q", second.Name, "Group A(1)")
+ }
+ if second.Templates[0].Name != "Group A(1)" {
+ t.Fatalf("second template name = %q, want %q", second.Templates[0].Name, "Group A(1)")
+ }
+
+ updated, err := svc.UpdateGroup(ctx, "tenant-1", second.ID, &GroupRequest{
+ Name: "Group A(1)",
+ Templates: []*GroupTemplate{
+ {ID: second.Templates[0].ID, Name: "Group A(1)", Kind: "text", Config: entity.JSONMap{}},
+ },
+ })
+ if err != nil {
+ t.Fatalf("UpdateGroup after fallback: %v", err)
+ }
+ if updated.Name != "Group A(1)" {
+ t.Fatalf("updated group name = %q, want %q", updated.Name, "Group A(1)")
+ }
+ if updated.Templates[0].Name != "Group A(1)" {
+ t.Fatalf("updated template name = %q, want %q", updated.Templates[0].Name, "Group A(1)")
+ }
+}
+
+// Multi-template groups keep their own per-group deduped child names; only a
+// single-template group mirrors the group name.
+func TestCreateGroupMultiTemplateKeepsChildNames(t *testing.T) {
+ setupCompilationGroupTestDB(t)
+ svc := NewCompilationTemplateGroupService()
+
+ group := seedCompilationGroup(t, svc, "tenant-1", "Group A", "A", "B")
+ if group.Templates[0].Name != "A" {
+ t.Fatalf("first template name = %q, want %q", group.Templates[0].Name, "A")
+ }
+ if group.Templates[1].Name != "B" {
+ t.Fatalf("second template name = %q, want %q", group.Templates[1].Name, "B")
+ }
+}
diff --git a/internal/service/dataset/crud.go b/internal/service/dataset/crud.go
index 35da7433f7..5273481471 100644
--- a/internal/service/dataset/crud.go
+++ b/internal/service/dataset/crud.go
@@ -189,9 +189,12 @@ func (d *DatasetService) CreateDataset(ctx context.Context, req *service.CreateD
kbID := utility.GenerateToken()
status := string(entity.StatusValid)
- // Mirror Python's duplicate_name: append (1), (2), ... until the name is
- // unique within the tenant.
- name = d.dedupeDatasetName(ctx, name, tenantID)
+ // Fall back to a numbered name when the requested one is already taken.
+ dedupedName, dedupeErr := d.dedupeDatasetName(ctx, name, tenantID)
+ if dedupeErr != nil {
+ return nil, common.CodeServerError, dedupeErr
+ }
+ name = dedupedName
parserConfig = service.ApplyComponentScopedParserConfig(
parserConfig,
@@ -232,18 +235,12 @@ func (d *DatasetService) CreateDataset(ctx context.Context, req *service.CreateD
return datasetToMap(createdKB), common.CodeSuccess, nil
}
-// dedupeDatasetName mirrors Python's duplicate_name: if the name already
-// exists within the tenant, append (1), (2), ... until it is unique.
-func (d *DatasetService) dedupeDatasetName(ctx context.Context, name, tenantID string) string {
- candidate := name
- for i := 1; i < 1000; i++ {
- existing, err := d.kbDAO.GetByName(ctx, dao.DB, candidate, tenantID)
- if err != nil || existing == nil {
- return candidate
- }
- candidate = fmt.Sprintf("%s(%d)", name, i)
- }
- return candidate
+// dedupeDatasetName returns a non-colliding dataset name within the tenant,
+// appending (1), (2), ... when the requested name is already taken.
+func (d *DatasetService) dedupeDatasetName(ctx context.Context, name, tenantID string) (string, error) {
+ return common.UniqueName(name, entity.DatasetNameLimit, func(candidate string) (bool, error) {
+ return d.kbDAO.NameExists(ctx, dao.DB, tenantID, candidate)
+ })
}
func (d *DatasetService) GetDataset(ctx context.Context, datasetID, userID string) (map[string]interface{}, common.ErrorCode, error) {
diff --git a/internal/service/dataset/update.go b/internal/service/dataset/update.go
index 99b330171a..1a3c925ffd 100644
--- a/internal/service/dataset/update.go
+++ b/internal/service/dataset/update.go
@@ -195,14 +195,23 @@ func (d *DatasetService) UpdateDataset(ctx context.Context, datasetID, tenantID
updates[key] = value
}
- if nameValue, ok := updates["name"].(string); ok && strings.ToLower(nameValue) != strings.ToLower(lockedKB.Name) {
- var existing entity.Knowledgebase
- lookupErr := tx.Where("LOWER(name) = LOWER(?) AND tenant_id = ? AND status = ?", nameValue, tenantID, string(entity.StatusValid)).First(&existing).Error
- if lookupErr != nil && !dao.IsNotFoundErr(lookupErr) {
+ if nameValue, ok := updates["name"].(string); ok {
+ available, nameErr := common.NameAvailable(lockedKB.Name, nameValue, func(candidate string) (bool, error) {
+ var existing entity.Knowledgebase
+ lookupErr := tx.Where("LOWER(name) = LOWER(?) AND tenant_id = ? AND status = ?", candidate, tenantID, string(entity.StatusValid)).First(&existing).Error
+ if lookupErr != nil {
+ if dao.IsNotFoundErr(lookupErr) {
+ return false, nil
+ }
+ return false, lookupErr
+ }
+ return true, nil
+ })
+ if nameErr != nil {
txCode = common.CodeServerError
return errors.New("database operation failed")
}
- if lookupErr == nil {
+ if !available {
txCode = common.CodeDataError
return fmt.Errorf("Dataset name '%s' already exists", nameValue)
}
diff --git a/internal/service/document/document_crud.go b/internal/service/document/document_crud.go
index 10b0e76167..5b05deb8e1 100644
--- a/internal/service/document/document_crud.go
+++ b/internal/service/document/document_crud.go
@@ -386,15 +386,9 @@ func (s *DocumentService) InsertDocument(doc *entity.Document) error {
// Returns an error when the existing-name lookup fails so callers never write
// blind and risk duplicated document names.
func (s *DocumentService) UniqueDocumentName(ctx context.Context, kbID, name string) (string, error) {
- names, err := s.documentDAO.ListNamesByKbID(ctx, dao.DB, kbID)
- if err != nil {
- return "", err
- }
- taken := make(map[string]bool, len(names))
- for _, n := range names {
- taken[n] = true
- }
- return uniqueUploadName(name, taken), nil
+ return common.UniqueFileName(name, 255, func(candidate string) (bool, error) {
+ return s.documentDAO.NameExistsInKB(ctx, dao.DB, kbID, candidate)
+ })
}
// resolveDocAndKB loads the document and its knowledgebase, returning both or
diff --git a/internal/service/document/document_dataset_update.go b/internal/service/document/document_dataset_update.go
index cabe485207..28518b9cf7 100644
--- a/internal/service/document/document_dataset_update.go
+++ b/internal/service/document/document_dataset_update.go
@@ -383,14 +383,14 @@ func (s *DocumentService) validateDocumentName(ctx context.Context, doc *entity.
return common.CodeArgumentError, errors.New("the extension of file can't be changed")
}
- docs, err := s.documentDAO.GetByNameAndKBID(ctx, dao.DB, newName, doc.KbID)
+ available, err := common.NameAvailable(oldName, newName, func(candidate string) (bool, error) {
+ return s.documentDAO.NameExistsInKB(ctx, dao.DB, doc.KbID, candidate)
+ })
if err != nil {
return common.CodeServerError, err
}
- for _, d := range docs {
- if d.ID != doc.ID && d.Name != nil && *d.Name == newName {
- return common.CodeDataError, errors.New("duplicated document name in the same dataset")
- }
+ if !available {
+ return common.CodeDataError, errors.New("duplicated document name in the same dataset")
}
return common.CodeSuccess, nil
diff --git a/internal/service/document/document_upload.go b/internal/service/document/document_upload.go
index 0d56b0be29..247fdd09ad 100644
--- a/internal/service/document/document_upload.go
+++ b/internal/service/document/document_upload.go
@@ -51,17 +51,6 @@ func (s *DocumentService) UploadLocalDocuments(ctx context.Context, kb *entity.K
safeParent := utility.SanitizeFilename(parentPath)
- // Don't silently disable dedupe protection: a transient lookup failure means
- // the existing-name set is unknown, so fail rather than risk duplicates.
- names, err := s.documentDAO.ListNamesByKbID(ctx, dao.DB, kb.ID)
- if err != nil {
- return nil, []string{err.Error()}
- }
- taken := map[string]bool{}
- for _, n := range names {
- taken[n] = true
- }
-
var results []map[string]interface{}
var errMsgs []string
@@ -73,7 +62,13 @@ func (s *DocumentService) UploadLocalDocuments(ctx context.Context, kb *entity.K
continue
}
- filename := uniqueUploadName(fh.Filename, taken)
+ filename, err := common.UniqueFileName(fh.Filename, 255, func(candidate string) (bool, error) {
+ return s.documentDAO.NameExistsInKB(ctx, dao.DB, kb.ID, candidate)
+ })
+ if err != nil {
+ errMsgs = append(errMsgs, fh.Filename+": "+err.Error())
+ continue
+ }
filetype := utility.FilenameType(filename)
if filetype == utility.FileTypeOTHER {
@@ -115,8 +110,6 @@ func (s *DocumentService) UploadLocalDocuments(ctx context.Context, kb *entity.K
errMsgs = append(errMsgs, fh.Filename+": "+err.Error())
continue
}
- // Only reserve the name once write fully succeeds.
- taken[filename] = true
results = append(results, docToRawMap(doc))
}
@@ -125,17 +118,13 @@ func (s *DocumentService) UploadLocalDocuments(ctx context.Context, kb *entity.K
// UploadEmptyDocument inserts a zero-byte "virtual" document into the dataset.
func (s *DocumentService) UploadEmptyDocument(ctx context.Context, kb *entity.Knowledgebase, tenantID, name string) (map[string]interface{}, common.ErrorCode, error) {
- // A transient lookup failure means the existing-name set is unknown; fail
- // rather than write blind and risk a duplicate.
- names, err := s.documentDAO.ListNamesByKbID(ctx, dao.DB, kb.ID)
+ // Fall back to a numbered name when the requested one is already taken.
+ name, err := common.UniqueFileName(name, 255, func(candidate string) (bool, error) {
+ return s.documentDAO.NameExistsInKB(ctx, dao.DB, kb.ID, candidate)
+ })
if err != nil {
return nil, common.CodeServerError, err
}
- for _, n := range names {
- if n == name {
- return nil, common.CodeDataError, fmt.Errorf("duplicated document name in the same dataset")
- }
- }
kbFolder, err := s.ensureKBFolder(ctx, kb, tenantID)
if err != nil {
@@ -252,15 +241,6 @@ func (s *DocumentService) UploadWebDocument(ctx context.Context, kb *entity.Know
return nil, common.CodeServerError, err
}
- names, err := s.documentDAO.ListNamesByKbID(ctx, dao.DB, kb.ID)
- if err != nil {
- return nil, common.CodeServerError, err
- }
- taken := map[string]bool{}
- for _, n := range names {
- taken[n] = true
- }
-
blob, headers, _, err := utility.FetchRemoteFileSafely(ctx, url, maxUploadDocSize)
if err != nil {
return nil, common.CodeDataError, err
@@ -271,7 +251,12 @@ func (s *DocumentService) UploadWebDocument(ctx context.Context, kb *entity.Know
}
filename := normalizeWebDocumentName(name, contentType, blob)
filename, _, blob = utility.NormalizeUploadInfoContent(filename, contentType, blob)
- filename = uniqueUploadName(filename, taken)
+ filename, err = common.UniqueFileName(filename, 255, func(candidate string) (bool, error) {
+ return s.documentDAO.NameExistsInKB(ctx, dao.DB, kb.ID, candidate)
+ })
+ if err != nil {
+ return nil, common.CodeServerError, err
+ }
filetype := utility.FilenameType(filename)
if filetype == utility.FileTypeOTHER {
@@ -399,24 +384,6 @@ func docToRawMap(doc *entity.Document) map[string]interface{} {
return m
}
-// uniqueUploadName appends a numeric suffix until the name is free, mirroring
-// Python duplicate_name.
-func uniqueUploadName(name string, taken map[string]bool) string {
- if !taken[name] {
- return name
- }
- base, ext := name, ""
- if i := strings.LastIndex(name, "."); i >= 0 {
- base, ext = name[:i], name[i:]
- }
- for i := 1; ; i++ {
- candidate := fmt.Sprintf("%s(%d)%s", base, i, ext)
- if !taken[candidate] {
- return candidate
- }
- }
-}
-
func readFileHeaderBytes(fh *multipart.FileHeader) ([]byte, error) {
if fh.Size > maxUploadDocSize {
return nil, fmt.Errorf("file exceeds the maximum allowed size of %d bytes", maxUploadDocSize)
diff --git a/internal/service/document/document_upload_test.go b/internal/service/document/document_upload_test.go
index 0778ef2ebb..bf676f0141 100644
--- a/internal/service/document/document_upload_test.go
+++ b/internal/service/document/document_upload_test.go
@@ -63,18 +63,3 @@ func TestNormalizeWebDocumentName(t *testing.T) {
}
}
}
-
-func TestUniqueUploadName(t *testing.T) {
- if got := uniqueUploadName("a.txt", map[string]bool{}); got != "a.txt" {
- t.Errorf("free name: got %q", got)
- }
- if got := uniqueUploadName("a.txt", map[string]bool{"a.txt": true}); got != "a(1).txt" {
- t.Errorf("single clash: got %q", got)
- }
- if got := uniqueUploadName("a.txt", map[string]bool{"a.txt": true, "a(1).txt": true}); got != "a(2).txt" {
- t.Errorf("double clash: got %q", got)
- }
- if got := uniqueUploadName("noext", map[string]bool{"noext": true}); got != "noext(1)" {
- t.Errorf("no-extension clash: got %q", got)
- }
-}
diff --git a/internal/service/file/file_folder.go b/internal/service/file/file_folder.go
index edae130eff..566b46adfb 100644
--- a/internal/service/file/file_folder.go
+++ b/internal/service/file/file_folder.go
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
- "path/filepath"
"ragflow/internal/common"
"ragflow/internal/dao"
"ragflow/internal/entity"
@@ -281,32 +280,12 @@ func (s *FileService) createFolderRecursive(ctx context.Context, parentFolder *e
return s.createFolderRecursive(ctx, newFolder, names, count+1, tenantID)
}
+// getUniqueFilename returns a non-colliding file name within the folder,
+// appending (1), (2), ... when the requested name is already taken.
func (s *FileService) getUniqueFilename(ctx context.Context, name, parentID, tenantID string) (string, error) {
- existingFiles, err := s.fileDAO.Query(ctx, dao.DB, name, parentID, tenantID)
- if err != nil {
- return "", err
- }
-
- if len(existingFiles) == 0 {
- return name, nil
- }
-
- base := filepath.Base(name)
- ext := filepath.Ext(name)
- nameWithoutExt := strings.TrimSuffix(base, ext)
-
- counter := 1
- for {
- newName := fmt.Sprintf("%s_%d%s", nameWithoutExt, counter, ext)
- existingFiles, err = s.fileDAO.Query(ctx, dao.DB, newName, parentID, tenantID)
- if err != nil {
- return "", err
- }
- if len(existingFiles) == 0 {
- return newName, nil
- }
- counter++
- }
+ return common.UniqueFileName(name, 255, func(candidate string) (bool, error) {
+ return s.fileDAO.NameExists(ctx, dao.DB, candidate, parentID, tenantID, "")
+ })
}
// CreateFolder creates a new folder or virtual file
@@ -330,23 +309,28 @@ func (s *FileService) CreateFolder(ctx context.Context, tenantID, name, parentID
return nil, fmt.Errorf("parent folder not found")
}
- existingFiles, err := s.fileDAO.Query(ctx, dao.DB, name, parentID, tenantID)
- if err != nil {
- return nil, fmt.Errorf("failed to query existing files: %w", err)
- }
- if len(existingFiles) > 0 {
- return nil, fmt.Errorf("duplicated folder name in the same folder")
- }
-
if fileType == "" {
fileType = FileTypeVirtual
}
+ if fileType != FileTypeFolder {
+ fileType = FileTypeVirtual
+ }
+ existsInParent := func(candidate string) (bool, error) {
+ return s.fileDAO.NameExists(ctx, dao.DB, candidate, parentID, tenantID, "")
+ }
+ var uniqueName string
+ var err error
if fileType == FileTypeFolder {
- fileType = FileTypeFolder
+ // A folder is not a file: append the counter to the whole name.
+ uniqueName, err = common.UniqueName(name, 255, existsInParent)
} else {
- fileType = FileTypeVirtual
+ uniqueName, err = common.UniqueFileName(name, 255, existsInParent)
+ }
+ if err != nil {
+ return nil, err
}
+ name = uniqueName
folder, err := s.fileDAO.CreateFolder(ctx, dao.DB, parentID, tenantID, name, fileType)
if err != nil {
@@ -449,34 +433,45 @@ func (s *FileService) MoveFiles(ctx context.Context, uid string, srcFileIDs []st
}
}
- // Check for duplicate names in target folder
+ // Check for duplicate names in the target folder.
targetParentID := file.ParentID
if destFolder != nil {
targetParentID = destFolder.ID
}
- var existingFiles []*entity.File
- existingFiles, err = s.fileDAO.Query(ctx, dao.DB, newName, targetParentID, file.TenantID)
- if err != nil {
- return false, fmt.Sprintf("failed to query existing files: %v", err)
+ existsInTarget := func(candidate string) (bool, error) {
+ return s.fileDAO.NameExists(ctx, dao.DB, candidate, targetParentID, file.TenantID, file.ID)
}
- for _, f := range existingFiles {
- if f.Name == newName {
+ if targetParentID == file.ParentID {
+ // Renaming within the same folder: a case-only change refers to the
+ // file itself, so the NameAvailable shortcut is safe.
+ available, err := common.NameAvailable(file.Name, newName, existsInTarget)
+ if err != nil {
+ return false, fmt.Sprintf("failed to query existing files: %v", err)
+ }
+ if !available {
+ return false, "duplicated file name in the same folder"
+ }
+ } else {
+ // Moving into another folder: the source entry is not part of the
+ // destination namespace, so always check the destination name.
+ taken, err := existsInTarget(newName)
+ if err != nil {
+ return false, fmt.Sprintf("failed to query existing files: %v", err)
+ }
+ if taken {
return false, "duplicated file name in the same folder"
}
}
} else if destFolder != nil {
- // Plain move (no rename): check for duplicate names in destination folder
+ // Plain move (no rename): check for duplicate names in destination folder.
for _, file := range files {
- var existingFiles []*entity.File
- existingFiles, err = s.fileDAO.Query(ctx, dao.DB, file.Name, destFolder.ID, file.TenantID)
+ var exists bool
+ exists, err = s.fileDAO.NameExists(ctx, dao.DB, file.Name, destFolder.ID, file.TenantID, file.ID)
if err != nil {
return false, fmt.Sprintf("failed to query existing files: %v", err)
}
- for _, f := range existingFiles {
- // Ignore the source file itself
- if f.ID != file.ID {
- return false, "Duplicated file name in the same folder."
- }
+ if exists {
+ return false, "Duplicated file name in the same folder."
}
}
}
diff --git a/internal/service/file/file_folder_test.go b/internal/service/file/file_folder_test.go
index 5cf3ab851d..45dde7c8d5 100644
--- a/internal/service/file/file_folder_test.go
+++ b/internal/service/file/file_folder_test.go
@@ -23,6 +23,66 @@ func TestFileService_CreateFolder_RejectsSlashInName(t *testing.T) {
}
}
+func TestFileService_CreateFolderDedupesDuplicateName(t *testing.T) {
+ setupFolderTestDB(t)
+
+ parent := &entity.File{ID: "pf1", ParentID: "pf1", TenantID: "tenant-1", Name: "root", Type: FileTypeFolder}
+ if err := dao.DB.Create(parent).Error; err != nil {
+ t.Fatalf("seed parent folder: %v", err)
+ }
+
+ svc := testFileService()
+ ctx := context.Background()
+
+ created, err := svc.CreateFolder(ctx, "tenant-1", "notes", "pf1", FileTypeFolder)
+ if err != nil {
+ t.Fatalf("CreateFolder failed: %v", err)
+ }
+ if got := created["name"]; got != "notes" {
+ t.Fatalf("first create name = %v, want notes", got)
+ }
+
+ // A second create with the same name in the same folder appends a counter
+ // instead of failing.
+ created, err = svc.CreateFolder(ctx, "tenant-1", "notes", "pf1", FileTypeFolder)
+ if err != nil {
+ t.Fatalf("CreateFolder failed: %v", err)
+ }
+ if got := created["name"]; got != "notes(1)" {
+ t.Fatalf("duplicate create name = %v, want notes(1)", got)
+ }
+
+ // Virtual files keep the extension at the end of the generated name.
+ if _, err = svc.CreateFolder(ctx, "tenant-1", "report.pdf", "pf1", FileTypeVirtual); err != nil {
+ t.Fatalf("CreateFolder failed: %v", err)
+ }
+ created, err = svc.CreateFolder(ctx, "tenant-1", "report.pdf", "pf1", FileTypeVirtual)
+ if err != nil {
+ t.Fatalf("CreateFolder failed: %v", err)
+ }
+ if got := created["name"]; got != "report(1).pdf" {
+ t.Fatalf("duplicate create name = %v, want report(1).pdf", got)
+ }
+
+ // Folders are not files: a dotted folder name keeps its dot at the end.
+ if got := firstCreatedFolderName(t, svc, "v1.2", FileTypeFolder); got != "v1.2" {
+ t.Fatalf("first folder name = %q, want %q", got, "v1.2")
+ }
+ if got := firstCreatedFolderName(t, svc, "v1.2", FileTypeFolder); got != "v1.2(1)" {
+ t.Fatalf("duplicate folder name = %q, want %q", got, "v1.2(1)")
+ }
+}
+
+// firstCreatedFolderName creates one entry and returns its resulting name.
+func firstCreatedFolderName(t *testing.T, svc *FileService, name, fileType string) string {
+ t.Helper()
+ created, err := svc.CreateFolder(context.Background(), "tenant-1", name, "pf1", fileType)
+ if err != nil {
+ t.Fatalf("CreateFolder(%q) failed: %v", name, err)
+ }
+ return created["name"].(string)
+}
+
func TestFileService_MoveFiles_RejectsSlashInNewName(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{TranslateError: true})
if err != nil {
@@ -53,6 +113,76 @@ func TestFileService_MoveFiles_RejectsSlashInNewName(t *testing.T) {
}
}
+func TestFileService_MoveFilesRejectsDuplicateName(t *testing.T) {
+ setupFolderTestDB(t)
+
+ if err := dao.DB.Create(&entity.File{ID: "t1", ParentID: "pf1", TenantID: "tenant-1", Name: "target", Type: FileTypeFolder}).Error; err != nil {
+ t.Fatalf("seed target folder: %v", err)
+ }
+ if err := dao.DB.Create(&entity.File{ID: "s1", ParentID: "pf1", TenantID: "tenant-1", Name: "source", Type: FileTypeFolder}).Error; err != nil {
+ t.Fatalf("seed source folder: %v", err)
+ }
+
+ svc := testFileService()
+ ctx := context.Background()
+
+ ok, msg := svc.MoveFiles(ctx, "user-1", []string{"s1"}, "", "TARGET")
+ if ok || !strings.Contains(msg, "duplicated file name") {
+ t.Fatalf("rename to case-variant duplicate = %v, %q, want duplicate error", ok, msg)
+ }
+
+ ok, msg = svc.MoveFiles(ctx, "user-1", []string{"s1"}, "", "SOURCE")
+ if !ok {
+ t.Fatalf("case-only rename failed: %q", msg)
+ }
+}
+
+// Moving a file into another folder must check the destination namespace even
+// when the requested name only differs from the source name by case.
+func TestFileService_MoveFilesRejectsCaseVariantDuplicateInDestinationFolder(t *testing.T) {
+ setupFolderTestDB(t)
+
+ for _, f := range []*entity.File{
+ {ID: "pf1", ParentID: "pf1", TenantID: "tenant-1", Name: "root", Type: FileTypeFolder},
+ {ID: "d1", ParentID: "pf1", TenantID: "tenant-1", Name: "dest", Type: FileTypeFolder},
+ {ID: "s1", ParentID: "pf1", TenantID: "tenant-1", Name: "report.txt", Type: "pdf"},
+ {ID: "existing", ParentID: "d1", TenantID: "tenant-1", Name: "report.txt", Type: "pdf"},
+ } {
+ if err := dao.DB.Create(f).Error; err != nil {
+ t.Fatalf("seed %s: %v", f.ID, err)
+ }
+ }
+
+ svc := testFileService()
+ ok, msg := svc.MoveFiles(context.Background(), "user-1", []string{"s1"}, "d1", "REPORT.TXT")
+ if ok || !strings.Contains(msg, "duplicated file name") {
+ t.Fatalf("move+case-variant rename = %v, %q, want duplicate error", ok, msg)
+ }
+}
+
+// A plain move (no new_name) must detect a case-variant duplicate in the
+// destination folder too, not only the rename path.
+func TestFileService_MoveFilesRejectsCaseVariantDuplicateWithoutRename(t *testing.T) {
+ setupFolderTestDB(t)
+
+ for _, f := range []*entity.File{
+ {ID: "pf1", ParentID: "pf1", TenantID: "tenant-1", Name: "root", Type: FileTypeFolder},
+ {ID: "d1", ParentID: "pf1", TenantID: "tenant-1", Name: "dest", Type: FileTypeFolder},
+ {ID: "s1", ParentID: "pf1", TenantID: "tenant-1", Name: "report.txt", Type: "pdf"},
+ {ID: "existing", ParentID: "d1", TenantID: "tenant-1", Name: "REPORT.TXT", Type: "pdf"},
+ } {
+ if err := dao.DB.Create(f).Error; err != nil {
+ t.Fatalf("seed %s: %v", f.ID, err)
+ }
+ }
+
+ svc := testFileService()
+ ok, msg := svc.MoveFiles(context.Background(), "user-1", []string{"s1"}, "d1", "")
+ if ok || !strings.Contains(msg, "Duplicated file name") {
+ t.Fatalf("plain move into case-variant duplicate = %v, %q, want duplicate error", ok, msg)
+ }
+}
+
// setupFolderTestDB initializes an in-memory SQLite database for file folder tests.
func setupFolderTestDB(t *testing.T) *gorm.DB {
t.Helper()
diff --git a/internal/service/mcp.go b/internal/service/mcp.go
index 0872bbba56..b96a7b5640 100644
--- a/internal/service/mcp.go
+++ b/internal/service/mcp.go
@@ -117,13 +117,13 @@ func (s *MCPService) CreateMCPServer(ctx context.Context, tenantID string, req C
return nil, common.CodeDataError, fmt.Errorf("Invalid MCP name or length is %d which is large than 255.", len([]byte(req.Name)))
}
- exists, err := s.mcpServerDAO.ExistsByNameAndTenant(ctx, dao.DB, req.Name, tenantID)
+ name, err := common.UniqueName(req.Name, mcpServerNameLimit, func(candidate string) (bool, error) {
+ return s.mcpServerDAO.ExistsByNameAndTenant(ctx, dao.DB, candidate, tenantID)
+ })
if err != nil {
return nil, common.CodeServerError, err
}
- if exists {
- return nil, common.CodeDataError, errors.New("duplicated MCP server name")
- }
+ req.Name = name
if req.URL == "" {
return nil, common.CodeDataError, errors.New("invalid url")
@@ -412,12 +412,14 @@ func (s *MCPService) UpdateMCPServer(ctx context.Context, tenantID, mcpID string
if serverName != "" && len([]byte(serverName)) > mcpServerNameLimit {
return nil, common.CodeDataError, fmt.Errorf("Invalid MCP name or length is %d which is large than 255.", len([]byte(serverName)))
}
- if serverNameProvided && serverName != server.Name {
- exists, err := s.mcpServerDAO.ExistsByNameAndTenant(ctx, dao.DB, serverName, tenantID)
+ if serverNameProvided {
+ available, err := common.NameAvailable(server.Name, serverName, func(candidate string) (bool, error) {
+ return s.mcpServerDAO.ExistsByNameAndTenant(ctx, dao.DB, candidate, tenantID)
+ })
if err != nil {
return nil, common.CodeServerError, err
}
- if exists {
+ if !available {
return nil, common.CodeDataError, errors.New("duplicated MCP server name")
}
}
@@ -776,19 +778,9 @@ func (s *MCPService) ImportServers(ctx context.Context, tenantID string, servers
}
func (s *MCPService) nextAvailableMCPName(ctx context.Context, base, tenantID string) (string, error) {
- name := base
- counter := 0
- for {
- exists, err := s.mcpServerDAO.ExistsByNameAndTenant(ctx, dao.DB, name, tenantID)
- if err != nil {
- return "", err
- }
- if !exists {
- return name, nil
- }
- name = fmt.Sprintf("%s_%d", base, counter)
- counter++
- }
+ return common.UniqueName(base, mcpServerNameLimit, func(candidate string) (bool, error) {
+ return s.mcpServerDAO.ExistsByNameAndTenant(ctx, dao.DB, candidate, tenantID)
+ })
}
// TestServerRequest previews unsaved connection settings. A masked token is
diff --git a/internal/service/mcp_test.go b/internal/service/mcp_test.go
index 4e6fd15c28..51735253af 100644
--- a/internal/service/mcp_test.go
+++ b/internal/service/mcp_test.go
@@ -421,7 +421,7 @@ func TestImportServersPreservesExplicitHeadersAndVariables(t *testing.T) {
}
}
var roundTripped entity.MCPServer
- if err := testDB.Where("name = ?", "parallel_0").First(&roundTripped).Error; err != nil {
+ if err := testDB.Where("name = ?", "parallel(1)").First(&roundTripped).Error; err != nil {
t.Fatalf("load reimported server: %v", err)
}
if len(roundTripped.Headers) != len(tc.headers) {
diff --git a/internal/service/memory.go b/internal/service/memory.go
index 27cfb0ad16..a68ff6325f 100644
--- a/internal/service/memory.go
+++ b/internal/service/memory.go
@@ -509,10 +509,13 @@ func (s *MemoryService) CreateMemory(ctx context.Context, tenantID string, req *
uniqueMemoryTypes = append(uniqueMemoryTypes, mt)
}
- memoryName, err := common.DuplicateName(func(name string, tid string) bool {
- existing, _ := s.memoryDAO.GetByNameAndTenant(ctx, dao.DB, name, tid)
- return len(existing) > 0
- }, memoryName, tenantID)
+ memoryName, err := common.UniqueName(memoryName, MemoryNameLimit, func(candidate string) (bool, error) {
+ existing, err := s.memoryDAO.GetByNameAndTenant(ctx, dao.DB, candidate, tenantID)
+ if err != nil {
+ return false, err
+ }
+ return len(existing) > 0, nil
+ })
if err != nil {
return nil, err
}
@@ -589,16 +592,20 @@ func (s *MemoryService) UpdateMemory(ctx context.Context, tenantID string, memor
if err = common.ValidateName(memoryName); err != nil {
return nil, err
}
- if memoryName != strings.TrimSpace(currentMemory.Name) {
- memoryName, err = common.DuplicateName(func(name string, tid string) bool {
- existing, _ := s.memoryDAO.GetByNameAndTenant(ctx, dao.DB, name, tid)
- return len(existing) > 0
- }, memoryName, ownerTenantID)
+ available, nameErr := common.NameAvailable(strings.TrimSpace(currentMemory.Name), memoryName, func(candidate string) (bool, error) {
+ existing, err := s.memoryDAO.GetByNameAndTenant(ctx, dao.DB, candidate, ownerTenantID)
if err != nil {
- return nil, err
+ return false, err
}
- updateDict["name"] = memoryName
+ return len(existing) > 0, nil
+ })
+ if nameErr != nil {
+ return nil, nameErr
+ }
+ if !available {
+ return nil, errors.New("duplicated memory name")
}
+ updateDict["name"] = memoryName
}
if req.Permissions != nil {
diff --git a/internal/service/search.go b/internal/service/search.go
index 930f086c0c..fc28675c56 100644
--- a/internal/service/search.go
+++ b/internal/service/search.go
@@ -204,10 +204,15 @@ func (s *SearchService) CreateSearch(ctx context.Context, userID string, name st
searchID := utility.GenerateUUID()
// Generate unique name (same as Python duplicate_name)
- uniqueName, err := common.DuplicateName(func(name string, tid string) bool {
- existing, _ := s.searchDAO.GetByNameAndTenant(ctx, dao.DB, name, tid)
- return len(existing) > 0
- }, name, userID)
+ // search.name is a 128-byte column; keep generated names within it.
+ uniqueName, err := common.UniqueName(name, 128, func(candidate string) (bool, error) {
+ existing, err := s.searchDAO.GetByNameAndTenant(ctx, dao.DB, candidate, userID)
+ if err != nil {
+ return false, err
+ }
+ return len(existing) > 0, nil
+ })
+
if err != nil {
return nil, err
}
@@ -609,14 +614,21 @@ func (s *SearchService) UpdateSearch(ctx context.Context, userID string, searchI
return nil, fmt.Errorf("cannot find search %s", searchID)
}
- // Step 3: Check for duplicate name (if name changed)
- // Python: if req["name"].lower() != search_app.name.lower() and len(SearchService.query(...)) >= 1
+ // Step 3: Check for duplicate name. Case-only changes are allowed, matching
+ // the dataset rename rule.
trimmedName := req.Name
- if search.Name != trimmedName {
- existing, _ := s.searchDAO.GetByNameAndTenant(ctx, dao.DB, trimmedName, userID)
- if len(existing) > 0 {
- return nil, fmt.Errorf("duplicated search name")
+ available, err := common.NameAvailable(search.Name, trimmedName, func(candidate string) (bool, error) {
+ existing, err := s.searchDAO.GetByNameAndTenant(ctx, dao.DB, candidate, userID)
+ if err != nil {
+ return false, err
}
+ return len(existing) > 0, nil
+ })
+ if err != nil {
+ return nil, err
+ }
+ if !available {
+ return nil, fmt.Errorf("duplicated search name")
}
if err := NormalizeSimilarityWeights(req.SearchConfig); err != nil {
return nil, err
diff --git a/internal/service/skill_space.go b/internal/service/skill_space.go
index f3f9f485fc..e12be6ae10 100644
--- a/internal/service/skill_space.go
+++ b/internal/service/skill_space.go
@@ -164,24 +164,33 @@ func (s *SkillSpaceService) CreateSpace(ctx context.Context, req *CreateSpaceReq
s.spaceCreateMu.Delete(tenantKey)
}()
- // Double-check after acquiring lock: Check if space with same name already exists (active status)
- existingSpace, err := s.spaceDAO.GetByTenantAndName(ctx, dao.DB, req.TenantID, req.Name)
+ // Fall back to a numbered name when an active space already uses the
+ // requested one, mirroring the dataset create rule.
+ // skill_space.name is a 128-byte column; keep generated names within it.
+ spaceName, err := common.UniqueName(req.Name, 128, func(candidate string) (bool, error) {
+ existing, lookupErr := s.spaceDAO.GetByTenantAndName(ctx, dao.DB, req.TenantID, candidate)
+ if lookupErr != nil {
+ if dao.IsNotFoundErr(lookupErr) {
+ return false, nil
+ }
+ return false, lookupErr
+ }
+ return existing != nil, nil
+ })
if err != nil {
- // Space doesn't exist, continue
- } else if existingSpace != nil {
- return nil, common.CodeDataError, fmt.Errorf("space with name '%s' already exists", req.Name)
+ return nil, common.CodeOperatingError, err
}
// Check if there's a space with the same name that is currently being deleted
- existingSpaceAny, err := s.spaceDAO.GetByTenantAndNameAnyStatus(ctx, dao.DB, req.TenantID, req.Name)
+ existingSpaceAny, err := s.spaceDAO.GetByTenantAndNameAnyStatus(ctx, dao.DB, req.TenantID, spaceName)
if err == nil && existingSpaceAny != nil && existingSpaceAny.Status == entity.SpaceStatusDeleting {
- return nil, common.CodeDataError, fmt.Errorf("space with name '%s' is being deleted, please try again later", req.Name)
+ return nil, common.CodeDataError, fmt.Errorf("space with name '%s' is being deleted, please try again later", spaceName)
}
// Check if there's a deleted/non-active space with the same name and permanently delete it
// This handles the case where a previous creation failed partially
// Only delete non-active spaces (status != '1') to prevent TOCTOU race
- if err = s.spaceDAO.DeletePermanentByName(ctx, dao.DB, req.TenantID, req.Name); err != nil {
+ if err = s.spaceDAO.DeletePermanentByName(ctx, dao.DB, req.TenantID, spaceName); err != nil {
common.Warn("Failed to delete permanent space by name", zap.Error(err))
}
@@ -194,13 +203,13 @@ func (s *SkillSpaceService) CreateSpace(ctx context.Context, req *CreateSpaceReq
// Check if there's an existing folder with the same name under skills folder
// If exists, delete it to prevent duplicate folder names
- existingFolders, err := s.fileDAO.Query(ctx, dao.DB, req.Name, skillsFolderID, req.TenantID)
+ existingFolders, err := s.fileDAO.Query(ctx, dao.DB, spaceName, skillsFolderID, req.TenantID)
if err != nil {
return nil, common.CodeOperatingError, fmt.Errorf("failed to query existing folders: %w", err)
}
for _, f := range existingFolders {
- if f.Type == "folder" && f.Name == req.Name {
- common.Info("Deleting existing space folder with same name", zap.String("folderID", f.ID), zap.String("name", req.Name))
+ if f.Type == "folder" && f.Name == spaceName {
+ common.Info("Deleting existing space folder with same name", zap.String("folderID", f.ID), zap.String("name", spaceName))
if err = s.deleteFolderRecursive(ctx, f.ID); err != nil {
common.Warn("Failed to delete existing folder", zap.String("folderID", f.ID), zap.Error(err))
}
@@ -218,7 +227,7 @@ func (s *SkillSpaceService) CreateSpace(ctx context.Context, req *CreateSpaceReq
ParentID: skillsFolderID,
TenantID: req.TenantID,
CreatedBy: req.TenantID,
- Name: req.Name,
+ Name: spaceName,
Type: "folder",
Size: 0,
SourceType: "skill_space",
@@ -233,7 +242,7 @@ func (s *SkillSpaceService) CreateSpace(ctx context.Context, req *CreateSpaceReq
space := &entity.SkillSpace{
ID: spaceID,
TenantID: req.TenantID,
- Name: req.Name,
+ Name: spaceName,
FolderID: folderID,
Description: req.Description,
EmbdID: req.EmbdID,
@@ -328,9 +337,22 @@ func (s *SkillSpaceService) UpdateSpace(ctx context.Context, spaceID string, ten
updates := make(map[string]interface{})
if req.Name != "" && req.Name != space.Name {
- // Check if name already exists
- existingSpace, _ := s.spaceDAO.GetByTenantAndName(ctx, dao.DB, tenantID, req.Name)
- if existingSpace != nil && existingSpace.ID != spaceID {
+ // Reject a rename onto another space's name; case-only changes are
+ // allowed, matching the dataset rename rule.
+ available, err := common.NameAvailable(space.Name, req.Name, func(candidate string) (bool, error) {
+ existing, lookupErr := s.spaceDAO.GetByTenantAndName(ctx, dao.DB, tenantID, candidate)
+ if lookupErr != nil {
+ if dao.IsNotFoundErr(lookupErr) {
+ return false, nil
+ }
+ return false, lookupErr
+ }
+ return existing != nil && existing.ID != spaceID, nil
+ })
+ if err != nil {
+ return nil, common.CodeOperatingError, err
+ }
+ if !available {
return nil, common.CodeDataError, fmt.Errorf("space with name '%s' already exists", req.Name)
}
diff --git a/test/testcases/restful_api/test_agents.py b/test/testcases/restful_api/test_agents.py
index 0b920c8f87..fe97a5ad91 100644
--- a/test/testcases/restful_api/test_agents.py
+++ b/test/testcases/restful_api/test_agents.py
@@ -109,8 +109,12 @@ def test_agents_crud_validation_contract(rest_client, create_agent_resource):
duplicate = rest_client.post("/agents", json={"title": "restful_agent_crud", "dsl": MINIMAL_DSL})
assert duplicate.status_code == 200
duplicate_payload = duplicate.json()
- assert duplicate_payload["code"] == 102, duplicate_payload
- assert "already exists" in duplicate_payload["message"], duplicate_payload
+ assert duplicate_payload["code"] == 0, duplicate_payload
+ assert duplicate_payload["data"]["title"] == "restful_agent_crud(1)", duplicate_payload
+ duplicate_id = duplicate_payload["data"]["id"]
+ cleanup_duplicate = rest_client.delete(f"/agents/{duplicate_id}")
+ assert cleanup_duplicate.status_code == 200
+ assert cleanup_duplicate.json()["code"] == 0, cleanup_duplicate.json()
invalid_update = rest_client.put("/agents/invalid-agent-id", json={"title": "updated", "dsl": MINIMAL_DSL})
assert invalid_update.status_code == 200
diff --git a/test/testcases/restful_api/test_agents_go_mode.py b/test/testcases/restful_api/test_agents_go_mode.py
index 7226d05817..a72bcbf877 100644
--- a/test/testcases/restful_api/test_agents_go_mode.py
+++ b/test/testcases/restful_api/test_agents_go_mode.py
@@ -26,7 +26,7 @@ V2_DSL = {
@pytest.mark.p2
def test_v2_dsl_round_trip_position_preserved(rest_client):
- # Unique title per run so the test is idempotent (Go returns 102 on duplicate).
+ # Unique title per run so the test is idempotent.
title = f"go_v2_e2e_{uuid.uuid4().hex[:8]}"
# 1. POST v2 DSL
diff --git a/test/testcases/restful_api/test_chats.py b/test/testcases/restful_api/test_chats.py
index d0ac9314cc..501987d26b 100644
--- a/test/testcases/restful_api/test_chats.py
+++ b/test/testcases/restful_api/test_chats.py
@@ -168,8 +168,8 @@ def test_chat_duplicate_name_validation(rest_client, clear_chats):
second = rest_client.post("/chats", json={"name": "duplicate_chat_name", "dataset_ids": []})
assert second.status_code == 200
second_payload = second.json()
- assert second_payload["code"] == 102, second_payload
- assert "duplicated chat name" in second_payload["message"], second_payload
+ assert second_payload["code"] == 0, second_payload
+ assert second_payload["data"]["name"] == "duplicate_chat_name(1)", second_payload
@pytest.mark.p2
diff --git a/test/testcases/restful_api/test_files.py b/test/testcases/restful_api/test_files.py
index 566b14657a..291a74df8e 100644
--- a/test/testcases/restful_api/test_files.py
+++ b/test/testcases/restful_api/test_files.py
@@ -62,3 +62,40 @@ def test_files_list_create_folder_and_upload_to_root(rest_client, tmp_path):
finally:
if created_ids:
rest_client.delete("/files", json={"ids": created_ids})
+
+
+def test_files_folder_create_fallback_and_rename_duplicate(rest_client):
+ created_ids: list[str] = []
+ suffix = uuid.uuid4().hex[:12]
+ folder_name = f"rf_dup_folder_{suffix}"
+
+ try:
+ first = _assert_ok(rest_client.post("/files", json={"name": folder_name, "type": "folder"}))
+ created_ids.append(first["id"])
+ assert first["name"] == folder_name, first
+
+ # A duplicate create falls back to a numbered name instead of failing.
+ second = _assert_ok(rest_client.post("/files", json={"name": folder_name, "type": "folder"}))
+ created_ids.append(second["id"])
+ assert second["name"] == f"{folder_name}(1)", second
+
+ # Renaming onto another entry's name is rejected.
+ duplicate_rename = rest_client.post(
+ "/files/move",
+ json={"src_file_ids": [second["id"]], "new_name": folder_name},
+ )
+ assert duplicate_rename.status_code == 200, duplicate_rename.text
+ duplicate_rename_payload = duplicate_rename.json()
+ assert duplicate_rename_payload["code"] != 0, duplicate_rename_payload
+ assert "duplicated file name" in duplicate_rename_payload["message"], duplicate_rename_payload
+
+ # A case-only rename of the same entry is allowed.
+ case_only_rename = rest_client.post(
+ "/files/move",
+ json={"src_file_ids": [second["id"]], "new_name": second["name"].upper()},
+ )
+ assert _assert_ok(case_only_rename) is True, case_only_rename.text
+ finally:
+ if created_ids:
+ rest_client.delete("/files", json={"ids": created_ids})