Skip to content

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

fix(tag): rebuild tagging on a Go tag source index (#19985)

qinling021025a7c14e4f18
diff --git a/internal/cli/cli_http.go b/internal/cli/cli_http.go
index d8687f7c76..bf6d17d29f 100644
--- a/internal/cli/cli_http.go
+++ b/internal/cli/cli_http.go
@@ -536,8 +536,6 @@ func (c *CLI) ExecuteUserCommand(commandCount int, cmd *Command) (ResponseIf, er
return c.DevSetMetaCommand(commandCount, cmd)
case "dev_delete_meta":
return c.DevDeleteMetaCommand(commandCount, cmd)
- case "dev_rm_tags":
- return c.DevRmTagsCommand(commandCount, cmd)
case "dev_remove_chunks":
return c.DevRemoveChunksCommand(commandCount, cmd)
case "dev_get_metadata":
diff --git a/internal/cli/dev_parser.go b/internal/cli/dev_parser.go
index 06f91e509f..d33b22fac6 100644
--- a/internal/cli/dev_parser.go
+++ b/internal/cli/dev_parser.go
@@ -283,61 +283,6 @@ func (p *Parser) parseDevDeleteMeta() (*Command, error) {
return cmd, nil
}
-// parseDevRemoveTags parses: REMOVE TAGS 'tag1', 'tag2' from DATASET 'dataset_name';
-func (p *Parser) parseDevRemoveTags() (*Command, error) {
- p.nextToken() // consume TAGS
-
- // Parse first tag
- tag, err := p.parseQuotedString()
- if err != nil {
- return nil, fmt.Errorf("expected tag: %w", err)
- }
- tags := []string{tag}
-
- // Parse additional tags separated by commas
- for {
- p.nextToken()
- if p.curToken.Type == TokenComma {
- p.nextToken()
- tag, err := p.parseQuotedString()
- if err != nil {
- return nil, fmt.Errorf("expected tag after comma: %w", err)
- }
- tags = append(tags, tag)
- } else {
- break
- }
- }
- cmd := NewCommand("dev_rm_tags")
- cmd.Params["tags"] = tags
-
- // Expect from
- if p.curToken.Type != TokenFrom {
- return nil, fmt.Errorf("expected FROM after tags")
- }
- p.nextToken()
-
- // Expect DATASET
- if p.curToken.Type != TokenDataset {
- return nil, fmt.Errorf("expected DATASET after FROM")
- }
- p.nextToken()
-
- // Parse dataset_name
- datasetName, err := p.parseQuotedString()
- if err != nil {
- return nil, fmt.Errorf("expected dataset_name: %w", err)
- }
- cmd.Params["dataset_name"] = datasetName
-
- // Semicolon is optional
- if p.curToken.Type == TokenSemicolon {
- p.nextToken()
- }
-
- return cmd, nil
-}
-
// parseDevRemoveChunk parses:
// - REMOVE CHUNKS 'chunk_id1', 'chunk_id2' FROM DOCUMENT 'doc_id' IN DATASET 'dataset_name';
// - REMOVE ALL CHUNKS FROM DOCUMENT 'doc_id' IN DATASET 'dataset_name';
diff --git a/internal/cli/lexer.go b/internal/cli/lexer.go
index 07c618be95..46dfc6eeab 100644
--- a/internal/cli/lexer.go
+++ b/internal/cli/lexer.go
@@ -479,8 +479,6 @@ func (l *Lexer) lookupIdent(ident string) Token {
return Token{Type: TokenDocument, Value: ident}
case "DOCUMENTS":
return Token{Type: TokenDocuments, Value: ident}
- case "TAGS":
- return Token{Type: TokenTag, Value: ident}
case "REGION":
return Token{Type: TokenRegion, Value: ident}
case "URL":
diff --git a/internal/cli/types.go b/internal/cli/types.go
index 2ebdc71876..d525bb5ec9 100644
--- a/internal/cli/types.go
+++ b/internal/cli/types.go
@@ -170,7 +170,6 @@ const (
TokenChunks
TokenDocument
TokenDocuments
- TokenTag
TokenRegion
TokenURL
TokenTask
diff --git a/internal/cli/user_command.go b/internal/cli/user_command.go
index c9b73aee60..5d330f8d4a 100644
--- a/internal/cli/user_command.go
+++ b/internal/cli/user_command.go
@@ -3120,63 +3120,6 @@ func (c *CLI) DevDeleteMetaCommand(commandCount int, cmd *Command) (ResponseIf,
return &result, nil
}
-// DevRmTagsCommand removes tags from chunks in a dataset
-func (c *CLI) DevRmTagsCommand(commandCount int, cmd *Command) (ResponseIf, error) {
- if c.Config.CLIMode != APIMode {
- return nil, fmt.Errorf("this command is only allowed in USER mode")
- }
-
- httpClient := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer]
-
- datasetName, ok := cmd.Params["dataset_name"].(string)
- if !ok {
- return nil, fmt.Errorf("dataset_name not provided")
- }
-
- kbID, err := c.getDatasetID(datasetName)
- if err != nil {
- return nil, err
- }
-
- tags, ok := cmd.Params["tags"].([]string)
- if !ok {
- return nil, fmt.Errorf("tags not provided")
- }
-
- payload := map[string]interface{}{
- "tags": tags,
- }
-
- resp, err := httpClient.Request(commandCount, "DELETE", "/datasets/"+kbID+"/tags", "web", nil, payload)
- if err != nil {
- return nil, fmt.Errorf("failed to remove tags: %w", err)
- }
-
- if resp.StatusCode != 200 {
- return nil, fmt.Errorf("failed to remove tags: HTTP %d, body: %s", resp.StatusCode, string(resp.Body))
- }
-
- resJSON, err := resp.JSON()
- if err != nil {
- return nil, fmt.Errorf("invalid JSON response: %w", err)
- }
-
- code, ok := resJSON["code"].(float64)
- if !ok {
- return nil, fmt.Errorf("invalid response format: code is not a number")
- }
-
- var result SimpleResponse
- result.Code = int(code)
- if result.Code == 0 {
- result.Message = fmt.Sprintf("Success to remove tags from dataset: %s", kbID)
- } else {
- result.Message = fmt.Sprintf("Failed to remove tags: %v", resJSON)
- }
- result.Duration = 0
- return &result, nil
-}
-
// DevRemoveChunksCommand removes chunks from a document
func (c *CLI) DevRemoveChunksCommand(commandCount int, cmd *Command) (ResponseIf, error) {
if c.Config.CLIMode != APIMode {
diff --git a/internal/cli/user_parser.go b/internal/cli/user_parser.go
index af74729a67..ac74d1751b 100644
--- a/internal/cli/user_parser.go
+++ b/internal/cli/user_parser.go
@@ -3653,8 +3653,6 @@ func (p *Parser) parseAPIRemove() (*Command, error) {
return p.parseAPIRemoveTask()
// Dev commands
- case TokenTag:
- return p.parseDevRemoveTags()
case TokenChunks, TokenAll:
return p.parseDevRemoveChunk()
default:
diff --git a/internal/development.md b/internal/development.md
index 150bbbf78a..8d4ee7ae06 100644
--- a/internal/development.md
+++ b/internal/development.md
@@ -689,11 +689,6 @@ RAGFlow(api/default)> CREATE CHUNK STORE FOR DATASET 'test' VECTOR SIZE 384
RAGFlow(api/default)> UPDATE CHUNK 'deb165dc6a732a64' OF DOCUMENT 'bbe55942535e11f1bc5184ba59049aa3' IN DATASET 'test' SET '{"content": "Updated chunk content here", "important_keywords": ["keyword1", "keyword2"], "questions": ["What is this about?", "Why is it important?"], "available": true, "tag_kwd": ["tag5", "tag2"]}'
```
-- Remove tags from a dataset
-```
-RAGFlow(api/default)> REMOVE TAGS 'tag1', 'tag2' FROM DATASET 'test'
-```
-
- Remove specific chunks from a document
```
RAGFlow(api/default)> REMOVE CHUNKS '29cc4f6d7a5c6e7c' '0360e3d8519eab12' FROM DOCUMENT 'bbe55942535e11f1bc5184ba59049aa3' IN DATASET 'test'
diff --git a/internal/handler/chunk.go b/internal/handler/chunk.go
index 7013b1ea9d..e6207c942e 100644
--- a/internal/handler/chunk.go
+++ b/internal/handler/chunk.go
@@ -549,12 +549,17 @@ func (h *ChunkHandler) UpdateChunk(c *gin.Context) {
"questions": true,
"available": true,
"positions": true,
- "tag_kwd": true,
- "tag_feas": true,
+ // Accepted but never persisted: the UI always sends tag_kwd, so
+ // dropping it here would 400 every chunk edit. Go's tagger writes
+ // tag_feas; tag_kwd belongs to a Python tag dataset
+ // (rag/app/tag.py::beAdoc), which Go never builds. Left out of the
+ // error text below so it does not read as updatable.
+ "tag_kwd": true,
+ "tag_feas": true,
}
for field := range rawBody {
if field != "dataset_id" && field != "document_id" && field != "chunk_id" && !allowedFields[field] {
- common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Update field '"+field+"' is not supported. Updatable fields: content, important_keywords, questions, available, positions, tag_kwd, tag_feas")
+ common.ResponseWithHttpCodeData(c, http.StatusBadRequest, 400, nil, "Update field '"+field+"' is not supported. Updatable fields: content, important_keywords, questions, available, positions, tag_feas")
return
}
}
@@ -586,14 +591,6 @@ func (h *ChunkHandler) UpdateChunk(c *gin.Context) {
if positions, ok := rawBody["positions"].([]interface{}); ok {
req.Positions = positions
}
- if tagKwd, ok := rawBody["tag_kwd"].([]interface{}); ok {
- req.TagKwd = make([]string, len(tagKwd))
- for i, v := range tagKwd {
- if s, ok := v.(string); ok {
- req.TagKwd[i] = s
- }
- }
- }
req.TagFeas = rawBody["tag_feas"]
// Set path parameters
@@ -749,11 +746,6 @@ func (h *ChunkHandler) AddChunk(c *gin.Context) {
common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())
return
}
- tagKwd, err := addChunkStringListField(rawBody, "tag_kwd", "`tag_kwd` is required to be a list", "`tag_kwd` must be a list of strings")
- if err != nil {
- common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())
- return
- }
imageBase64, err := addChunkStringPtrField(rawBody, "image_base64")
if err != nil {
common.ResponseWithCodeData(c, common.CodeArgumentError, nil, err.Error())
@@ -773,7 +765,6 @@ func (h *ChunkHandler) AddChunk(c *gin.Context) {
Content: content,
ImportantKeywords: importantKeywords,
Questions: questions,
- TagKwd: tagKwd,
TagFeas: tagFeas,
ImageBase64: imageBase64,
}
diff --git a/internal/handler/chunk_test.go b/internal/handler/chunk_test.go
index 03679f8d44..166b86a6d9 100644
--- a/internal/handler/chunk_test.go
+++ b/internal/handler/chunk_test.go
@@ -755,11 +755,6 @@ func TestChunkHandlerAddChunkValidatesListFields(t *testing.T) {
body: `{"content":"chunk body","important_keywords":{}}`,
wantMsg: "`important_keywords` is required to be a list",
},
- {
- name: "tag kwd element type",
- body: `{"content":"chunk body","tag_kwd":[1]}`,
- wantMsg: "`tag_kwd` must be a list of strings",
- },
}
for _, tt := range tests {
diff --git a/internal/handler/dataset.go b/internal/handler/dataset.go
index 31a2382636..309a81cb18 100644
--- a/internal/handler/dataset.go
+++ b/internal/handler/dataset.go
@@ -821,81 +821,6 @@ func (h *DatasetsHandler) GetKnowledgeGraph(c *gin.Context) {
common.SuccessWithData(c, result, "success")
}
-// ListTags handles GET /api/v1/datasets/:dataset_id/tags.
-// @Summary List dataset tags
-// @Description List tags for a dataset
-// @Tags datasets
-// @Produce json
-// @Security ApiKeyAuth
-// @Param dataset_id path string true "Dataset ID"
-// @Success 200 {object} map[string]interface{}
-// @Router /api/v1/datasets/{dataset_id}/tags [get]
-func (h *DatasetsHandler) ListTags(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.ErrorWithCode(c, errorCode, errorMessage)
- return
- }
-
- ctx := c.Request.Context()
-
- datasetID := strings.TrimSpace(c.Param("dataset_id"))
- result, code, err := h.datasetsService.ListTags(ctx, datasetID, user.ID)
- if err != nil {
- common.ErrorWithCode(c, code, err.Error())
- return
- }
-
- common.SuccessWithData(c, result, "success")
-}
-
-type renameTagRequest struct {
- FromTag string `json:"from_tag"`
- ToTag string `json:"to_tag"`
-}
-
-func (h *DatasetsHandler) RenameTag(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.ErrorWithCode(c, errorCode, errorMessage)
- return
- }
- datasetID := strings.TrimSpace(c.Param("dataset_id"))
-
- var payload map[string]interface{}
- if err := c.ShouldBindJSON(&payload); err != nil {
- common.ResponseWithCodeData(c, common.CodeDataError, nil, "Lack of from_tag or to_tag in request body")
- return
- }
- fromTagValue, hasFrom := payload["from_tag"]
- toTagValue, hasTo := payload["to_tag"]
- if !hasFrom || !hasTo {
- common.ResponseWithCodeData(c, common.CodeDataError, nil, "Lack of from_tag or to_tag in request body")
- return
- }
- fromTag, okFrom := fromTagValue.(string)
- toTag, okTo := toTagValue.(string)
- if !okFrom || !okTo {
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "from_tag and to_tag must be strings")
- return
- }
- req := renameTagRequest{FromTag: fromTag, ToTag: toTag}
- if strings.TrimSpace(req.FromTag) == "" || strings.TrimSpace(req.ToTag) == "" {
- common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "from_tag and to_tag must not be empty")
- return
- }
-
- ctx := c.Request.Context()
-
- result, code, err := h.datasetsService.RenameTag(ctx, datasetID, user.ID, req.FromTag, req.ToTag)
- if err != nil {
- common.ErrorWithCode(c, code, err.Error())
- return
- }
-
- common.SuccessWithData(c, result, "success")
-}
-
// DeleteKnowledgeGraph handles DELETE /api/v1/datasets/:dataset_id/graph.
func (h *DatasetsHandler) DeleteKnowledgeGraph(c *gin.Context) {
user, errorCode, errorMessage := GetUser(c)
@@ -941,75 +866,6 @@ func (h *DatasetsHandler) DeleteKnowledgeGraph(c *gin.Context) {
common.SuccessWithData(c, true, "success")
}
-// RemoveTags handles DELETE /api/v1/datasets/:dataset_id/tags.
-// @Summary Remove Tags
-// @Description Remove tags from a dataset
-// @Tags datasets
-// @Security ApiKeyAuth
-// @Param dataset_id path string true "Dataset ID"
-// @Param request body object{tags []string} true "tags to remove"
-// @Success 200 {object} map[string]interface{}
-// @Router /api/v1/datasets/{dataset_id}/tags [delete]
-func (h *DatasetsHandler) RemoveTags(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.ErrorWithCode(c, errorCode, errorMessage)
- return
- }
-
- datasetID := strings.TrimSpace(c.Param("dataset_id"))
- if datasetID == "" {
- common.ResponseWithCodeData(c, common.CodeDataError, nil, "dataset_id is required")
- return
- }
-
- ctx := c.Request.Context()
- datasetInstance, code, err := h.datasetsService.GetDataset(ctx, datasetID, user.ID)
- if err != nil {
- common.ErrorWithCode(c, code, err.Error())
- return
- }
-
- tenantID, _ := datasetInstance["tenant_id"].(string)
- if tenantID == "" {
- common.ResponseWithCodeData(c, common.CodeDataError, nil, "tenant_id is required")
- return
- }
-
- var req struct {
- Tags []string `json:"tags" binding:"required"`
- }
- if err := c.ShouldBindJSON(&req); err != nil {
- common.ResponseWithCodeData(c, common.CodeDataError, nil, err.Error())
- return
- }
-
- indexName := fmt.Sprintf("ragflow_%s", tenantID)
- docEngine := engine.Get()
- if docEngine == nil {
- common.ResponseWithCodeData(c, common.CodeServerError, nil, "Document engine is not initialized")
- return
- }
-
- for _, tag := range req.Tags {
- condition := map[string]interface{}{
- "tag_kwd": tag,
- "kb_id": datasetID,
- }
- newValue := map[string]interface{}{
- "remove": map[string]interface{}{
- "tag_kwd": tag,
- },
- }
- if err := docEngine.UpdateChunks(c.Request.Context(), condition, newValue, indexName, datasetID); err != nil {
- common.ResponseWithCodeData(c, common.CodeServerError, nil, "Failed to remove tag: "+err.Error())
- return
- }
- }
-
- common.SuccessWithData(c, true, "success")
-}
-
// CheckEmbedding Check embedding model compatibility by sampling random chunks,
// re-embedding them with the new model, and computing cosine similarity.
func (h *DatasetsHandler) CheckEmbedding(c *gin.Context) {
diff --git a/internal/handler/dataset_list_tags_test.go b/internal/handler/dataset_list_tags_test.go
deleted file mode 100644
index 371e6264d7..0000000000
--- a/internal/handler/dataset_list_tags_test.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package handler
-
-import (
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/gin-gonic/gin"
-
- "ragflow/internal/common"
-)
-
-func TestDatasetsHandlerListTagsRequiresAuth(t *testing.T) {
- gin.SetMode(gin.TestMode)
- h := &DatasetsHandler{}
- r := gin.New()
- r.GET("/api/v1/datasets/:dataset_id/tags", func(c *gin.Context) {
- h.ListTags(c)
- })
-
- resp := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodGet, "/api/v1/datasets/123e4567-e89b-12d3-a456-426614174000/tags", nil)
- r.ServeHTTP(resp, req)
-
- var body struct {
- Code int `json:"code"`
- Message string `json:"message"`
- }
- if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
- t.Fatalf("unmarshal response: %v body=%s", err, resp.Body.String())
- }
- if body.Code != int(common.CodeUnauthorized) {
- t.Fatalf("code=%d want=%d body=%s", body.Code, common.CodeUnauthorized, resp.Body.String())
- }
- if body.Message != "User not found" {
- t.Fatalf("message=%q want=%q", body.Message, "User not found")
- }
-}
diff --git a/internal/handler/dataset_rename_tag_test.go b/internal/handler/dataset_rename_tag_test.go
deleted file mode 100644
index d2dd17a323..0000000000
--- a/internal/handler/dataset_rename_tag_test.go
+++ /dev/null
@@ -1,126 +0,0 @@
-package handler
-
-import (
- "bytes"
- "encoding/json"
- "net/http"
- "net/http/httptest"
- "testing"
-
- "github.com/gin-gonic/gin"
-
- "ragflow/internal/common"
- "ragflow/internal/entity"
-)
-
-func TestDatasetsHandlerRenameTagRequiresAuth(t *testing.T) {
- gin.SetMode(gin.TestMode)
- h := &DatasetsHandler{}
- r := gin.New()
- r.PUT("/api/v1/datasets/:dataset_id/tags", func(c *gin.Context) {
- h.RenameTag(c)
- })
-
- resp := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodPut, "/api/v1/datasets/123e4567-e89b-12d3-a456-426614174000/tags", bytes.NewBufferString(`{"from_tag":"a","to_tag":"b"}`))
- req.Header.Set("Content-Type", "application/json")
- r.ServeHTTP(resp, req)
-
- var body struct {
- Code int `json:"code"`
- Message string `json:"message"`
- }
- if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
- t.Fatalf("unmarshal response: %v body=%s", err, resp.Body.String())
- }
- if body.Code != int(common.CodeUnauthorized) {
- t.Fatalf("code=%d want=%d body=%s", body.Code, common.CodeUnauthorized, resp.Body.String())
- }
- if body.Message != "User not found" {
- t.Fatalf("message=%q want=%q", body.Message, "User not found")
- }
-}
-
-func TestDatasetsHandlerRenameTagRejectsMissingFields(t *testing.T) {
- gin.SetMode(gin.TestMode)
- h := &DatasetsHandler{}
- r := gin.New()
- r.PUT("/api/v1/datasets/:dataset_id/tags", func(c *gin.Context) {
- c.Set("user", &entity.User{ID: "user-1"})
- h.RenameTag(c)
- })
-
- resp := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodPut, "/api/v1/datasets/123e4567-e89b-12d3-a456-426614174000/tags", bytes.NewBufferString(`{"from_tag":"a"}`))
- req.Header.Set("Content-Type", "application/json")
- r.ServeHTTP(resp, req)
-
- var body struct {
- Code int `json:"code"`
- Message string `json:"message"`
- }
- if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
- t.Fatalf("unmarshal response: %v body=%s", err, resp.Body.String())
- }
- if body.Code != int(common.CodeDataError) {
- t.Fatalf("code=%d want=%d body=%s", body.Code, common.CodeDataError, resp.Body.String())
- }
-}
-
-func TestDatasetsHandlerRenameTagRejectsEmptyFields(t *testing.T) {
- gin.SetMode(gin.TestMode)
- h := &DatasetsHandler{}
- r := gin.New()
- r.PUT("/api/v1/datasets/:dataset_id/tags", func(c *gin.Context) {
- c.Set("user", &entity.User{ID: "user-1"})
- h.RenameTag(c)
- })
-
- resp := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodPut, "/api/v1/datasets/123e4567-e89b-12d3-a456-426614174000/tags", bytes.NewBufferString(`{"from_tag":" ","to_tag":"x"}`))
- req.Header.Set("Content-Type", "application/json")
- r.ServeHTTP(resp, req)
-
- var body struct {
- Code int `json:"code"`
- Message string `json:"message"`
- }
- if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
- t.Fatalf("unmarshal response: %v body=%s", err, resp.Body.String())
- }
- if body.Code != int(common.CodeArgumentError) {
- t.Fatalf("code=%d want=%d body=%s", body.Code, common.CodeArgumentError, resp.Body.String())
- }
- if body.Message != "from_tag and to_tag must not be empty" {
- t.Fatalf("message=%q want=%q", body.Message, "from_tag and to_tag must not be empty")
- }
-}
-
-func TestDatasetsHandlerRenameTagRejectsNonStringFields(t *testing.T) {
- gin.SetMode(gin.TestMode)
- h := &DatasetsHandler{}
- r := gin.New()
- r.PUT("/api/v1/datasets/:dataset_id/tags", func(c *gin.Context) {
- c.Set("user", &entity.User{ID: "user-1"})
- h.RenameTag(c)
- })
-
- resp := httptest.NewRecorder()
- req := httptest.NewRequest(http.MethodPut, "/api/v1/datasets/123e4567-e89b-12d3-a456-426614174000/tags", bytes.NewBufferString(`{"from_tag":1,"to_tag":"x"}`))
- req.Header.Set("Content-Type", "application/json")
- r.ServeHTTP(resp, req)
-
- var body struct {
- Code int `json:"code"`
- Message string `json:"message"`
- }
- if err := json.Unmarshal(resp.Body.Bytes(), &body); err != nil {
- t.Fatalf("unmarshal response: %v body=%s", err, resp.Body.String())
- }
- if body.Code != int(common.CodeArgumentError) {
- t.Fatalf("code=%d want=%d body=%s", body.Code, common.CodeArgumentError, resp.Body.String())
- }
- if body.Message != "from_tag and to_tag must be strings" {
- t.Fatalf("message=%q want=%q", body.Message, "from_tag and to_tag must be strings")
- }
-}
diff --git a/internal/ingestion/component/chunker/token_hardcap_test.go b/internal/ingestion/component/chunker/token_hardcap_test.go
index ad01cf31fa..30361c327d 100644
--- a/internal/ingestion/component/chunker/token_hardcap_test.go
+++ b/internal/ingestion/component/chunker/token_hardcap_test.go
@@ -270,7 +270,6 @@ func TestMergeUnits_ExpandedPiecesCarryMetadata(t *testing.T) {
Layout: "text",
Image: "raw-image",
PageNumber: intPtr(3),
- TagKwd: []string{"t1"},
ChunkOrderInt: intPtr(7),
}
got := mergeUnits([]schema.ChunkDoc{unit}, target, 0, "\n")
@@ -284,9 +283,6 @@ func TestMergeUnits_ExpandedPiecesCarryMetadata(t *testing.T) {
if ck.PageNumber == nil || *ck.PageNumber != 3 {
t.Errorf("sub-piece %d lost PageNumber: %#v", i, ck.PageNumber)
}
- if len(ck.TagKwd) != 1 || ck.TagKwd[0] != "t1" {
- t.Errorf("sub-piece %d lost TagKwd: %#v", i, ck.TagKwd)
- }
if ck.ChunkOrderInt == nil || *ck.ChunkOrderInt != 7 {
t.Errorf("sub-piece %d lost ChunkOrderInt: %#v", i, ck.ChunkOrderInt)
}
diff --git a/internal/ingestion/component/extractor.go b/internal/ingestion/component/extractor.go
index 60a55ffc5e..64602a7016 100644
--- a/internal/ingestion/component/extractor.go
+++ b/internal/ingestion/component/extractor.go
@@ -304,7 +304,7 @@ func (c *ExtractorComponent) Inputs() map[string]string {
//
// chunks []map[string]any — input chunks, each augmented with
// extracted modular fields (important_kwd,
-// question_kwd, tag_kwd, summary, metadata).
+// question_kwd, tag_feas, summary, metadata).
// output_format string — always "chunks". Parity with
// python set_output contract.
// _ERROR string — populated on a short-circuit
@@ -312,7 +312,7 @@ func (c *ExtractorComponent) Inputs() map[string]string {
// set_output("_ERROR", ...)).
func (c *ExtractorComponent) Outputs() map[string]string {
return map[string]string{
- "chunks": "Extraction results — input chunks, each enriched with modular extraction fields (important_kwd, question_kwd, tag_kwd, summary, metadata).",
+ "chunks": "Extraction results — input chunks, each enriched with modular extraction fields (important_kwd, question_kwd, tag_feas, summary, metadata).",
"output_format": "Always \"chunks\". Parity marker for downstream consumers.",
"_ERROR": "Optional short-circuit error message (reserved for the future TOC branch and other error paths).",
}
diff --git a/internal/ingestion/component/extractor_tag.go b/internal/ingestion/component/extractor_tag.go
index 7480177e8d..71d663517d 100644
--- a/internal/ingestion/component/extractor_tag.go
+++ b/internal/ingestion/component/extractor_tag.go
@@ -1,13 +1,10 @@
package component
import (
- "bufio"
"bytes"
"context"
- "encoding/csv"
"encoding/json"
"fmt"
- "io"
"math"
"math/rand/v2"
"path/filepath"
@@ -20,14 +17,11 @@ import (
"github.com/cespare/xxhash/v2"
eschema "github.com/cloudwego/eino/schema"
- "github.com/xuri/excelize/v2"
"go.uber.org/zap"
"gorm.io/gorm"
"ragflow/internal/agent/runtime"
"ragflow/internal/common"
- "ragflow/internal/dao"
- "ragflow/internal/entity"
"ragflow/internal/ingestion/chunkcache"
"ragflow/internal/ingestion/component/globals"
"ragflow/internal/ingestion/component/schema"
@@ -47,9 +41,6 @@ const (
// defaultTopK is the maximum number of matched example candidates to aggregate in Phase 1.
defaultTopK = 5
- // bgSmoothing is the Dirichlet smoothing constant for background prior tag probabilities.
- bgSmoothing = 10.0
-
// rankDecayTierDropRelativeThreshold is the relative drop threshold to descend an effective rank tier.
rankDecayTierDropRelativeThreshold = 0.05
@@ -106,128 +97,6 @@ Output:
`
-// MemoryTagIndex is an in-memory inverted index of tag examples (immutable after construction, safe for concurrent use).
-type MemoryTagIndex struct {
- examples []schema.TagLabel
- postings map[string][]int // word -> doc_ids (compact slice without per-doc map overhead)
- idfs map[string]float64 // word -> idf
- exTotalIDF []float64 // doc_id -> sum(IDF(w))
- exTokenCount []int // doc_id -> number of unique tokens
- allTags map[string]float64 // tag -> background prob (S=10)
-}
-
-func buildMemoryTagIndex(rawExamples []schema.TagLabel, tok tokenizer.Tokenizer) *MemoryTagIndex {
- if len(rawExamples) == 0 {
- return nil
- }
-
- cleanExamples := make([]schema.TagLabel, 0, len(rawExamples))
- exWordSets := make([]map[string]struct{}, 0, len(rawExamples))
- allTagCounts := make(map[string]int)
- totalTagCount := 0
-
- // 1. Filter empty contents, deduplicate tags per sample, and normalize dots with deep copies.
- for _, ex := range rawExamples {
- content := strings.TrimSpace(ex.Content)
- if content == "" {
- continue // Skip empty content.
- }
- tks, err := tok.Tokenize(content)
- if err != nil {
- common.Warn(fmt.Sprintf("extractor tags: tokenize example failed: %v", err))
- continue
- }
- fields := strings.Fields(tks)
- if len(fields) == 0 {
- continue // Skip samples with no tokens.
- }
- wordSet := make(map[string]struct{}, len(fields))
- for _, w := range fields {
- if w = strings.TrimSpace(w); w != "" {
- wordSet[w] = struct{}{}
- }
- }
- if len(wordSet) == 0 {
- continue
- }
-
- tagSet := make(map[string]struct{}, len(ex.Tags))
- cleanTags := make([]string, 0, len(ex.Tags))
- for _, t := range ex.Tags {
- t = strings.TrimSpace(strings.ReplaceAll(t, ".", "_"))
- if t != "" {
- if _, exists := tagSet[t]; !exists {
- tagSet[t] = struct{}{}
- cleanTags = append(cleanTags, t)
- }
- }
- }
- if len(cleanTags) == 0 {
- continue // Skip examples with no usable tags.
- }
- for _, t := range cleanTags {
- allTagCounts[t]++
- totalTagCount++
- }
-
- cleanExamples = append(cleanExamples, schema.TagLabel{
- Content: content,
- Tags: cleanTags,
- })
- exWordSets = append(exWordSets, wordSet)
- }
-
- N := float64(len(cleanExamples))
- if N == 0 || totalTagCount == 0 {
- return nil // Guard against all samples having empty tags.
- }
-
- docFreq := make(map[string]int)
- postings := make(map[string][]int)
-
- for i, wordSet := range exWordSets {
- // Invariant: each docID is added to postings[w] at most once.
- for w := range wordSet {
- postings[w] = append(postings[w], i)
- docFreq[w]++ // Each document contributes at most 1 to document frequency.
- }
- }
-
- // 2. Standard smoothed IDF (terms covering all documents smoothly approach 0).
- idfs := make(map[string]float64, len(docFreq))
- for w, df := range docFreq {
- idfs[w] = math.Log(1.0 + (N-float64(df)+0.5)/(float64(df)+0.5))
- }
-
- // 3. Precompute total IDF and token count per valid example (short-text TF=1, avoiding per-example TF maps).
- exTotalIDF := make([]float64, len(cleanExamples))
- exTokenCount := make([]int, len(cleanExamples))
- for i, wordSet := range exWordSets {
- var sum float64
- for w := range wordSet {
- sum += idfs[w]
- }
- exTotalIDF[i] = sum
- exTokenCount[i] = len(wordSet)
- }
-
- // 4. Background prior probability distribution (smoothed Dirichlet prior).
- alpha := bgSmoothing / float64(len(allTagCounts))
- bgProportions := make(map[string]float64, len(allTagCounts))
- for t, count := range allTagCounts {
- bgProportions[t] = (float64(count) + alpha) / (float64(totalTagCount) + bgSmoothing)
- }
-
- return &MemoryTagIndex{
- examples: cleanExamples,
- postings: postings,
- idfs: idfs,
- exTotalIDF: exTotalIDF,
- exTokenCount: exTokenCount,
- allTags: bgProportions,
- }
-}
-
// OrderedTagWeights represents a tag-to-weight mapping that preserves
// score-descending order when marshaled to JSON for Elasticsearch storage.
type OrderedTagWeights map[string]int
@@ -477,7 +346,6 @@ func matchAndTagChunk(
}
chunk[common.TAG_FLD] = tagWeights
- chunk["tag_kwd"] = matchedTags
return &schema.TaggedChunk{
Content: text,
@@ -486,65 +354,6 @@ func matchAndTagChunk(
}
}
-// ----------------------------------------------------------------------
-// Cache & scheduling pipeline with language passthrough and few-shot fallback.
-// ----------------------------------------------------------------------
-
-const tagSourceCacheMax = 128
-
-type boundedTagCache struct {
- mu sync.Mutex
- cap int
- items map[string]*MemoryTagIndex
- recent []string
-}
-
-func newBoundedTagCache(cap int) *boundedTagCache {
- return &boundedTagCache{
- cap: cap,
- items: make(map[string]*MemoryTagIndex, cap),
- }
-}
-
-func (c *boundedTagCache) load(key string) (*MemoryTagIndex, bool) {
- c.mu.Lock()
- defer c.mu.Unlock()
- v, ok := c.items[key]
- if !ok {
- return nil, false
- }
- c.markRecentLocked(key)
- return v, true
-}
-
-func (c *boundedTagCache) store(key string, val *MemoryTagIndex) *MemoryTagIndex {
- c.mu.Lock()
- defer c.mu.Unlock()
- if existing, ok := c.items[key]; ok {
- return existing
- }
- c.items[key] = val
- c.recent = append(c.recent, key)
- for len(c.items) > c.cap {
- oldest := c.recent[0]
- c.recent = c.recent[1:]
- delete(c.items, oldest)
- }
- return val
-}
-
-func (c *boundedTagCache) markRecentLocked(key string) {
- for i, k := range c.recent {
- if k == key {
- c.recent = append(c.recent[:i], c.recent[i+1:]...)
- c.recent = append(c.recent, k)
- break
- }
- }
-}
-
-var tagSourceFileIndexCache = newBoundedTagCache(tagSourceCacheMax)
-
func isHighConfidenceMatch(matched *schema.TaggedChunk) bool {
if matched == nil {
return false
@@ -656,376 +465,36 @@ func (c *ExtractorComponent) loadTagFileIndexed(ctx context.Context, lang string
// user-controlled through parser_config, so it must resolve inside the
// caller's tenant before the bytes are read.
tenantID := globals.GlobalOrInput(ctx, nil, "tenant_id", "")
- f, err := dao.NewFileDAO().GetByIDAndTenant(ctx, dao.DB, c.Param.Tags.TagFileID, tenantID)
- if err != nil || f == nil || f.Location == nil || *f.Location == "" {
+ f, err := resolveTagSourceFile(ctx, c.Param.Tags.TagFileID, tenantID)
+ if err != nil {
common.Warn(fmt.Sprintf("extractor tags: resolve tag_file_id %q: %v", c.Param.Tags.TagFileID, err))
return nil, false
}
- cacheKey := tagSourceFileCacheKey(f, lang)
- if cached, ok := tagSourceFileIndexCache.load(cacheKey); ok {
+ indexed, reused, err := loadOrBuildTagFileIndex(ctx, f, tenantID, lang)
+ if err != nil {
+ common.Warn(fmt.Sprintf("extractor tags: load tag source %q: %v", c.Param.Tags.TagFileID, err))
+ return nil, false
+ }
+ if indexed == nil {
+ return nil, false
+ }
+ if reused {
common.Info("extractor tags: reused tag source file index",
zap.String("file_id", c.Param.Tags.TagFileID),
zap.String("bucket", f.ParentID),
zap.String("key", *f.Location),
)
- return cached, true
+ return indexed, true
}
- stg := resolveStorage()
- if stg == nil {
- common.Warn("extractor tags: no storage backend registered")
- return nil, false
- }
- data, err := stg.Get(ctx, f.ParentID, *f.Location, tenantID)
- if err != nil {
- common.Warn(fmt.Sprintf("extractor tags: load tag source %q/%q: %v", f.ParentID, *f.Location, err))
- return nil, false
- }
- indexed, ok := buildIndexedTagSourceFromBytes(data, f.Name, lang)
- if !ok || indexed == nil {
- return nil, false // Guard against caching nil index in LRU.
- }
- indexed = tagSourceFileIndexCache.store(cacheKey, indexed)
common.Info("extractor tags: loaded tag source file",
zap.String("file_id", c.Param.Tags.TagFileID),
zap.String("bucket", f.ParentID),
zap.String("key", *f.Location),
zap.Int64("size", f.Size),
- zap.Int("bytes", len(data)),
)
return indexed, true
}
-func buildIndexedTagSourceFromBytes(data []byte, filename, lang string) (*MemoryTagIndex, bool) {
- rawExamples, err := parseTagSourceByFilename(data, filename)
- if err != nil || len(rawExamples) == 0 {
- if err != nil {
- common.Warn(fmt.Sprintf("extractor tags: %v", err))
- }
- return nil, false
- }
- tok := tokenizer.New(lang)
- indexed := buildMemoryTagIndex(rawExamples, tok)
- if indexed == nil {
- return nil, false
- }
- return indexed, true
-}
-
-func tagSourceFileCacheKey(f *entity.File, lang string) string {
- location := ""
- if f.Location != nil {
- location = *f.Location
- }
- updateTime := int64(0)
- if f.UpdateTime != nil {
- updateTime = *f.UpdateTime
- }
- return fmt.Sprintf("tag-file:%s:%s:%s:%d:%d:%s", f.ID, f.ParentID, location, f.Size, updateTime, lang)
-}
-
-// parseTagSourceByFilename mirrors rag/app/tag.py chunk(): the format is chosen
-// by the file extension, and only .xlsx/.xls, .txt and .csv are supported. Any
-// other extension (including no extension) is rejected, matching Python's
-// NotImplementedError for unsupported formats. xlsx is parsed per-sheet (2
-// columns, no header, multiple sheets); .csv uses a quote-aware reader; .txt
-// uses the delimiter-detecting reader.
-func parseTagSourceByFilename(data []byte, filename string) ([]schema.TagLabel, error) {
- switch strings.ToLower(filepath.Ext(filename)) {
- case ".xlsx", ".xls":
- return parseXLSXTagSource(data), nil
- case ".csv":
- return parseCSVQuoteAwareReader(bytes.NewReader(data)), nil
- case ".txt":
- delimiter := detectCSVDelimiterBytes(data)
- return parseCSVTagSourceReader(bytes.NewReader(data), delimiter), nil
- default:
- return nil, fmt.Errorf("unsupported tag source extension %q: only .xlsx, .txt and .csv are supported", filepath.Ext(filename))
- }
-}
-
-// TagVocabularyFromBytes is the storage/DAO-free core of
-// TagVocabularyFromTagFileID. It parses a tag source file's raw bytes (mirroring
-// rag/app/tag.py's chunk format) and returns the vocabulary as tag -> number of
-// source examples that mention the tag; a tag repeated within one source example
-// counts once, matching buildMemoryTagIndex's per-sample deduplication. Note: the
-// Go tag extractor
-// (matchAndTagChunk) DOES write tag_kwd onto chunks at parse time, but this
-// vocabulary is the authoritative selectable-tag list for the Go backend (the
-// tag-options/aggregation API sources the list from the tag source file, not
-// from chunk usage).
-func TagVocabularyFromBytes(data []byte, filename string) (map[string]int, error) {
- labels, err := parseTagSourceByFilename(data, filename)
- if err != nil {
- return nil, err
- }
- counts := make(map[string]int)
- for _, lbl := range labels {
- seen := make(map[string]struct{}, len(lbl.Tags))
- for _, t := range lbl.Tags {
- t = strings.TrimSpace(strings.ReplaceAll(t, ".", "_"))
- if t != "" {
- if _, exists := seen[t]; exists {
- continue
- }
- seen[t] = struct{}{}
- counts[t]++
- }
- }
- }
- return counts, nil
-}
-
-// TagVocabularyFromTagFileID loads a tag source file (parser_config.tags.tag_file_id)
-// and returns the tag vocabulary it defines. It is the Go-native source of the
-// selectable-tag list surfaced by the tag-options API. Although the Go tag
-// extractor (matchAndTagChunk) writes tag_kwd onto chunks during parsing, the
-// selectable-tag list is taken from this vocabulary (the tag source file), not
-// from chunk usage.
-//
-// It returns (nil, nil) when tagFileID is empty.
-//
-// ownerTenantID is the tenant of the dataset that configured the file and is
-// required: tag_file_id is user-writable through parser_config, so the file must
-// be proven to belong to that tenant before its bytes are read (IDOR, CWE-639).
-// An empty ownerTenantID fails closed. Note that storage.Get's tenant argument
-// does not establish file ownership by itself.
-func TagVocabularyFromTagFileID(ctx context.Context, tagFileID, ownerTenantID string) (map[string]int, error) {
- if tagFileID == "" {
- return nil, nil
- }
- common.Info(fmt.Sprintf("tag_vocab: loading tag source file_id=%q", tagFileID))
- f, err := dao.NewFileDAO().GetByIDAndTenant(ctx, dao.DB, tagFileID, ownerTenantID)
- if err != nil || f == nil || f.Location == nil || *f.Location == "" {
- return nil, fmt.Errorf("tag source file %q not found: %w", tagFileID, err)
- }
- common.Info(fmt.Sprintf("tag_vocab: file_id=%q name=%q parent_id=%q location=%q",
- tagFileID, f.Name, f.ParentID, *f.Location))
- stg := resolveStorage()
- if stg == nil {
- return nil, fmt.Errorf("tag source file %q: no storage backend registered", tagFileID)
- }
- data, err := stg.Get(ctx, f.ParentID, *f.Location, ownerTenantID)
- if err != nil {
- return nil, fmt.Errorf("load tag source file %q/%q: %w", f.ParentID, *f.Location, err)
- }
- common.Info(fmt.Sprintf("tag_vocab: file_id=%q loaded %d bytes", tagFileID, len(data)))
- return TagVocabularyFromBytes(data, f.Name)
-}
-
-func parseCSVTagSource(text string) []schema.TagLabel {
- return parseCSVTagSourceBytes([]byte(text))
-}
-
-func parseCSVTagSourceBytes(data []byte) []schema.TagLabel {
- return parseCSVTagSourceReader(bytes.NewReader(data), detectCSVDelimiterBytes(data))
-}
-
-// parseCSVTagSourceReader mirrors rag/app/tag.py's txt parsing: lines that do
-// not split into exactly two columns are accumulated as body text and prepended
-// to the next tagged line. The second column holds comma-separated tags.
-func parseCSVTagSourceReader(r io.Reader, delimiter string) []schema.TagLabel {
- scanner := newTagSourceScannerFromReader(r, scanBufferMax)
- result := make([]schema.TagLabel, 0)
- content := ""
- appendLine := func(s string) {
- if content == "" {
- content = s
- } else {
- content += "\n" + s
- }
- }
- for scanner.Scan() {
- line := scanner.Text()
- arr := strings.Split(line, delimiter)
- if len(arr) != 2 {
- appendLine(line)
- continue
- }
- appendLine(arr[0])
- tags := splitAndTrim(arr[1], ",")
- result = append(result, schema.TagLabel{Content: content, Tags: tags})
- content = ""
- }
- if scanner.Err() != nil {
- common.Warn(fmt.Sprintf("extractor tags: parse tag source: %v", scanner.Err()))
- }
- return result
-}
-
-// parseCSVQuoteAwareReader mirrors rag/app/tag.py's .csv path: each line is
-// parsed with encoding/csv (so quoted fields containing the delimiter are
-// handled), lines that do not yield exactly two non-empty columns are
-// accumulated as body text and prepended to the next tagged line, and the
-// second column holds comma-separated tags.
-func parseCSVQuoteAwareReader(r io.Reader) []schema.TagLabel {
- scanner := newTagSourceScannerFromReader(r, scanBufferMax)
- result := make([]schema.TagLabel, 0)
- content := ""
- appendLine := func(s string) {
- if content == "" {
- content = s
- } else {
- content += "\n" + s
- }
- }
- for scanner.Scan() {
- line := scanner.Text()
- rec, err := csv.NewReader(strings.NewReader(line)).Read()
- if err != nil {
- appendLine(line)
- continue
- }
- row := stripEmptyFields(rec)
- if len(row) != 2 {
- appendLine(line)
- continue
- }
- appendLine(row[0])
- tags := splitAndTrim(row[1], ",")
- result = append(result, schema.TagLabel{Content: content, Tags: tags})
- content = ""
- }
- if scanner.Err() != nil {
- common.Warn(fmt.Sprintf("extractor tags: parse csv tag source: %v", scanner.Err()))
- }
- return result
-}
-
-// parseXLSXTagSource mirrors rag/app/tag.py's .xlsx path: every sheet is read
-// with no header, and each row contributes a (content, tags) pair from its
-// first and second non-empty cells. Single-cell rows are accumulated as body text
-// and prepended to the next tagged row, matching CSV parsing behavior.
-// The second cell holds comma-separated tags.
-func parseXLSXTagSource(data []byte) []schema.TagLabel {
- f, err := excelize.OpenReader(bytes.NewReader(data))
- if err != nil {
- common.Warn(fmt.Sprintf("extractor tags: open xlsx tag source: %v", err))
- return nil
- }
- defer f.Close()
-
- result := make([]schema.TagLabel, 0)
- for _, sheet := range f.GetSheetList() {
- rows, err := f.GetRows(sheet)
- if err != nil {
- common.Warn(fmt.Sprintf("extractor tags: read xlsx sheet %q: %v", sheet, err))
- continue
- }
- content := ""
- appendLine := func(s string) {
- if content == "" {
- content = s
- } else {
- content += "\n" + s
- }
- }
- for _, row := range rows {
- var cells []string
- for _, c := range row {
- if c = strings.TrimSpace(c); c != "" {
- cells = append(cells, c)
- }
- }
- if len(cells) == 0 {
- continue
- }
- if len(cells) == 1 {
- appendLine(cells[0])
- continue
- }
- appendLine(cells[0])
- tags := splitAndTrim(cells[1], ",")
- result = append(result, schema.TagLabel{Content: content, Tags: tags})
- content = ""
- }
- }
- return result
-}
-
-func stripEmptyFields(fields []string) []string {
- out := make([]string, 0, len(fields))
- for _, f := range fields {
- if f = strings.TrimSpace(f); f != "" {
- out = append(out, f)
- }
- }
- return out
-}
-
-const scanBufferMax = 1 << 20
-
-func detectCSVDelimiterBytes(data []byte) string {
- comma, tab := 0, 0
- scanner := newTagSourceScanner(bytes.NewReader(data), len(data))
- for scanner.Scan() {
- line := scanner.Text()
- if strings.TrimSpace(line) == "" {
- continue
- }
- // Try quote-aware parse for comma
- rComma := csv.NewReader(strings.NewReader(line))
- rComma.Comma = ','
- if rec, err := rComma.Read(); err == nil {
- if len(rec) == 2 {
- comma++
- }
- } else if len(strings.Split(line, ",")) == 2 {
- comma++
- }
-
- // Try quote-aware parse for tab
- rTab := csv.NewReader(strings.NewReader(line))
- rTab.Comma = '\t'
- if rec, err := rTab.Read(); err == nil {
- if len(rec) == 2 {
- tab++
- }
- } else if len(strings.Split(line, "\t")) == 2 {
- tab++
- }
- }
- if scanner.Err() != nil {
- common.Warn(fmt.Sprintf("extractor tags: delimiter scan: %v", scanner.Err()))
- }
- if tab > 0 && tab >= comma {
- return "\t"
- }
- return ","
-}
-
-func newTagSourceScanner(r io.Reader, dataLen int) *bufio.Scanner {
- maxToken := dataLen + 1
- if maxToken < 64*1024 {
- maxToken = 64 * 1024
- }
- if maxToken > scanBufferMax {
- maxToken = scanBufferMax
- }
- return newTagSourceScannerFromReader(r, maxToken)
-}
-
-func newTagSourceScannerFromReader(r io.Reader, maxTokens ...int) *bufio.Scanner {
- maxToken := 64 * 1024
- if len(maxTokens) > 0 && maxTokens[0] > maxToken {
- maxToken = maxTokens[0]
- }
- initBuf := min(64*1024, maxToken)
- scanner := bufio.NewScanner(r)
- scanner.Buffer(make([]byte, 0, initBuf), maxToken)
- return scanner
-}
-
-func splitAndTrim(s, sep string) []string {
- parts := strings.Split(s, sep)
- out := make([]string, 0, len(parts))
- for _, p := range parts {
- if p = strings.TrimSpace(p); p != "" {
- out = append(out, p)
- }
- }
- return out
-}
-
func isAlphaExt(ext string) bool {
if len(ext) < 2 || ext[0] != '.' {
return false
@@ -1162,20 +631,11 @@ func detectTextLanguage(chunks []map[string]any) string {
return "English"
}
-func containsCJK(s string) bool {
- for _, r := range s {
- if (r >= 0x4e00 && r <= 0x9fff) || (r >= 0x3400 && r <= 0x4dbf) {
- return true
- }
- }
- return false
-}
-
+// roundInt mirrors Python's round() on a float, which is round-half-to-even
+// (banker's rounding): round(2.5) == 2 and round(3.5) == 4. The previous
+// int(f+0.5) form rounded halves away from zero and returned 3 for 2.5.
func roundInt(f float64) int {
- if f < 0 {
- return int(f - 0.5)
- }
- return int(f + 0.5)
+ return int(math.RoundToEven(f))
}
// ----------------------------------------------------------------------
@@ -1233,7 +693,6 @@ func llmTagChunk(
if cached := getTaggerLLMCache(ctx, cache, modelID, chunkID, text, allTags, picked, topN); cached != nil {
chunk[common.TAG_FLD] = cached
- chunk["tag_kwd"] = sortedTagWeightsKeys(cached)
return
}
@@ -1281,7 +740,6 @@ func llmTagChunk(
if len(result) > 0 {
chunk[common.TAG_FLD] = result
- chunk["tag_kwd"] = sortedTagWeightsKeys(result)
setTaggerLLMCache(ctx, cache, modelID, chunkID, text, allTags, picked, topN, result)
}
}
@@ -1416,31 +874,6 @@ func sortedTagNames(allTags map[string]float64) []string {
return out
}
-func sortedTagWeightsKeys(m map[string]int) []string {
- if len(m) == 0 {
- return nil
- }
- type kv struct {
- k string
- v int
- }
- kvs := make([]kv, 0, len(m))
- for k, v := range m {
- kvs = append(kvs, kv{k, v})
- }
- sort.Slice(kvs, func(i, j int) bool {
- if kvs[i].v != kvs[j].v {
- return kvs[i].v > kvs[j].v
- }
- return kvs[i].k < kvs[j].k
- })
- keys := make([]string, len(kvs))
- for i, item := range kvs {
- keys[i] = item.k
- }
- return keys
-}
-
func sampleWithoutReplacement(slice []schema.TaggedChunk, k int, seed int64) []schema.TaggedChunk {
if len(slice) == 0 || k <= 0 {
return nil
diff --git a/internal/ingestion/component/extractor_tag_integration_test.go b/internal/ingestion/component/extractor_tag_integration_test.go
index ccbec906be..23a1c31257 100644
--- a/internal/ingestion/component/extractor_tag_integration_test.go
+++ b/internal/ingestion/component/extractor_tag_integration_test.go
@@ -214,8 +214,8 @@ func TestMatchAndTagChunk_TitleFallback(t *testing.T) {
if matched.TagWeights["BiddingDoc"] <= 0 || matched.TagWeights["Engineering"] <= 0 {
t.Fatalf("expected BiddingDoc and Engineering tags matched, got: %v", matched.TagWeights)
}
- if chunk["tag_kwd"] == nil {
- t.Fatal("expected tag_kwd to be populated on chunk")
+ if _, ok := chunk["tag_kwd"]; ok {
+ t.Fatal("tag_kwd must not be written onto the tagged chunk")
}
}
diff --git a/internal/ingestion/component/extractor_tag_test.go b/internal/ingestion/component/extractor_tag_test.go
index 1b258493c5..bd6e37ee7b 100644
--- a/internal/ingestion/component/extractor_tag_test.go
+++ b/internal/ingestion/component/extractor_tag_test.go
@@ -7,6 +7,7 @@ import (
"fmt"
"strings"
"testing"
+ "time"
"github.com/xuri/excelize/v2"
@@ -467,7 +468,7 @@ func TestLlmtagChunk_ColdStartFallback(t *testing.T) {
func TestParseCSVQuoteAwareReader(t *testing.T) {
text := "\"RAGFlow, the guide\",RAG\nplain line,LLM"
- result := parseCSVQuoteAwareReader(strings.NewReader(text))
+ result := parseCSVQuoteAwareReader(strings.NewReader(text), ',')
if len(result) != 2 {
t.Fatalf("expected 2 examples, got %d", len(result))
}
@@ -485,6 +486,54 @@ func TestParseCSVQuoteAwareReader(t *testing.T) {
}
}
+// A quoted field may span physical lines; Python's single csv.reader keeps it
+// in one record (infiniflow/ragflow#16881 fixes the same for qa.csv).
+func TestParseCSVQuoteAwareReaderMultilineField(t *testing.T) {
+ text := "\"who is\nRAGFlow?\",RAG\nplain line,LLM"
+ result := parseCSVQuoteAwareReader(strings.NewReader(text), ',')
+ if len(result) != 2 {
+ t.Fatalf("expected 2 examples, got %d (%+v)", len(result), result)
+ }
+ if result[0].Content != "who is\nRAGFlow?" {
+ t.Errorf("content[0] = %q", result[0].Content)
+ }
+ if len(result[0].Tags) != 1 || result[0].Tags[0] != "RAG" {
+ t.Errorf("tags[0] = %v", result[0].Tags)
+ }
+ if result[1].Content != "plain line" {
+ t.Errorf("content[1] = %q", result[1].Content)
+ }
+}
+
+// When a multi-line record is not a (content, tags) pair, the raw span - quotes
+// and embedded newline included - becomes body text, like Python's raw join.
+func TestParseCSVQuoteAwareReaderMultilineBody(t *testing.T) {
+ text := "\"body start\nbody end\"\nquestion,RAG"
+ result := parseCSVQuoteAwareReader(strings.NewReader(text), ',')
+ if len(result) != 1 {
+ t.Fatalf("expected 1 example, got %d (%+v)", len(result), result)
+ }
+ if result[0].Content != "\"body start\nbody end\"\nquestion" {
+ t.Errorf("content[0] = %q", result[0].Content)
+ }
+ if len(result[0].Tags) != 1 || result[0].Tags[0] != "RAG" {
+ t.Errorf("tags[0] = %v", result[0].Tags)
+ }
+}
+
+// Blank lines are not reported by encoding/csv, but Python feeds them to the
+// reader as empty records; they must still separate accumulated body text.
+func TestParseCSVQuoteAwareReaderBlankLine(t *testing.T) {
+ text := "first,RAG\n\nsecond,LLM"
+ result := parseCSVQuoteAwareReader(strings.NewReader(text), ',')
+ if len(result) != 2 {
+ t.Fatalf("expected 2 examples, got %d (%+v)", len(result), result)
+ }
+ if result[0].Content != "first" || result[1].Content != "second" {
+ t.Errorf("contents = %q, %q", result[0].Content, result[1].Content)
+ }
+}
+
func TestParseXLSXTagSource(t *testing.T) {
data := stubXLSXBytes(t)
result := parseXLSXTagSource(data)
@@ -545,6 +594,25 @@ func TestParseTagSourceByFilename(t *testing.T) {
}
}
+// rag/app/tag.py's .csv path switches to TAB as soon as the file contains one,
+// while the tags column stays comma-separated.
+func TestParseTagSourceByFilename_TabSeparatedCSV(t *testing.T) {
+ data := []byte("Document Title\tTag1,Tag2\nAnother Document\tTag3\n")
+ got, err := parseTagSourceByFilename(data, "tags.csv")
+ if err != nil {
+ t.Fatalf("csv: unexpected error: %v", err)
+ }
+ if len(got) != 2 {
+ t.Fatalf("csv: expected 2 examples, got %d (%+v)", len(got), got)
+ }
+ if got[0].Content != "Document Title" || len(got[0].Tags) != 2 || got[0].Tags[0] != "Tag1" || got[0].Tags[1] != "Tag2" {
+ t.Errorf("csv[0] = %+v", got[0])
+ }
+ if got[1].Content != "Another Document" || len(got[1].Tags) != 1 || got[1].Tags[0] != "Tag3" {
+ t.Errorf("csv[1] = %+v", got[1])
+ }
+}
+
func TestParseTaggerResponse_DotSanitization(t *testing.T) {
raw := `{"model.v1.0": 8, "rag_tech": 6, "rag.db.v2": 4}`
result := parseTaggerResponse(raw, 5)
@@ -791,93 +859,24 @@ func TestOrderedTagWeights_MarshalJSON(t *testing.T) {
}
}
-func TestContainsCJK(t *testing.T) {
- tests := []struct {
- input string
- want bool
- }{
- {"Hello world", false},
- {"Hello 世界", true},
- {"这是一段中文", true},
- {"12345!@#$", false},
- {"\u3400\u3401", true}, // CJK Extension A
- }
- for _, tt := range tests {
- if got := containsCJK(tt.input); got != tt.want {
- t.Errorf("containsCJK(%q) = %v, want %v", tt.input, got, tt.want)
- }
- }
-}
-
-func TestContainsCJK_LanguageAutoDetection(t *testing.T) {
- tests := []struct {
- name string
- input string
- want bool
- }{
- {"pure english text", "This is pure English text without any Asian characters.", false},
- {"pure ascii numbers and symbols", "1234567890 !@#$%^&*()_+=-~`[]{}\\|;':\",.<>/?", false},
- {"simplified chinese characters", "这是简体中文字符串", true},
- {"traditional chinese characters", "這是繁體中文詞彙", true},
- {"mixed english and chinese", "RAGFlow 智能知识库问答系统 version 2.0", true},
- {"single CJK character boundary low", "\u4e00", true}, // U+4E00: '一'
- {"single CJK character boundary high", "\u9fa5", true}, // U+9FA5
- {"CJK Extension A boundary low", "\u3400", true}, // U+3400
- {"CJK Extension A boundary high", "\u4dbf", true}, // U+4DBF
- {"non-CJK unicode characters (latin accents)", "Café, résumé, naïve, señor", false},
- {"greek unicode characters", "αβγδε", false},
- {"cyrillic unicode characters", "Привет мир", false},
- {"empty string", "", false},
- {"whitespace only", " \t\r\n ", false},
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- got := containsCJK(tt.input)
- if got != tt.want {
- t.Errorf("containsCJK(%q) = %v, want %v", tt.input, got, tt.want)
- }
- })
- }
-}
-
-func TestPopulateTagKwd_LLMTagChunk(t *testing.T) {
+func TestLLMTagChunkWritesOnlyTagFeas(t *testing.T) {
capt := pushCapturingTagChat(t)
chunk := map[string]any{"text": "some content"}
allTags := map[string]float64{"RAG": 0.5, "vector database": 0.5}
llmTagChunk(t.Context(), nil, capt, chunk, allTags, nil, nil, "test@test", "test@test", "test_driver", "test_model", "test_key", "", 3, nil)
- tagKwd, ok := chunk["tag_kwd"].([]string)
- if !ok {
- t.Fatalf("expected chunk['tag_kwd'] to be []string, got %T (%v)", chunk["tag_kwd"], chunk["tag_kwd"])
- }
- if len(tagKwd) != 2 {
- t.Fatalf("expected 2 tags in tag_kwd, got %d: %v", len(tagKwd), tagKwd)
- }
- // Verify strict score-descending order: RAG (8) > vector database (6)
- if tagKwd[0] != "RAG" || tagKwd[1] != "vector database" {
- t.Fatalf("expected tag_kwd to be ordered descending by score ['RAG', 'vector database'], got: %v", tagKwd)
- }
- if chunk[common.TAG_FLD] == nil {
- t.Fatal("expected tag_feas to be populated")
- }
-}
-
-func TestSortedTagWeightsKeys(t *testing.T) {
- weights := map[string]int{
- "Low": 3,
- "Highest": 9,
- "Medium": 6,
- "Another": 6,
+ feas, ok := chunk[common.TAG_FLD].(OrderedTagWeights)
+ if !ok || len(feas) != 2 {
+ t.Fatalf("expected 2 tag_feas weights, got %T (%v)", chunk[common.TAG_FLD], chunk[common.TAG_FLD])
}
- got := sortedTagWeightsKeys(weights)
- expected := []string{"Highest", "Another", "Medium", "Low"}
- if len(got) != len(expected) {
- t.Fatalf("length mismatch: got %d, want %d", len(got), len(expected))
+ if _, ok := feas["RAG"]; !ok {
+ t.Fatalf("expected tag_feas to contain RAG, got %v", feas)
}
- if got[0] != "Highest" || got[3] != "Low" {
- t.Fatalf("sortedTagWeightsKeys order mismatch: %v", got)
+ // The tagged dataset writes only tag_feas; tag_kwd belongs to the tag
+ // source, so it must not be written onto the chunk (Python apply_tags).
+ if _, ok := chunk["tag_kwd"]; ok {
+ t.Fatalf("tag_kwd must not be written onto the tagged chunk, got %v", chunk["tag_kwd"])
}
}
@@ -900,7 +899,7 @@ func TestCleanTitle_PreservesVersionNumbers(t *testing.T) {
}
}
-func TestMatchAndTagChunk_TagKwdPopulated(t *testing.T) {
+func TestMatchAndTagChunkWritesOnlyTagFeas(t *testing.T) {
tokenizer.SetEngineType("infinity")
t.Cleanup(func() { tokenizer.SetEngineType("") })
tok := tokenizer.New("English")
@@ -928,31 +927,20 @@ func TestMatchAndTagChunk_TagKwdPopulated(t *testing.T) {
t.Fatalf("expected chunk[%q] to be non-empty OrderedTagWeights, got %T (%v)", common.TAG_FLD, chunk[common.TAG_FLD], chunk[common.TAG_FLD])
}
- // Verify chunk["tag_kwd"] is populated as []string
- kwds, ok := chunk["tag_kwd"].([]string)
- if !ok || len(kwds) == 0 {
- t.Fatalf("expected chunk['tag_kwd'] to be non-empty []string, got %T (%v)", chunk["tag_kwd"], chunk["tag_kwd"])
- }
-
- // Verify lengths match
- if len(kwds) != len(feas) {
- t.Fatalf("tag_kwd length (%d) != tag_feas length (%d)", len(kwds), len(feas))
+ // The tagged dataset writes only tag_feas; tag_kwd belongs to the tag
+ // source, so it must not be written onto the chunk (Python apply_tags).
+ if _, ok := chunk["tag_kwd"]; ok {
+ t.Fatalf("tag_kwd must not be written onto the tagged chunk, got %v", chunk["tag_kwd"])
}
- // Verify every tag in tag_kwd is present in tag_feas
- for _, k := range kwds {
- if _, exists := feas[k]; !exists {
- t.Errorf("tag %q in tag_kwd not found in tag_feas %v", k, feas)
- }
- }
-
- // Verify res.Tags matches chunk["tag_kwd"]
- if len(res.Tags) != len(kwds) {
- t.Fatalf("res.Tags length (%d) != chunk['tag_kwd'] length (%d)", len(res.Tags), len(kwds))
+ // The returned TaggedChunk still carries the tag list for LLM cold-start
+ // examples, and every returned tag must have a matching weight.
+ if len(res.Tags) == 0 {
+ t.Fatal("expected res.Tags to be non-empty")
}
- for i, tag := range res.Tags {
- if tag != kwds[i] {
- t.Errorf("res.Tags[%d] = %q, want %q", i, tag, kwds[i])
+ for _, tag := range res.Tags {
+ if _, exists := feas[tag]; !exists {
+ t.Errorf("tag %q in res.Tags not found in tag_feas %v", tag, feas)
}
}
}
@@ -1595,3 +1583,74 @@ func TestMatchAndTagChunk_RankDecayGradientScores(t *testing.T) {
t.Errorf("expected secondary Database (%d) > peripheral CloudInfra (%d)", dbScore, cloudScore)
}
}
+
+func TestTagSourceFileRowCacheExpiresAndCopies(t *testing.T) {
+ c := &tagSourceFileRowCache{items: make(map[string]tagSourceFileRow, 4)}
+ now := time.Now()
+ loc := "bucket/key.xlsx"
+ in := &entity.File{ID: "f1", Name: "tags.xlsx", Location: &loc}
+
+ stored := c.store("k", in, now)
+ if stored == in {
+ t.Fatal("store must hand back a copy, not the caller's row")
+ }
+ stored.Name = "mutated.xlsx" // mutating the returned row must not poison the cache
+ if got, ok := c.load("k", now.Add(time.Second)); !ok || got.Name != "tags.xlsx" {
+ t.Fatalf("cache hit lost the original row: got %+v ok=%v", got, ok)
+ }
+ if _, ok := c.load("k", now.Add(tagSourceFileRowTTL+time.Second)); ok {
+ t.Fatal("row must expire after tagSourceFileRowTTL")
+ }
+ if _, ok := c.load("missing", now); ok {
+ t.Fatal("unknown key must miss")
+ }
+}
+
+func TestTagSourceFileRowCacheEvictsOldest(t *testing.T) {
+ c := &tagSourceFileRowCache{items: make(map[string]tagSourceFileRow, tagSourceFileRowCacheMax)}
+ now := time.Now()
+ for i := 0; i < tagSourceFileRowCacheMax; i++ {
+ c.store(fmt.Sprintf("k%03d", i), &entity.File{ID: fmt.Sprintf("k%03d", i)}, now)
+ }
+ if len(c.items) != tagSourceFileRowCacheMax {
+ t.Fatalf("expected a full cache, got %d entries", len(c.items))
+ }
+ // One more insert must drop the oldest key instead of growing unbounded.
+ c.store("newest", &entity.File{ID: "newest"}, now)
+ if len(c.items) != tagSourceFileRowCacheMax {
+ t.Fatalf("expected the cache to stay bounded, got %d entries", len(c.items))
+ }
+ if _, ok := c.load("k000", now); ok {
+ t.Fatal("the oldest row should have been evicted")
+ }
+ if got, ok := c.load("newest", now); !ok || got.ID != "newest" {
+ t.Fatalf("the newest row should survive, got %+v ok=%v", got, ok)
+ }
+}
+
+// roundInt must match Python's round(), which is round-half-to-even:
+// round(0.5) == 0, round(1.5) == 2, round(2.5) == 2, round(3.5) == 4. The old
+// int(f+0.5) form rounded halves away from zero and returned 3 for 2.5.
+func TestRoundIntIsHalfToEvenLikePython(t *testing.T) {
+ cases := []struct {
+ in float64
+ want int
+ }{
+ {0.4, 0},
+ {0.5, 0},
+ {0.6, 1},
+ {1.5, 2},
+ {2.5, 2},
+ {3.5, 4},
+ {4.5, 4},
+ {-0.5, 0},
+ {-1.5, -2},
+ {-2.5, -2},
+ {9.0, 9},
+ }
+ for _, c := range cases {
+ if got := roundInt(c.in); got != c.want {
+ t.Errorf("roundInt(%v) = %d, want %d", c.in, got, c.want)
+ }
+ }
+}
diff --git a/internal/ingestion/component/schema/chunk_types.go b/internal/ingestion/component/schema/chunk_types.go
index 3c73b42ade..c60b8c7ce9 100644
--- a/internal/ingestion/component/schema/chunk_types.go
+++ b/internal/ingestion/component/schema/chunk_types.go
@@ -119,7 +119,6 @@ type ChunkDoc struct {
TitleSmTks string `json:"title_sm_tks,omitempty"`
ContentLtks string `json:"content_ltks,omitempty"`
ContentSmLtks string `json:"content_sm_ltks,omitempty"`
- TagKwd []string `json:"tag_kwd,omitempty"`
PageNumber *int `json:"page_number,omitempty"`
TopInt []int `json:"top_int,omitempty"`
PDFPositions json.RawMessage `json:"_pdf_positions,omitempty"`
@@ -146,6 +145,10 @@ func (d *ChunkDoc) UnmarshalJSON(data []byte) error {
if err := json.Unmarshal(data, &raw); err != nil {
return err
}
+ // Known ChunkDoc fields plus tag_kwd, which has no ChunkDoc field: Go's
+ // tagger emits tag_feas and the vocabulary comes from a tag source file,
+ // so no chunk carries tag_kwd. Deleted rather than left in raw so it
+ // cannot fall through to Extra and be re-emitted by MarshalJSON.
for _, key := range []string{
"text", "doc_type_kwd", "mom", "img_id",
"ck_type", "tk_nums", "layout", "layout_type", "layoutno", "image",
diff --git a/internal/ingestion/component/schema/extractor.go b/internal/ingestion/component/schema/extractor.go
index 7357b0aaa8..4a27f37268 100644
--- a/internal/ingestion/component/schema/extractor.go
+++ b/internal/ingestion/component/schema/extractor.go
@@ -144,7 +144,7 @@ type ExtractorOutputs struct {
OutputFormat string `json:"output_format,omitempty"`
// Chunks is the enriched chunk list. Each chunk is enriched with
- // modular extraction fields (important_kwd, question_kwd, tag_kwd,
+ // modular extraction fields (important_kwd, question_kwd, tag_feas,
// summary, metadata).
Chunks []map[string]any `json:"chunks,omitempty"`
diff --git a/internal/ingestion/component/tag_query.go b/internal/ingestion/component/tag_query.go
new file mode 100644
index 0000000000..778adecdb8
--- /dev/null
+++ b/internal/ingestion/component/tag_query.go
@@ -0,0 +1,342 @@
+//
+// 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 component
+
+import (
+ "context"
+ "math"
+ "sort"
+ "strings"
+
+ "ragflow/internal/entity"
+ "ragflow/internal/ingestion/component/schema"
+ "ragflow/internal/tokenizer"
+)
+
+const (
+ // tagQueryTopLabels caps how many tag source records contribute to the
+ // question's tag distribution.
+ //
+ // Python's tag_query (rag/nlp/search.py) issues the match with a
+ // MatchTextExpr whose topn is 100, so the engine returns at most 100
+ // records and the tag aggregation is computed over exactly that window:
+ //
+ // - Infinity (default engine): limit=0 is rewritten to 10000 but
+ // builder.match_text(..., topn=100) caps the result set; get_aggregation
+ // counts over the returned DataFrame.
+ // - OceanBase: LIMIT offset, fulltext_topn (= 100).
+ // - Elasticsearch/OpenSearch: aggregation comes from the engine's own
+ // terms agg over ALL matching documents, so there is no window at all.
+ //
+ // 100 matches the non-ES engines; for ES the window is an approximation.
+ tagQueryTopLabels = 100
+
+ // tagQueryProportionSmoothing is the S constant in Python's
+ // all_tags_in_portion / tag_query formulas.
+ tagQueryProportionSmoothing = 1000.0
+
+ // tagQueryLang is the analyzer language for the retrieval-side tag source
+ // index. "" selects the tokenizer's default (English). Documents and the
+ // question are tokenized with the same analyzer, so both sides stay
+ // consistent.
+ tagQueryLang = ""
+)
+
+// tagQueryIndexCache caches the merged retrieval-side index per set of tag
+// source files. Separate from tagSourceFileIndexCache (the per-file index,
+// which both consumers feed) because the merged index is keyed by the whole
+// file set instead of one file.
+var tagQueryIndexCache = newBoundedTagCache(tagSourceCacheMax)
+
+// TagSourceRef names a tag source file (parser_config tags.tag_file_id) and the
+// tenant that owns it. The tenant is required so the file can be resolved
+// inside the dataset's ownership scope before it is read (IDOR, CWE-639).
+type TagSourceRef struct {
+ FileID string
+ TenantID string
+}
+
+// TagFileIDFromParserConfig returns the tag source file id declared in a
+// dataset's parser_config. Two persisted shapes are supported:
+//
+// - Legacy / flat form: parser_config["tags"]["tag_file_id"].
+// - Go pipeline scoped form: parser_config["Extractor:<name>"]["tags"]
+// ["tag_file_id"], mirroring how NewExtractorComponent reads its params.
+//
+// Returns "" when unset.
+func TagFileIDFromParserConfig(parserConfig map[string]any) string {
+ if parserConfig == nil {
+ return ""
+ }
+ if v := tagFileIDFromTagsMap(parserConfig["tags"]); v != "" {
+ return v
+ }
+ // Several Extractor nodes can each declare their own tags block, so the
+ // winner has to be picked in a stable order: Go randomizes map iteration,
+ // and an unstable pick would let the dataset's tag source change between
+ // process restarts (different chunks tagged, different retrieval
+ // features). Sorting makes it deterministic; "Extractor" sorts before
+ // "Extractor:<name>" because it is a prefix, so the unscoped node wins.
+ keys := make([]string, 0, len(parserConfig))
+ for key := range parserConfig {
+ if key == "Extractor" || strings.HasPrefix(key, "Extractor:") {
+ keys = append(keys, key)
+ }
+ }
+ sort.Strings(keys)
+ for _, key := range keys {
+ extractorMap, ok := asStringAnyMap(parserConfig[key])
+ if !ok {
+ continue
+ }
+ // The tags config sits at the top level of the Extractor node value,
+ // i.e. parser_config["Extractor:<name>"]["tags"].
+ if v := tagFileIDFromTagsMap(extractorMap["tags"]); v != "" {
+ return v
+ }
+ }
+ return ""
+}
+
+// tagFileIDFromTagsMap pulls tag_file_id out of a raw "tags" config value,
+// accepting either a map[string]any or an entity.JSONMap.
+func tagFileIDFromTagsMap(raw any) string {
+ tags, ok := asStringAnyMap(raw)
+ if !ok {
+ return ""
+ }
+ if v, ok := tags["tag_file_id"].(string); ok {
+ return strings.TrimSpace(v)
+ }
+ return ""
+}
+
+// asStringAnyMap accepts both plain and entity.JSONMap values, which is how
+// parser_config is persisted depending on the write path.
+func asStringAnyMap(raw any) (map[string]any, bool) {
+ switch v := raw.(type) {
+ case map[string]any:
+ return v, true
+ case entity.JSONMap:
+ return map[string]any(v), true
+ default:
+ return nil, false
+ }
+}
+
+// resolvedTagSource pairs a reference with the file row it resolved to.
+type resolvedTagSource struct {
+ ref TagSourceRef
+ file *entity.File
+}
+
+// LoadTagQueryIndex loads the referenced tag source files and merges their
+// records into a single retrieval-time matching index, cached by the file set
+// (including each file's size/update time, so an edited tag file invalidates
+// the merged index). A single tag source file needs no merging: its own cached
+// index is returned as-is.
+//
+// It is the Go equivalent of Python's tag-dataset corpus used by
+// all_tags_in_portion / tag_query: Go has no tag dataset, so the records come
+// from the tag source file. Returns (nil, nil) when refs is empty or yields no
+// usable records.
+func LoadTagQueryIndex(ctx context.Context, refs []TagSourceRef) (*MemoryTagIndex, error) {
+ resolved := make([]resolvedTagSource, 0, len(refs))
+ tokens := make([]string, 0, len(refs))
+ for _, ref := range refs {
+ if ref.FileID == "" {
+ continue
+ }
+ f, err := resolveTagSourceFile(ctx, ref.FileID, ref.TenantID)
+ if err != nil {
+ return nil, err
+ }
+ resolved = append(resolved, resolvedTagSource{ref: ref, file: f})
+ tokens = append(tokens, tagSourceFileCacheKey(f, tagQueryLang))
+ }
+ if len(resolved) == 0 {
+ return nil, nil
+ }
+ // Single-file fast path: the per-file index was built from exactly the
+ // labels and the tokenizer the merged index would use, so it already is the
+ // merged index. Reusing it skips the rebuild and keeps only one copy cached.
+ // One tag source file per dataset is the common case - refs are deduplicated
+ // by (tenant, file).
+ if len(resolved) == 1 {
+ r := resolved[0]
+ idx, _, err := loadOrBuildTagFileIndex(ctx, r.file, r.ref.TenantID, tagQueryLang)
+ return idx, err
+ }
+ sort.Strings(tokens)
+ key := "tag-query\x00" + strings.Join(tokens, "\x01")
+ if cached, hit := tagQueryIndexCache.load(key); hit {
+ return cached, nil
+ }
+
+ var labels []schema.TagLabel
+ for _, r := range resolved {
+ idx, _, err := loadOrBuildTagFileIndex(ctx, r.file, r.ref.TenantID, tagQueryLang)
+ if err != nil {
+ return nil, err
+ }
+ if idx != nil {
+ labels = append(labels, idx.examples...)
+ }
+ }
+ if len(labels) == 0 {
+ return nil, nil
+ }
+ merged := buildMemoryTagIndex(labels, tokenizer.New(tagQueryLang))
+ if merged == nil {
+ return nil, nil
+ }
+ return tagQueryIndexCache.store(key, merged), nil
+}
+
+// TagProportions returns the per-tag background proportions used by the
+// tag_query formula, mirroring Python's all_tags_in_portion: a tag's count is
+// the number of records that mention it, and its proportion is
+// (count+1)/(total+smoothing).
+// The counts are precomputed on the index: only the smoothing denominator
+// differs per call, so this is O(distinct tags) rather than a walk over every
+// tag occurrence of every record.
+func (idx *MemoryTagIndex) TagProportions(smoothing float64) map[string]float64 {
+ out := make(map[string]float64)
+ if idx == nil || idx.tagTotal == 0 {
+ return out
+ }
+ denom := float64(idx.tagTotal) + smoothing
+ for t, c := range idx.tagCounts {
+ out[t] = (float64(c) + 1) / denom
+ }
+ return out
+}
+
+// MatchTagQuery mirrors rag/nlp/search.py::tag_query over a Go tag source file:
+// it matches the question against the tag source records, aggregates the tags of
+// the best-matching records, and converts that distribution into rank-feature
+// weights with Python's formula
+//
+// round(0.1 * (count+1) / (total + S) / max(1e-6, all_tags[tag]))
+//
+// returning the top-n tags (dots normalized to underscores, floored at 1).
+//
+// The question is tokenized with the analyzer the index itself was built with
+// (idx.tok), so records and question can never be analyzed differently: a
+// mismatched analyzer does not fail, it just silently matches nothing.
+//
+// The record-matching step approximates Python's engine query with an
+// IDF-weighted token overlap over the tag source records; unlike ingestion-time
+// tagging it applies no coverage threshold, because the query is short and
+// Python's tag_query runs with min_match=0.0.
+func (idx *MemoryTagIndex) MatchTagQuery(question string, topnTags int) map[string]float64 {
+ out := make(map[string]float64)
+ if idx == nil || len(idx.examples) == 0 || topnTags <= 0 || strings.TrimSpace(question) == "" {
+ return out
+ }
+ tokens, err := idx.tok.Tokenize(question)
+ if err != nil {
+ return out
+ }
+
+ scores := make(map[int]float64)
+ seen := make(map[string]struct{})
+ for _, w := range strings.Fields(tokens) {
+ w = strings.TrimSpace(w)
+ if w == "" {
+ continue
+ }
+ if _, dup := seen[w]; dup {
+ continue
+ }
+ seen[w] = struct{}{}
+ idf, ok := idx.idfs[w]
+ if !ok || idf <= 1e-6 {
+ continue
+ }
+ for _, docID := range idx.postings[w] {
+ scores[docID] += idf
+ }
+ }
+ if len(scores) == 0 {
+ return out
+ }
+
+ matched := make([]int, 0, len(scores))
+ for docID := range scores {
+ matched = append(matched, docID)
+ }
+ sort.Slice(matched, func(i, j int) bool {
+ if scores[matched[i]] != scores[matched[j]] {
+ return scores[matched[i]] > scores[matched[j]]
+ }
+ return matched[i] < matched[j]
+ })
+ if len(matched) > tagQueryTopLabels {
+ matched = matched[:tagQueryTopLabels]
+ }
+
+ counts := make(map[string]int)
+ for _, docID := range matched {
+ for _, t := range idx.examples[docID].Tags {
+ counts[t]++
+ }
+ }
+ if len(counts) == 0 {
+ return out
+ }
+ total := 0
+ for _, c := range counts {
+ total += c
+ }
+ allTags := idx.TagProportions(tagQueryProportionSmoothing)
+
+ type tagScore struct {
+ tag string
+ score float64
+ }
+ scored := make([]tagScore, 0, len(counts))
+ for t, c := range counts {
+ background := allTags[t]
+ if background <= 0 {
+ background = 0.0001
+ }
+ raw := 0.1 * float64(c+1) / (float64(total) + tagQueryProportionSmoothing) / math.Max(1e-6, background)
+ // Python rounds the raw score with round() before ranking it and only
+ // then floors it at 1 (search.py: tag_query), so the weight is an
+ // integer. round() is round-half-to-even, i.e. math.RoundToEven, not
+ // math.Round: round(2.5) == 2 while math.Round(2.5) == 3. Ranking on
+ // the rounded value keeps the top-n cut the same as Python's. Ties are
+ // broken by tag name here, where Python's are left in the engine's
+ // aggregation order.
+ scored = append(scored, tagScore{tag: t, score: math.RoundToEven(raw)})
+ }
+ sort.Slice(scored, func(i, j int) bool {
+ if scored[i].score != scored[j].score {
+ return scored[i].score > scored[j].score
+ }
+ return scored[i].tag < scored[j].tag
+ })
+ for i := 0; i < topnTags && i < len(scored); i++ {
+ name := strings.ReplaceAll(scored[i].tag, ".", "_")
+ value := math.Max(1.0, scored[i].score)
+ if existing, ok := out[name]; !ok || value > existing {
+ out[name] = value
+ }
+ }
+ return out
+}
diff --git a/internal/ingestion/component/tag_query_test.go b/internal/ingestion/component/tag_query_test.go
new file mode 100644
index 0000000000..1fa2b4884e
--- /dev/null
+++ b/internal/ingestion/component/tag_query_test.go
@@ -0,0 +1,234 @@
+//
+// 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 component
+
+import (
+ "fmt"
+ "math"
+ "testing"
+
+ "ragflow/internal/entity"
+ "ragflow/internal/ingestion/component/schema"
+ "ragflow/internal/tokenizer"
+)
+
+func TestTagFileIDFromParserConfig(t *testing.T) {
+ tests := []struct {
+ name string
+ parserConfig map[string]any
+ want string
+ }{
+ {
+ name: "nil config",
+ parserConfig: nil,
+ want: "",
+ },
+ {
+ name: "flat tags map",
+ parserConfig: map[string]any{"tags": map[string]any{"tag_file_id": "file-1"}},
+ want: "file-1",
+ },
+ {
+ name: "flat tags map trims",
+ parserConfig: map[string]any{"tags": map[string]any{"tag_file_id": " file-2 "}},
+ want: "file-2",
+ },
+ {
+ name: "extractor scoped form",
+ parserConfig: map[string]any{
+ "Extractor:AutoExtractDefault": map[string]any{
+ "tags": map[string]any{"tag_file_id": "file-3"},
+ },
+ },
+ want: "file-3",
+ },
+ {
+ name: "entity.JSONMap nested value",
+ parserConfig: map[string]any{
+ "tags": entity.JSONMap{"tag_file_id": "file-4"},
+ },
+ want: "file-4",
+ },
+ {
+ name: "no tag file id",
+ parserConfig: map[string]any{"tags": map[string]any{"top_n": 3}},
+ want: "",
+ },
+ {
+ name: "unrelated config",
+ parserConfig: map[string]any{"chunk_token_num": 128},
+ want: "",
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := TagFileIDFromParserConfig(tt.parserConfig); got != tt.want {
+ t.Fatalf("TagFileIDFromParserConfig(%v) = %q, want %q", tt.parserConfig, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestTagFileIDFromParserConfigPicksStableExtractorNode(t *testing.T) {
+ // Several Extractor nodes can each declare their own tags block. Go
+ // randomizes map iteration, so an unsorted scan would return a different
+ // tag file - and thus tag the dataset from a different tag source - on
+ // every call and every process restart.
+ parserConfig := map[string]any{
+ "Extractor": map[string]any{"tags": map[string]any{"tag_file_id": "file-unscoped"}},
+ }
+ for i := 0; i < 8; i++ {
+ parserConfig[fmt.Sprintf("Extractor:node-%d", i)] = map[string]any{
+ "tags": map[string]any{"tag_file_id": fmt.Sprintf("file-%d", i)},
+ }
+ }
+ // The unscoped "Extractor" node wins: it is a prefix of the scoped keys,
+ // so it sorts first.
+ for i := 0; i < 200; i++ {
+ if got := TagFileIDFromParserConfig(parserConfig); got != "file-unscoped" {
+ t.Fatalf("TagFileIDFromParserConfig with unscoped node = %q, want %q", got, "file-unscoped")
+ }
+ }
+ // Without it the lowest-sorting scoped node wins, still stably.
+ delete(parserConfig, "Extractor")
+ for i := 0; i < 200; i++ {
+ if got := TagFileIDFromParserConfig(parserConfig); got != "file-0" {
+ t.Fatalf("TagFileIDFromParserConfig across scoped nodes = %q, want %q", got, "file-0")
+ }
+ }
+}
+
+func newTagQueryTestIndex(t *testing.T) *MemoryTagIndex {
+ t.Helper()
+ // The infinity engine tokenizes by identity (whitespace split), so these
+ // tests need no native analyzer pool.
+ tokenizer.SetEngineType("infinity")
+ t.Cleanup(func() { tokenizer.SetEngineType("") })
+
+ labels := []schema.TagLabel{
+ {Content: "kubernetes cluster container orchestration pod scheduling", Tags: []string{"K8s", "Container"}},
+ {Content: "retrieval augmented generation vector search database", Tags: []string{"RAG", "Search"}},
+ }
+ idx := buildMemoryTagIndex(labels, tokenizer.New("English"))
+ if idx == nil {
+ t.Fatal("buildMemoryTagIndex returned nil")
+ }
+ return idx
+}
+
+func TestTagProportions(t *testing.T) {
+ idx := newTagQueryTestIndex(t)
+
+ got := idx.TagProportions(tagQueryProportionSmoothing)
+ // Four distinct tags, each appearing once, so total = 4.
+ want := (1.0 + 1) / (4.0 + tagQueryProportionSmoothing)
+ for _, tag := range []string{"K8s", "Container", "RAG", "Search"} {
+ if math.Abs(got[tag]-want) > 1e-12 {
+ t.Fatalf("proportion[%q] = %v, want %v", tag, got[tag], want)
+ }
+ }
+}
+
+func TestMatchTagQueryMatchesRelevantTags(t *testing.T) {
+ idx := newTagQueryTestIndex(t)
+
+ got := idx.MatchTagQuery("kubernetes cluster orchestration", 3)
+ if len(got) == 0 {
+ t.Fatal("expected a non-empty tag distribution")
+ }
+ for _, tag := range []string{"K8s", "Container"} {
+ if _, ok := got[tag]; !ok {
+ t.Fatalf("expected tag %q in result, got %v", tag, got)
+ }
+ }
+ if _, ok := got["RAG"]; ok {
+ t.Fatalf("unrelated tag RAG must not be boosted, got %v", got)
+ }
+ for tag, weight := range got {
+ if weight < 1 {
+ t.Fatalf("weight[%q] = %v, want >= 1", tag, weight)
+ }
+ }
+}
+
+// Python rounds the raw score before flooring it at 1
+// (search.py::tag_query: max(1, round(0.1*(c+1)/(cnt+S)/max(1e-6, all_tags[t])))).
+// A matched tag of the index above has c=1, cnt=2 and all_tags[t]=2/1004, so
+// the raw score is 0.1001996..., which Python rounds down to 0 and then floors
+// at 1. Go must land on the same integral weight instead of returning the raw
+// fraction.
+func TestMatchTagQueryWeightMatchesPythonRounding(t *testing.T) {
+ idx := newTagQueryTestIndex(t)
+
+ got := idx.MatchTagQuery("kubernetes cluster orchestration", 3)
+ for _, tag := range []string{"K8s", "Container"} {
+ weight, ok := got[tag]
+ if !ok {
+ t.Fatalf("expected tag %q in result, got %v", tag, got)
+ }
+ if weight != 1.0 {
+ t.Errorf("weight[%q] = %v, want 1 (Python: max(1, round(0.1001996)))", tag, weight)
+ }
+ }
+}
+
+// Python's round() yields an integer, so every returned weight is integral.
+func TestMatchTagQueryWeightsAreIntegral(t *testing.T) {
+ idx := newTagQueryTestIndex(t)
+
+ got := idx.MatchTagQuery("kubernetes cluster container orchestration pod scheduling", 3)
+ if len(got) == 0 {
+ t.Fatal("expected a non-empty tag distribution")
+ }
+ for tag, weight := range got {
+ if weight != math.Trunc(weight) {
+ t.Errorf("weight[%q] = %v, want an integral value", tag, weight)
+ }
+ }
+}
+
+func TestMatchTagQueryUnmatchedQuestionIsEmpty(t *testing.T) {
+ idx := newTagQueryTestIndex(t)
+
+ if got := idx.MatchTagQuery("zzzz qqqq", 3); len(got) != 0 {
+ t.Fatalf("expected empty result for unmatched question, got %v", got)
+ }
+}
+
+func TestMatchTagQueryCapsToTopN(t *testing.T) {
+ idx := newTagQueryTestIndex(t)
+
+ got := idx.MatchTagQuery("kubernetes cluster container orchestration pod scheduling", 1)
+ if len(got) != 1 {
+ t.Fatalf("expected exactly 1 tag with topn=1, got %v", got)
+ }
+}
+
+func TestMatchTagQueryNilIndexOrEmptyInput(t *testing.T) {
+ var idx *MemoryTagIndex
+ if got := idx.MatchTagQuery("anything", 3); len(got) != 0 {
+ t.Fatalf("nil index should yield empty result, got %v", got)
+ }
+
+ idx = newTagQueryTestIndex(t)
+ if got := idx.MatchTagQuery("", 3); len(got) != 0 {
+ t.Fatalf("empty question should yield empty result, got %v", got)
+ }
+ if got := idx.MatchTagQuery("kubernetes", 0); len(got) != 0 {
+ t.Fatalf("topn=0 should yield empty result, got %v", got)
+ }
+}
diff --git a/internal/ingestion/component/tag_source.go b/internal/ingestion/component/tag_source.go
new file mode 100644
index 0000000000..bb16af45e6
--- /dev/null
+++ b/internal/ingestion/component/tag_source.go
@@ -0,0 +1,795 @@
+//
+// 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.
+//
+
+// This file owns the tag source file corpus: everything that turns the
+// parser_config tag_file_id (or raw bytes) into tag examples, an inverted
+// index, or a tag vocabulary. Both consumers live here on purpose - ingestion
+// time tagging (ExtractorComponent) and retrieval time label question
+// (tag_query.go) read the same files through the same caches, so the
+// resolution, ownership check, parsing entry point, index build and caches
+// must not drift apart. The low-level xlsx/csv/txt readers this file calls
+// still live in extractor_tag.go.
+//
+// Sharing the caches is not sharing one index: the key carries the analyzer
+// language, and ingestion (dataset language) differs from retrieval
+// (tagQueryLang), so each builds its own. That is required - an index must be
+// tokenized with the analyzer its own caller matches against.
+
+package component
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/csv"
+ "errors"
+ "fmt"
+ "io"
+ "math"
+ "path/filepath"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/xuri/excelize/v2"
+
+ "ragflow/internal/common"
+ "ragflow/internal/dao"
+ "ragflow/internal/entity"
+ "ragflow/internal/ingestion/component/schema"
+ "ragflow/internal/tokenizer"
+)
+
+// bgSmoothing is the Dirichlet smoothing constant for background prior tag probabilities.
+const bgSmoothing = 10.0
+
+// MemoryTagIndex is an in-memory inverted index of tag examples (immutable after construction, safe for concurrent use).
+//
+// It is built by buildMemoryTagIndex and loaded through loadOrBuildTagFileIndex.
+// The retrieval-side readers of an index (TagProportions, MatchTagQuery) live in
+// tag_query.go, next to the loading path that serves retrieval.
+type MemoryTagIndex struct {
+ examples []schema.TagLabel
+ postings map[string][]int // word -> doc_ids (compact slice without per-doc map overhead)
+ idfs map[string]float64 // word -> idf
+ exTotalIDF []float64 // doc_id -> sum(IDF(w))
+ exTokenCount []int // doc_id -> number of unique tokens
+ allTags map[string]float64 // tag -> background prob (S=10)
+
+ // tok is the analyzer the index was tokenized with. Retrieval must match
+ // the question with the same analyzer, so the index carries it instead of
+ // trusting every caller to pass an equal one: a mismatch produces no error,
+ // just an index that silently never matches. Tokenizer is a stateless value
+ // (it only holds the language; the analyzer comes from a pool per call), so
+ // it is safe to keep and share on this immutable index.
+ tok tokenizer.Tokenizer
+
+ // tagCounts/tagTotal are the raw occurrence counts behind allTags. They are
+ // index constants, so TagProportions can derive any smoothing S from them
+ // without walking the examples again on every query.
+ tagCounts map[string]int
+ tagTotal int
+}
+
+func buildMemoryTagIndex(rawExamples []schema.TagLabel, tok tokenizer.Tokenizer) *MemoryTagIndex {
+ if len(rawExamples) == 0 {
+ return nil
+ }
+
+ cleanExamples := make([]schema.TagLabel, 0, len(rawExamples))
+ exWordSets := make([]map[string]struct{}, 0, len(rawExamples))
+ allTagCounts := make(map[string]int)
+ totalTagCount := 0
+
+ // 1. Filter empty contents, deduplicate tags per sample, and normalize dots with deep copies.
+ for _, ex := range rawExamples {
+ content := strings.TrimSpace(ex.Content)
+ if content == "" {
+ continue // Skip empty content.
+ }
+ tks, err := tok.Tokenize(content)
+ if err != nil {
+ common.Warn(fmt.Sprintf("extractor tags: tokenize example failed: %v", err))
+ continue
+ }
+ fields := strings.Fields(tks)
+ if len(fields) == 0 {
+ continue // Skip samples with no tokens.
+ }
+ wordSet := make(map[string]struct{}, len(fields))
+ for _, w := range fields {
+ if w = strings.TrimSpace(w); w != "" {
+ wordSet[w] = struct{}{}
+ }
+ }
+ if len(wordSet) == 0 {
+ continue
+ }
+
+ tagSet := make(map[string]struct{}, len(ex.Tags))
+ cleanTags := make([]string, 0, len(ex.Tags))
+ for _, t := range ex.Tags {
+ t = strings.TrimSpace(strings.ReplaceAll(t, ".", "_"))
+ if t != "" {
+ if _, exists := tagSet[t]; !exists {
+ tagSet[t] = struct{}{}
+ cleanTags = append(cleanTags, t)
+ }
+ }
+ }
+ if len(cleanTags) == 0 {
+ continue // Skip examples with no usable tags.
+ }
+ for _, t := range cleanTags {
+ allTagCounts[t]++
+ totalTagCount++
+ }
+
+ cleanExamples = append(cleanExamples, schema.TagLabel{
+ Content: content,
+ Tags: cleanTags,
+ })
+ exWordSets = append(exWordSets, wordSet)
+ }
+
+ N := float64(len(cleanExamples))
+ if N == 0 || totalTagCount == 0 {
+ return nil // Guard against all samples having empty tags.
+ }
+
+ docFreq := make(map[string]int)
+ postings := make(map[string][]int)
+
+ for i, wordSet := range exWordSets {
+ // Invariant: each docID is added to postings[w] at most once.
+ for w := range wordSet {
+ postings[w] = append(postings[w], i)
+ docFreq[w]++ // Each document contributes at most 1 to document frequency.
+ }
+ }
+
+ // 2. Standard smoothed IDF (terms covering all documents smoothly approach 0).
+ idfs := make(map[string]float64, len(docFreq))
+ for w, df := range docFreq {
+ idfs[w] = math.Log(1.0 + (N-float64(df)+0.5)/(float64(df)+0.5))
+ }
+
+ // 3. Precompute total IDF and token count per valid example (short-text TF=1, avoiding per-example TF maps).
+ exTotalIDF := make([]float64, len(cleanExamples))
+ exTokenCount := make([]int, len(cleanExamples))
+ for i, wordSet := range exWordSets {
+ var sum float64
+ for w := range wordSet {
+ sum += idfs[w]
+ }
+ exTotalIDF[i] = sum
+ exTokenCount[i] = len(wordSet)
+ }
+
+ // 4. Background prior probability distribution (smoothed Dirichlet prior).
+ alpha := bgSmoothing / float64(len(allTagCounts))
+ bgProportions := make(map[string]float64, len(allTagCounts))
+ for t, count := range allTagCounts {
+ bgProportions[t] = (float64(count) + alpha) / (float64(totalTagCount) + bgSmoothing)
+ }
+
+ return &MemoryTagIndex{
+ examples: cleanExamples,
+ postings: postings,
+ idfs: idfs,
+ exTotalIDF: exTotalIDF,
+ exTokenCount: exTokenCount,
+ allTags: bgProportions,
+ tok: tok,
+ tagCounts: allTagCounts,
+ tagTotal: totalTagCount,
+ }
+}
+
+// ----------------------------------------------------------------------
+// Index caches: the built index is keyed by the tag file's size/update time,
+// so an edited tag file is re-read instead of being served stale.
+// ----------------------------------------------------------------------
+
+const tagSourceCacheMax = 128
+
+type boundedTagCache struct {
+ mu sync.Mutex
+ cap int
+ items map[string]*MemoryTagIndex
+ recent []string
+}
+
+// newBoundedTagCache returns an LRU-bounded cache. A non-positive cap disables
+// caching: nothing is retained, which is what store() would do anyway after
+// evicting the entry it just inserted, and it keeps the eviction loop bounded.
+func newBoundedTagCache(cap int) *boundedTagCache {
+ return &boundedTagCache{
+ cap: cap,
+ items: make(map[string]*MemoryTagIndex, max(cap, 0)),
+ }
+}
+
+func (c *boundedTagCache) load(key string) (*MemoryTagIndex, bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ v, ok := c.items[key]
+ if !ok {
+ return nil, false
+ }
+ c.markRecentLocked(key)
+ return v, true
+}
+
+func (c *boundedTagCache) store(key string, val *MemoryTagIndex) *MemoryTagIndex {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if existing, ok := c.items[key]; ok {
+ return existing
+ }
+ // cap <= 0 disables caching, and a nil index must never be cached: load()
+ // reports a stored key as a hit, so caching nil would hand callers a nil
+ // *MemoryTagIndex that looks valid.
+ if c.cap <= 0 || val == nil {
+ return val
+ }
+ c.items[key] = val
+ c.recent = append(c.recent, key)
+ c.evictLocked()
+ return val
+}
+
+// evictLocked drops the least recently used entries until the cache fits its
+// cap. Every pass pops one element, so it always terminates.
+func (c *boundedTagCache) evictLocked() {
+ for len(c.items) > c.cap {
+ if len(c.recent) == 0 {
+ // items and recent have drifted apart (only store appends to both,
+ // so this needs a bug to happen): recent[0] would panic, and no
+ // tracked key is left to evict, so reset instead of staying over
+ // the cap forever - which would wedge the cache with entries it can
+ // never evict again.
+ c.items = make(map[string]*MemoryTagIndex, max(c.cap, 0))
+ return
+ }
+ oldest := c.recent[0]
+ c.recent = c.recent[1:]
+ delete(c.items, oldest)
+ }
+}
+
+func (c *boundedTagCache) markRecentLocked(key string) {
+ for i, k := range c.recent {
+ if k == key {
+ c.recent = append(c.recent[:i], c.recent[i+1:]...)
+ c.recent = append(c.recent, k)
+ break
+ }
+ }
+}
+
+var tagSourceFileIndexCache = newBoundedTagCache(tagSourceCacheMax)
+
+func buildIndexedTagSourceFromBytes(data []byte, filename, lang string) (*MemoryTagIndex, bool) {
+ rawExamples, err := parseTagSourceByFilename(data, filename)
+ if err != nil || len(rawExamples) == 0 {
+ if err != nil {
+ common.Warn(fmt.Sprintf("extractor tags: %v", err))
+ }
+ return nil, false
+ }
+ tok := tokenizer.New(lang)
+ indexed := buildMemoryTagIndex(rawExamples, tok)
+ if indexed == nil {
+ return nil, false
+ }
+ return indexed, true
+}
+
+// loadOrBuildTagFileIndex loads one tag source file's records as an in-memory
+// index, reusing the shared per-file index cache. It is the single loading path
+// for both ingestion (ExtractorComponent.loadTagFileIndexed) and retrieval
+// (LoadTagQueryIndex), so the two cannot drift into different resolution,
+// ownership checks or parse entry points.
+//
+// The cache key carries lang (the analyzer language), so the two consumers
+// share one index only when they ask for the same language. Keeping lang in
+// the key is what keeps an index tokenized with the analyzer its caller
+// matches against.
+//
+// The file row must already be resolved inside the caller's tenant.
+// It returns (nil, nil) when the file yields no usable records.
+func loadOrBuildTagFileIndex(ctx context.Context, f *entity.File, tenantID, lang string) (*MemoryTagIndex, bool, error) {
+ cacheKey := tagSourceFileCacheKey(f, lang)
+ if cached, ok := tagSourceFileIndexCache.load(cacheKey); ok {
+ return cached, true, nil // reused: no bytes read.
+ }
+ data, err := fetchTagSourceBytes(ctx, f, tenantID)
+ if err != nil {
+ return nil, false, err
+ }
+ idx, ok := buildIndexedTagSourceFromBytes(data, f.Name, lang)
+ if !ok || idx == nil {
+ return nil, false, nil // Guard against caching nil index in LRU.
+ }
+ return tagSourceFileIndexCache.store(cacheKey, idx), false, nil
+}
+
+func tagSourceFileCacheKey(f *entity.File, lang string) string {
+ location := ""
+ if f.Location != nil {
+ location = *f.Location
+ }
+ updateTime := int64(0)
+ if f.UpdateTime != nil {
+ updateTime = *f.UpdateTime
+ }
+ return fmt.Sprintf("tag-file:%s:%s:%s:%d:%d:%s", f.ID, f.ParentID, location, f.Size, updateTime, lang)
+}
+
+// parseTagSourceByFilename mirrors rag/app/tag.py chunk(): the format is chosen
+// by the file extension, and only .xlsx/.xls, .txt and .csv are supported. Any
+// other extension (including no extension) is rejected, matching Python's
+// NotImplementedError for unsupported formats. xlsx is parsed per-sheet (2
+// columns, no header, multiple sheets); .csv uses a quote-aware reader; .txt
+// uses the delimiter-detecting reader.
+func parseTagSourceByFilename(data []byte, filename string) ([]schema.TagLabel, error) {
+ switch strings.ToLower(filepath.Ext(filename)) {
+ case ".xlsx", ".xls":
+ return parseXLSXTagSource(data), nil
+ case ".csv":
+ return parseCSVQuoteAwareReader(bytes.NewReader(data), csvTagSourceDelimiter(data)), nil
+ case ".txt":
+ delimiter := detectCSVDelimiterBytes(data)
+ return parseCSVTagSourceReader(bytes.NewReader(data), delimiter), nil
+ default:
+ return nil, fmt.Errorf("unsupported tag source extension %q: only .xlsx, .txt and .csv are supported", filepath.Ext(filename))
+ }
+}
+
+// ----------------------------------------------------------------------
+// Tag source file readers, mirroring rag/app/tag.py's chunk(): xlsx is read
+// per-sheet, .csv with a quote-aware reader, .txt with the delimiter-detecting
+// one. Only parseTagSourceByFilename above calls into this section.
+// ----------------------------------------------------------------------
+
+func parseCSVTagSource(text string) []schema.TagLabel {
+ return parseCSVTagSourceBytes([]byte(text))
+}
+
+func parseCSVTagSourceBytes(data []byte) []schema.TagLabel {
+ return parseCSVTagSourceReader(bytes.NewReader(data), detectCSVDelimiterBytes(data))
+}
+
+// parseCSVTagSourceReader mirrors rag/app/tag.py's txt parsing: lines that do
+// not split into exactly two columns are accumulated as body text and prepended
+// to the next tagged line. The second column holds comma-separated tags.
+func parseCSVTagSourceReader(r io.Reader, delimiter string) []schema.TagLabel {
+ scanner := newTagSourceScannerFromReader(r, scanBufferMax)
+ result := make([]schema.TagLabel, 0)
+ content := ""
+ appendLine := func(s string) {
+ if content == "" {
+ content = s
+ } else {
+ content += "\n" + s
+ }
+ }
+ for scanner.Scan() {
+ line := scanner.Text()
+ arr := strings.Split(line, delimiter)
+ if len(arr) != 2 {
+ appendLine(line)
+ continue
+ }
+ appendLine(arr[0])
+ tags := splitAndTrim(arr[1], ",")
+ result = append(result, schema.TagLabel{Content: content, Tags: tags})
+ content = ""
+ }
+ if scanner.Err() != nil {
+ common.Warn(fmt.Sprintf("extractor tags: parse tag source: %v", scanner.Err()))
+ }
+ return result
+}
+
+// csvTagSourceDelimiter mirrors rag/app/tag.py's .csv path: the delimiter is
+// TAB as soon as the file contains one, comma otherwise. Python's docstring
+// asks for TAB-separated .csv, so the comma default must not be assumed.
+func csvTagSourceDelimiter(data []byte) rune {
+ if bytes.Contains(data, []byte("\t")) {
+ return '\t'
+ }
+ return ','
+}
+
+// parseCSVQuoteAwareReader mirrors rag/app/tag.py's .csv path: the whole text
+// goes through a single encoding/csv reader, so a quoted field may contain the
+// delimiter or span several physical lines (Python's csv.reader pulls further
+// lines from its generator while inside quotes; Go's reader does the same).
+// Records that do not yield exactly two non-empty columns are accumulated as
+// body text using the raw lines they span, and the second column holds
+// comma-separated tags.
+//
+// LazyQuotes mirrors Python's tolerance for stray quote characters: a bare "
+// inside an unquoted field is data there, not a fatal parse error.
+func parseCSVQuoteAwareReader(r io.Reader, delimiter rune) []schema.TagLabel {
+ data, err := io.ReadAll(r)
+ if err != nil {
+ common.Warn(fmt.Sprintf("extractor tags: read csv tag source: %v", err))
+ return nil
+ }
+ text := string(data)
+
+ reader := csv.NewReader(strings.NewReader(text))
+ reader.Comma = delimiter
+ reader.FieldsPerRecord = -1 // Python's csv.reader accepts variable column counts.
+ reader.LazyQuotes = true
+
+ result := make([]schema.TagLabel, 0)
+ content := ""
+ appendLine := func(s string) {
+ if content == "" {
+ content = s
+ } else {
+ content += "\n" + s
+ }
+ }
+
+ // InputOffset() reports where a record ended, so the text between the
+ // previous offset and this one is the raw span the record was parsed from,
+ // the equivalent of Python's lines[prev_line_num : reader.line_num].
+ start := 0
+ for {
+ rec, err := reader.Read()
+ if err != nil {
+ if !errors.Is(err, io.EOF) {
+ common.Warn(fmt.Sprintf("extractor tags: parse csv tag source: %v", err))
+ }
+ break
+ }
+ end := int(reader.InputOffset())
+ raw := strings.TrimSuffix(strings.TrimSuffix(text[start:end], "\n"), "\r")
+ start = end
+ // encoding/csv skips blank lines without reporting them, while Python's
+ // generator hands them to the reader as empty records, which land in
+ // the body text. Replay them as empty lines.
+ for strings.HasPrefix(raw, "\n") || strings.HasPrefix(raw, "\r\n") {
+ if raw[0] == '\r' {
+ raw = raw[1:]
+ }
+ raw = raw[1:]
+ appendLine("")
+ }
+ row := stripEmptyFields(rec)
+ if len(row) != 2 {
+ appendLine(raw)
+ continue
+ }
+ appendLine(row[0])
+ tags := splitAndTrim(row[1], ",")
+ result = append(result, schema.TagLabel{Content: content, Tags: tags})
+ content = ""
+ }
+ return result
+}
+
+// parseXLSXTagSource mirrors rag/app/tag.py's .xlsx path: every sheet is read
+// with no header, and each row contributes a (content, tags) pair from its
+// first and second non-empty cells. Single-cell rows are accumulated as body text
+// and prepended to the next tagged row, matching CSV parsing behavior.
+// The second cell holds comma-separated tags.
+func parseXLSXTagSource(data []byte) []schema.TagLabel {
+ f, err := excelize.OpenReader(bytes.NewReader(data))
+ if err != nil {
+ common.Warn(fmt.Sprintf("extractor tags: open xlsx tag source: %v", err))
+ return nil
+ }
+ defer f.Close()
+
+ result := make([]schema.TagLabel, 0)
+ for _, sheet := range f.GetSheetList() {
+ rows, err := f.GetRows(sheet)
+ if err != nil {
+ common.Warn(fmt.Sprintf("extractor tags: read xlsx sheet %q: %v", sheet, err))
+ continue
+ }
+ content := ""
+ appendLine := func(s string) {
+ if content == "" {
+ content = s
+ } else {
+ content += "\n" + s
+ }
+ }
+ for _, row := range rows {
+ var cells []string
+ for _, c := range row {
+ if c = strings.TrimSpace(c); c != "" {
+ cells = append(cells, c)
+ }
+ }
+ if len(cells) == 0 {
+ continue
+ }
+ if len(cells) == 1 {
+ appendLine(cells[0])
+ continue
+ }
+ appendLine(cells[0])
+ tags := splitAndTrim(cells[1], ",")
+ result = append(result, schema.TagLabel{Content: content, Tags: tags})
+ content = ""
+ }
+ }
+ return result
+}
+
+func stripEmptyFields(fields []string) []string {
+ out := make([]string, 0, len(fields))
+ for _, f := range fields {
+ if f = strings.TrimSpace(f); f != "" {
+ out = append(out, f)
+ }
+ }
+ return out
+}
+
+const scanBufferMax = 1 << 20
+
+func detectCSVDelimiterBytes(data []byte) string {
+ comma, tab := 0, 0
+ scanner := newTagSourceScanner(bytes.NewReader(data), len(data))
+ for scanner.Scan() {
+ line := scanner.Text()
+ if strings.TrimSpace(line) == "" {
+ continue
+ }
+ // Try quote-aware parse for comma
+ rComma := csv.NewReader(strings.NewReader(line))
+ rComma.Comma = ','
+ if rec, err := rComma.Read(); err == nil {
+ if len(rec) == 2 {
+ comma++
+ }
+ } else if len(strings.Split(line, ",")) == 2 {
+ comma++
+ }
+
+ // Try quote-aware parse for tab
+ rTab := csv.NewReader(strings.NewReader(line))
+ rTab.Comma = '\t'
+ if rec, err := rTab.Read(); err == nil {
+ if len(rec) == 2 {
+ tab++
+ }
+ } else if len(strings.Split(line, "\t")) == 2 {
+ tab++
+ }
+ }
+ if scanner.Err() != nil {
+ common.Warn(fmt.Sprintf("extractor tags: delimiter scan: %v", scanner.Err()))
+ }
+ if tab > 0 && tab >= comma {
+ return "\t"
+ }
+ return ","
+}
+
+func newTagSourceScanner(r io.Reader, dataLen int) *bufio.Scanner {
+ maxToken := dataLen + 1
+ if maxToken < 64*1024 {
+ maxToken = 64 * 1024
+ }
+ if maxToken > scanBufferMax {
+ maxToken = scanBufferMax
+ }
+ return newTagSourceScannerFromReader(r, maxToken)
+}
+
+func newTagSourceScannerFromReader(r io.Reader, maxTokens ...int) *bufio.Scanner {
+ maxToken := 64 * 1024
+ if len(maxTokens) > 0 && maxTokens[0] > maxToken {
+ maxToken = maxTokens[0]
+ }
+ initBuf := min(64*1024, maxToken)
+ scanner := bufio.NewScanner(r)
+ scanner.Buffer(make([]byte, 0, initBuf), maxToken)
+ return scanner
+}
+
+func splitAndTrim(s, sep string) []string {
+ parts := strings.Split(s, sep)
+ out := make([]string, 0, len(parts))
+ for _, p := range parts {
+ if p = strings.TrimSpace(p); p != "" {
+ out = append(out, p)
+ }
+ }
+ return out
+}
+
+// TagVocabularyFromBytes is the storage/DAO-free core of
+// TagVocabularyFromTagFileID. It parses a tag source file's raw bytes (mirroring
+// rag/app/tag.py's chunk format) and returns the vocabulary as tag -> number of
+// source examples that mention the tag; a tag repeated within one source example
+// counts once, matching buildMemoryTagIndex's per-sample deduplication.
+func TagVocabularyFromBytes(data []byte, filename string) (map[string]int, error) {
+ labels, err := parseTagSourceByFilename(data, filename)
+ if err != nil {
+ return nil, err
+ }
+ return tagVocabularyFromLabels(labels), nil
+}
+
+// tagVocabularyFromLabels counts, per tag, how many source examples mention it.
+// A tag repeated within one example counts once.
+func tagVocabularyFromLabels(labels []schema.TagLabel) map[string]int {
+ counts := make(map[string]int)
+ for _, lbl := range labels {
+ seen := make(map[string]struct{}, len(lbl.Tags))
+ for _, t := range lbl.Tags {
+ t = strings.TrimSpace(strings.ReplaceAll(t, ".", "_"))
+ if t != "" {
+ if _, exists := seen[t]; exists {
+ continue
+ }
+ seen[t] = struct{}{}
+ counts[t]++
+ }
+ }
+ }
+ return counts
+}
+
+// readTagSourceFile resolves a tag source file id (parser_config.tags.tag_file_id)
+// inside ownerTenantID and returns the file row together with its raw bytes.
+//
+// ownerTenantID is the tenant of the dataset that configured the file and is
+// required: tag_file_id is user-writable through parser_config, so the file must
+// be proven to belong to that tenant before its bytes are read (IDOR, CWE-639).
+// An empty ownerTenantID fails closed. Note that storage.Get's tenant argument
+// does not establish file ownership by itself.
+func readTagSourceFile(ctx context.Context, tagFileID, ownerTenantID string) (*entity.File, []byte, error) {
+ f, err := resolveTagSourceFile(ctx, tagFileID, ownerTenantID)
+ if err != nil {
+ return nil, nil, err
+ }
+ data, err := fetchTagSourceBytes(ctx, f, ownerTenantID)
+ if err != nil {
+ return nil, nil, err
+ }
+ return f, data, nil
+}
+
+const (
+ // tagSourceFileRowTTL is how long a resolved tag source file row is reused
+ // before the DB is asked again. The row only proves ownership and supplies
+ // the index cache key (size/update time), and retrieval labels a question
+ // once per search leg, so a short TTL removes that per-leg query while
+ // keeping an edited tag file from being served stale for long.
+ tagSourceFileRowTTL = 30 * time.Second
+
+ // tagSourceFileRowCacheMax bounds the number of cached file rows.
+ tagSourceFileRowCacheMax = 512
+)
+
+// tagSourceFileRowCache is a TTL-bounded cache of resolved tag source file
+// rows, keyed by (file id, tenant). Only positive lookups are cached: an
+// unresolvable tag_file_id keeps failing closed instead of being pinned.
+type tagSourceFileRowCache struct {
+ mu sync.Mutex
+ items map[string]tagSourceFileRow
+ order []string
+}
+
+type tagSourceFileRow struct {
+ file *entity.File
+ expiry time.Time
+}
+
+func (c *tagSourceFileRowCache) load(key string, now time.Time) (*entity.File, bool) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ row, ok := c.items[key]
+ if !ok {
+ return nil, false
+ }
+ if now.After(row.expiry) {
+ delete(c.items, key)
+ return nil, false
+ }
+ return row.file, true
+}
+
+// store caches a copy of the row and returns another copy, so callers cannot
+// mutate what later lookups will hand out.
+func (c *tagSourceFileRowCache) store(key string, f *entity.File, now time.Time) *entity.File {
+ cached := *f
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ if _, ok := c.items[key]; !ok {
+ for len(c.items) >= tagSourceFileRowCacheMax && len(c.order) > 0 {
+ oldest := c.order[0]
+ c.order = c.order[1:]
+ delete(c.items, oldest)
+ }
+ c.order = append(c.order, key)
+ }
+ c.items[key] = tagSourceFileRow{file: &cached, expiry: now.Add(tagSourceFileRowTTL)}
+ out := *f
+ return &out
+}
+
+var tagSourceFileRows = &tagSourceFileRowCache{items: make(map[string]tagSourceFileRow, 64)}
+
+// resolveTagSourceFile looks up a tag source file inside ownerTenantID and
+// validates that it is a readable stored object. Resolved rows are reused for
+// tagSourceFileRowTTL so repeated lookups of the same file do not each cost a
+// query.
+func resolveTagSourceFile(ctx context.Context, tagFileID, ownerTenantID string) (*entity.File, error) {
+ key := tagFileID + "\x00" + ownerTenantID
+ now := time.Now()
+ if cached, ok := tagSourceFileRows.load(key, now); ok {
+ return cached, nil
+ }
+ f, err := dao.NewFileDAO().GetByIDAndTenant(ctx, dao.DB, tagFileID, ownerTenantID)
+ if err != nil {
+ return nil, fmt.Errorf("tag source file %q not found: %w", tagFileID, err)
+ }
+ // The DAO can return (nil, nil) for a missing row, so the "%w" form is only
+ // used when there is an error to wrap.
+ if f == nil {
+ return nil, fmt.Errorf("tag source file %q not found in tenant %q", tagFileID, ownerTenantID)
+ }
+ if f.Location == nil || *f.Location == "" {
+ return nil, fmt.Errorf("tag source file %q has no storage location", tagFileID)
+ }
+ common.Info(fmt.Sprintf("tag source: file_id=%q name=%q parent_id=%q location=%q",
+ tagFileID, f.Name, f.ParentID, *f.Location))
+ return tagSourceFileRows.store(key, f, now), nil
+}
+
+// fetchTagSourceBytes reads a resolved tag source file from the storage backend.
+func fetchTagSourceBytes(ctx context.Context, f *entity.File, ownerTenantID string) ([]byte, error) {
+ stg := resolveStorage()
+ if stg == nil {
+ return nil, fmt.Errorf("tag source file %q: no storage backend registered", f.ID)
+ }
+ data, err := stg.Get(ctx, f.ParentID, *f.Location, ownerTenantID)
+ if err != nil {
+ return nil, fmt.Errorf("load tag source file %q/%q: %w", f.ParentID, *f.Location, err)
+ }
+ return data, nil
+}
+
+// TagVocabularyFromTagFileID loads a tag source file (parser_config.tags.tag_file_id)
+// and returns the tag vocabulary it defines. It is the Go-native source of the
+// selectable-tag list surfaced by the tag-options/aggregation API.
+//
+// It returns (nil, nil) when tagFileID is empty.
+func TagVocabularyFromTagFileID(ctx context.Context, tagFileID, ownerTenantID string) (map[string]int, error) {
+ if tagFileID == "" {
+ return nil, nil
+ }
+ common.Info(fmt.Sprintf("tag_vocab: loading tag source file_id=%q", tagFileID))
+ f, data, err := readTagSourceFile(ctx, tagFileID, ownerTenantID)
+ if err != nil {
+ return nil, err
+ }
+ common.Info(fmt.Sprintf("tag_vocab: file_id=%q loaded %d bytes", tagFileID, len(data)))
+ return TagVocabularyFromBytes(data, f.Name)
+}
diff --git a/internal/ingestion/component/tag_source_test.go b/internal/ingestion/component/tag_source_test.go
new file mode 100644
index 0000000000..439d0bc0ca
--- /dev/null
+++ b/internal/ingestion/component/tag_source_test.go
@@ -0,0 +1,94 @@
+//
+// 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 component
+
+import "testing"
+
+func TestBoundedTagCacheEvictsOldest(t *testing.T) {
+ c := newBoundedTagCache(2)
+ a, b, d := &MemoryTagIndex{}, &MemoryTagIndex{}, &MemoryTagIndex{}
+ c.store("a", a)
+ c.store("b", b)
+ c.store("c", d) // pushes "a" out
+
+ if _, ok := c.load("a"); ok {
+ t.Fatal("the oldest entry should have been evicted")
+ }
+ for key, want := range map[string]*MemoryTagIndex{"b": b, "c": d} {
+ got, ok := c.load(key)
+ if !ok || got != want {
+ t.Errorf("load(%q) = %v, %v; want %v, true", key, got, ok, want)
+ }
+ }
+ if len(c.items) != 2 {
+ t.Errorf("len(items) = %d, want 2", len(c.items))
+ }
+}
+
+// A non-positive cap used to run the eviction loop once per insert, dropping
+// the entry that had just been stored; it must simply retain nothing.
+func TestBoundedTagCacheZeroCapRetainsNothing(t *testing.T) {
+ c := newBoundedTagCache(0)
+ idx := &MemoryTagIndex{}
+ if got := c.store("a", idx); got != idx {
+ t.Fatalf("store must still return the caller's index, got %v", got)
+ }
+ if _, ok := c.load("a"); ok {
+ t.Fatal("cap <= 0 must disable caching")
+ }
+ if len(c.items) != 0 || len(c.recent) != 0 {
+ t.Errorf("items=%d recent=%d, want 0/0", len(c.items), len(c.recent))
+ }
+}
+
+// load() reports a stored key as a hit, so caching a nil index would hand
+// callers a nil *MemoryTagIndex that looks valid.
+func TestBoundedTagCacheSkipsNilIndex(t *testing.T) {
+ c := newBoundedTagCache(2)
+ c.store("a", nil)
+ if _, ok := c.load("a"); ok {
+ t.Fatal("a nil index must not be cached")
+ }
+ if len(c.items) != 0 {
+ t.Errorf("len(items) = %d, want 0", len(c.items))
+ }
+}
+
+// The eviction loop indexes recent[0], so it panics when items and recent
+// drift apart (items holds keys recent does not track). It must stay bounded
+// and terminate instead, and leave the cache usable afterwards - a stale entry
+// that recent cannot name would otherwise wedge the only slot forever.
+func TestBoundedTagCacheEvictionSurvivesRecentDrift(t *testing.T) {
+ c := newBoundedTagCache(1)
+ c.items["stale-a"] = &MemoryTagIndex{}
+ c.items["stale-b"] = &MemoryTagIndex{}
+ c.recent = nil
+
+ c.store("fresh", &MemoryTagIndex{})
+ if len(c.items) > c.cap {
+ t.Fatalf("cache exceeded its cap: %d > %d", len(c.items), c.cap)
+ }
+
+ idx := &MemoryTagIndex{}
+ c.store("next", idx)
+ if got, ok := c.load("next"); !ok || got != idx {
+ t.Fatalf("load(%q) = %v, %v; want %v, true", "next", got, ok, idx)
+ }
+ if len(c.items) > c.cap {
+ t.Fatalf("cache exceeded its cap: %d > %d", len(c.items), c.cap)
+ }
+}
diff --git a/internal/rag/agentic-rag/runtime/tool_search.go b/internal/rag/agentic-rag/runtime/tool_search.go
index 3ebfe4c58a..a1d1b0a462 100644
--- a/internal/rag/agentic-rag/runtime/tool_search.go
+++ b/internal/rag/agentic-rag/runtime/tool_search.go
@@ -457,10 +457,10 @@ type SearchDeps struct {
}
// QuestionLabeler labels a question against the KB objects: given the query and the KBs
-// it returns a map of question-type tag → weight the retriever uses to rank results. The
-// extractor (extractor_tag.go) writes tag_kwd (the tag-name list) and tag_feas (per-tag
-// weights) onto each chunk; the labeler aggregates tag_kwd to build the vocabulary and the
-// retriever ranks with tag_feas. No separate tag-library dataset is needed. The production
+// it returns a map of question-type tag → weight the retriever uses to rank results. Go has
+// no tag-library dataset: the labeler matches the query against the KBs' tag source files
+// (parser_config tags.tag_file_id), and the extractor (extractor_tag.go) writes only tag_feas
+// (per-tag weights) onto each chunk, which the retriever ranks with. The production
// implementation is internal/service.MetadataService.LabelQuestion; tests supply a stub.
type QuestionLabeler interface {
LabelQuestion(ctx context.Context, question string, kbs []*entity.Knowledgebase) map[string]float64
diff --git a/internal/router/router.go b/internal/router/router.go
index 5dd84afce4..970aa1658b 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -350,9 +350,6 @@ func (r *Router) Setup(engine *gin.Engine) {
datasets.GET("/:dataset_id", r.datasetsHandler.GetDataset)
datasets.PUT("/:dataset_id", r.datasetsHandler.UpdateDataset)
datasets.GET("/:dataset_id/graph", r.datasetsHandler.GetKnowledgeGraph)
- datasets.GET("/:dataset_id/tags", r.datasetsHandler.ListTags)
- datasets.PUT("/:dataset_id/tags", r.datasetsHandler.RenameTag)
- datasets.DELETE("/:dataset_id/tags", r.datasetsHandler.RemoveTags)
datasets.POST("/:dataset_id/embedding/check", r.datasetsHandler.CheckEmbedding)
datasets.POST("/:dataset_id/documents/batch-update-status", r.documentHandler.BatchUpdateDocumentStatus)
// Scheduler compile-status contract (API_PROXY_SCHEME=go/hybrid);
diff --git a/internal/service/chunk/chunk.go b/internal/service/chunk/chunk.go
index b91ba33b25..d6f3f5fe91 100644
--- a/internal/service/chunk/chunk.go
+++ b/internal/service/chunk/chunk.go
@@ -350,10 +350,10 @@ func (s *ChunkService) RetrievalTest(ctx context.Context, req *service.Retrieval
zap.Bool("keywordExtraction", req.Keyword != nil && *req.Keyword))
}
- // Get tag-based rank features via LabelQuestion
+ // Get tag-based rank features via LabelQuestion. The result is logged inside
+ // LabelQuestion (info on match, debug when skipped), so no log here.
metadataSvc := service.NewMetadataService()
labels := metadataSvc.LabelQuestion(ctx, modifiedQuestion, kbRecords)
- common.Debug("LabelQuestion result", zap.Any("labels", labels))
// Determine embedding model.
var embeddingModel *models.EmbeddingModel
@@ -1207,11 +1207,6 @@ func (s *ChunkService) UpdateChunk(ctx context.Context, req *service.UpdateChunk
d["position_int"] = req.Positions
}
- // Tag keywords
- if req.TagKwd != nil {
- d["tag_kwd"] = req.TagKwd
- }
-
// Tag features
if req.TagFeas != nil {
tagFeas, err := validateTagFeatures(req.TagFeas)
@@ -1394,9 +1389,6 @@ func (s *ChunkService) AddChunk(ctx context.Context, req *service.AddChunkReques
"docnm_kwd": docName,
"doc_id": req.DocumentID,
}
- if req.TagKwd != nil {
- chunkData["tag_kwd"] = req.TagKwd
- }
if tagFeas != nil {
chunkData["tag_feas"] = tagFeas
}
@@ -1458,9 +1450,6 @@ func (s *ChunkService) AddChunk(ctx context.Context, req *service.AddChunkReques
"create_timestamp": chunkData["create_timestamp_flt"],
"create_time": chunkData["create_time"],
}
- if req.TagKwd != nil {
- renamedChunk["tag_kwd"] = req.TagKwd
- }
if imgID, ok := chunkData["img_id"]; ok {
renamedChunk["image_id"] = imgID
}
diff --git a/internal/service/chunk/chunk_test.go b/internal/service/chunk/chunk_test.go
index bbf700a95e..558ecc76fa 100644
--- a/internal/service/chunk/chunk_test.go
+++ b/internal/service/chunk/chunk_test.go
@@ -565,7 +565,6 @@ func TestAddChunkSuccess(t *testing.T) {
Content: "chunk body",
ImportantKeywords: []string{"k1"},
Questions: []string{" q1 ", ""},
- TagKwd: []string{"tag1"},
TagFeas: map[string]interface{}{"tag1": float64(0.5)},
}, userID)
if err != nil {
diff --git a/internal/service/chunk_types.go b/internal/service/chunk_types.go
index 68cc1c92ce..13935e2ec1 100644
--- a/internal/service/chunk_types.go
+++ b/internal/service/chunk_types.go
@@ -73,7 +73,6 @@ type AddChunkRequest struct {
Content string `json:"content"`
ImportantKeywords []string `json:"important_keywords,omitempty"`
Questions []string `json:"questions,omitempty"`
- TagKwd []string `json:"tag_kwd,omitempty"`
TagFeas interface{} `json:"tag_feas,omitempty"`
ImageBase64 *string `json:"image_base64,omitempty"`
}
@@ -148,7 +147,6 @@ type UpdateChunkRequest struct {
Questions []string `json:"questions,omitempty"`
Available *bool `json:"available,omitempty"`
Positions []interface{} `json:"positions,omitempty"`
- TagKwd []string `json:"tag_kwd,omitempty"`
TagFeas interface{} `json:"tag_feas,omitempty"`
}
diff --git a/internal/service/dataset/tags.go b/internal/service/dataset/tags.go
index e6a81c175d..179d3bb9b7 100644
--- a/internal/service/dataset/tags.go
+++ b/internal/service/dataset/tags.go
@@ -4,106 +4,22 @@ import (
"context"
"errors"
"fmt"
- "sort"
"strings"
- "time"
"ragflow/internal/common"
"ragflow/internal/dao"
- enginetypes "ragflow/internal/engine/types"
- "ragflow/internal/entity"
"ragflow/internal/ingestion/component"
)
-// tagFileIDFromTagsMap pulls tag_file_id out of a raw "tags" config value
-// (i.e. parser_config["tags"] in the legacy flat form, or
-// parser_config["Extractor:<name>"]["tags"] in the Go pipeline scoped form),
-// accepting either a map[string]any or an entity.JSONMap. Returns "" when the
-// value is not a tags map or has no tag_file_id. In the Go backend the
-// authoritative tag vocabulary lives in this tag source file (parsed by the
-// extractor in extractor_tag.go). Note: the Go tag extractor (matchAndTagChunk)
-// DOES write tag_kwd onto chunks at parse time, but the selectable-tag list is
-// sourced from this vocabulary, not from chunk usage. Returns "" when unset.
-func tagFileIDFromTagsMap(raw any) string {
- if raw == nil {
- return ""
- }
- var tags map[string]any
- switch v := raw.(type) {
- case map[string]any:
- tags = v
- case entity.JSONMap:
- tags = map[string]any(v)
- default:
- return ""
- }
- if v, ok := tags["tag_file_id"].(string); ok {
- return strings.TrimSpace(v)
- }
- return ""
-}
-
-// extractTagFileID returns the tag source file ID declared in a dataset's
-// parser_config. The tags config lives in two possible shapes depending on how
-// the dataset was persisted:
-//
-// - Legacy / flat form: parser_config["tags"]["tag_file_id"].
-// - Go pipeline scoped form: parser_config["Extractor:<name>"]["tags"]
-// ["tag_file_id"] (e.g. "Extractor:AutoExtractDefault"). In this form the
-// component config is keyed by "<Component>:<InstanceName>" and the
-// sub-feature maps (tags/keywords/questions/summary/metadata) sit at the
-// top level of that value — mirroring how NewExtractorComponent reads its
-// params.
-//
-// The Go backend sources the authoritative tag vocabulary from this tag source
-// file (parsed by the extractor in extractor_tag.go). Note: the Go tag extractor
-// (matchAndTagChunk) DOES write tag_kwd onto chunks at parse time, but the
-// selectable-tag list is taken from this vocabulary, not from chunk usage.
-// Returns "" when unset.
-func extractTagFileID(parserConfig entity.JSONMap) string {
- if parserConfig == nil {
- return ""
- }
- // 1. Legacy / flat form.
- if v := tagFileIDFromTagsMap(parserConfig["tags"]); v != "" {
- return v
- }
- // 2. Go pipeline scoped form: any key shaped "<Component>:<Instance>" whose
- // component is Extractor.
- for key, raw := range parserConfig {
- if key == "Extractor" || strings.HasPrefix(key, "Extractor:") {
- extractorMap, ok := raw.(map[string]any)
- if !ok {
- // entity.JSONMap is an alias of map[string]any, so the assertion
- // above already covers it; this guard handles any other wrapper.
- if jm, ok2 := raw.(entity.JSONMap); ok2 {
- extractorMap = map[string]any(jm)
- } else {
- continue
- }
- }
- // The tags config sits at the top level of the Extractor node value,
- // i.e. parser_config["Extractor:<name>"]["tags"], NOT at the node
- // value itself. Pass that nested "tags" map to tagFileIDFromTagsMap.
- if v := tagFileIDFromTagsMap(extractorMap["tags"]); v != "" {
- return v
- }
- }
- }
- return ""
-}
-
func (d *DatasetService) AggregateTags(ctx context.Context, datasetIDs []string, userID string) ([]map[string]interface{}, common.ErrorCode, error) {
if len(datasetIDs) == 0 {
return nil, common.CodeDataError, errors.New("Lack of dataset_ids in query parameters")
}
// merged holds the selectable-tag vocabulary sourced exclusively from each
// dataset's configured tag source file (parser_config.tags.tag_file_id). The
- // count for a tag is the number of times it appears in that source file. The
- // Go tag extractor (matchAndTagChunk) does write tag_kwd onto chunks at parse
- // time, but by requirement the count reflects only the tag-file occurrence
- // count, so there is intentionally no chunk-level aggregation here. The Go
- // backend has no Python-style tag-library datasets.
+ // count for a tag is the number of times it appears in that source file.
+ // The Go backend has no Python-style tag-library datasets, so there is no
+ // chunk-level aggregation.
loader := d.tagVocabularyLoader
if loader == nil {
loader = component.TagVocabularyFromTagFileID
@@ -143,7 +59,7 @@ func (d *DatasetService) AggregateTags(ctx context.Context, datasetIDs []string,
// the number of times it occurs in the tag source file. The file is
// resolved against the dataset's own tenant: tag_file_id is user-writable,
// so a foreign file ID must not resolve (IDOR, CWE-639).
- if tagFileID := extractTagFileID(kb.ParserConfig); tagFileID != "" {
+ if tagFileID := component.TagFileIDFromParserConfig(map[string]any(kb.ParserConfig)); tagFileID != "" {
counts, vErr := loader(ctx, tagFileID, kb.TenantID)
if vErr != nil {
return nil, common.CodeServerError,
@@ -163,139 +79,3 @@ func (d *DatasetService) AggregateTags(ctx context.Context, datasetIDs []string,
}
return result, common.CodeSuccess, nil
}
-
-func (d *DatasetService) ListTags(ctx context.Context, datasetID, userID string) ([]map[string]interface{}, common.ErrorCode, error) {
- datasetID = strings.TrimSpace(datasetID)
- if datasetID == "" {
- return nil, common.CodeDataError, errors.New("lack of \"Dataset ID\"")
- }
- normalizedID, err := normalizeDatasetID(datasetID)
- if err != nil {
- return nil, common.CodeDataError, err
- }
- datasetID = normalizedID
- if !d.kbDAO.Accessible(ctx, dao.DB, datasetID, userID) {
- return nil, common.CodeDataError, errors.New("no authorization")
- }
- if d.docEngine == nil {
- return nil, common.CodeServerError, errors.New("document engine is not initialized")
- }
- kb, err := d.kbDAO.GetByID(ctx, dao.DB, datasetID)
- if err != nil || kb == nil {
- return nil, common.CodeDataError, errors.New("invalid Dataset ID")
- }
- indexName := fmt.Sprintf("ragflow_%s", kb.TenantID)
- newCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
- defer cancel()
- exists, err := d.docEngine.ChunkStoreExists(newCtx, indexName, datasetID)
- if err != nil {
- return nil, common.CodeServerError, fmt.Errorf("failed to inspect chunk store: %w", err)
- }
- if !exists {
- return []map[string]interface{}{}, common.CodeSuccess, nil
- }
- const pageSize = 10000
- counts := make(map[string]int)
- for offset := 0; ; offset += pageSize {
- if err = newCtx.Err(); err != nil {
- return nil, common.CodeServerError, fmt.Errorf("list tags timeout or canceled: %w", err)
- }
- searchResp, err := d.docEngine.Search(newCtx, &enginetypes.SearchRequest{
- IndexNames: []string{indexName},
- KbIDs: []string{datasetID},
- Offset: offset,
- Limit: pageSize,
- SelectFields: []string{"tag_kwd"},
- })
- if err != nil {
- return nil, common.CodeServerError, fmt.Errorf("failed to list tags: %w", err)
- }
- for _, agg := range d.docEngine.GetAggregation(searchResp.Chunks, "tag_kwd") {
- tag, _ := agg["key"].(string)
- if tag == "" {
- continue
- }
- switch count := agg["count"].(type) {
- case int:
- counts[tag] += count
- case int32:
- counts[tag] += int(count)
- case int64:
- counts[tag] += int(count)
- case float64:
- counts[tag] += int(count)
- }
- }
- chunkCount := len(searchResp.Chunks)
- if chunkCount == 0 || chunkCount < pageSize {
- break
- }
- if searchResp.Total > 0 && int64(offset+chunkCount) >= searchResp.Total {
- break
- }
- }
- if len(counts) == 0 {
- return []map[string]interface{}{}, common.CodeSuccess, nil
- }
- tags := make([]string, 0, len(counts))
- for tag := range counts {
- tags = append(tags, tag)
- }
- sort.Slice(tags, func(i, j int) bool {
- if counts[tags[i]] != counts[tags[j]] {
- return counts[tags[i]] > counts[tags[j]]
- }
- return tags[i] < tags[j]
- })
- result := make([]map[string]interface{}, 0, len(tags))
- for _, tag := range tags {
- result = append(result, map[string]interface{}{
- "key": tag,
- "count": counts[tag],
- })
- }
- return result, common.CodeSuccess, nil
-}
-
-func (d *DatasetService) RenameTag(ctx context.Context, datasetID, userID, fromTag, toTag string) (map[string]interface{}, common.ErrorCode, error) {
- fromTag = strings.TrimSpace(fromTag)
- toTag = strings.TrimSpace(toTag)
- datasetID, err := normalizeDatasetID(datasetID)
- if err != nil {
- return nil, common.CodeDataError, err
- }
- if strings.TrimSpace(datasetID) == "" {
- return nil, common.CodeDataError, errors.New("lack of \"Dataset ID\"")
- }
- if !d.kbDAO.Accessible(ctx, dao.DB, datasetID, userID) {
- return nil, common.CodeDataError, errors.New("no authorization")
- }
- if d.docEngine == nil {
- return nil, common.CodeServerError, errors.New("document engine is not initialized")
- }
- kb, err := d.kbDAO.GetByID(ctx, dao.DB, datasetID)
- if err != nil || kb == nil {
- return nil, common.CodeDataError, errors.New("invalid Dataset ID")
- }
- indexName := fmt.Sprintf("ragflow_%s", kb.TenantID)
- condition := map[string]interface{}{
- "tag_kwd": fromTag,
- "kb_id": datasetID,
- }
- newValue := map[string]interface{}{
- "remove": map[string]interface{}{
- "tag_kwd": fromTag,
- },
- "add": map[string]interface{}{
- "tag_kwd": toTag,
- },
- }
- err = d.docEngine.UpdateChunks(ctx, condition, newValue, indexName, datasetID)
- if err != nil {
- return nil, common.CodeServerError, fmt.Errorf("failed to rename tag: %w", err)
- }
- return map[string]interface{}{
- "from": fromTag,
- "to": toTag,
- }, common.CodeSuccess, nil
-}
diff --git a/internal/service/dataset/tags_list_test.go b/internal/service/dataset/tags_list_test.go
deleted file mode 100644
index c18aa2989c..0000000000
--- a/internal/service/dataset/tags_list_test.go
+++ /dev/null
@@ -1,245 +0,0 @@
-package dataset
-
-import (
- "context"
- "errors"
- "strings"
- "testing"
-
- "ragflow/internal/common"
- "ragflow/internal/dao"
- "ragflow/internal/engine"
- "ragflow/internal/engine/types"
- "ragflow/internal/entity"
-)
-
-type listTagsMockEngine struct {
- engine.DocEngine
- searchResults map[string]*types.SearchResult
- searchErr error
- requests []*types.SearchRequest
- chunkStoreExists bool
- chunkStoreErr error
-}
-
-func (m *listTagsMockEngine) Search(ctx context.Context, req *types.SearchRequest) (*types.SearchResult, error) {
- if m.searchErr != nil {
- return nil, m.searchErr
- }
- cloned := &types.SearchRequest{
- IndexNames: append([]string(nil), req.IndexNames...),
- KbIDs: append([]string(nil), req.KbIDs...),
- Offset: req.Offset,
- Limit: req.Limit,
- SelectFields: append([]string(nil), req.SelectFields...),
- }
- m.requests = append(m.requests, cloned)
- if len(req.IndexNames) == 0 {
- return &types.SearchResult{}, nil
- }
- if res, ok := m.searchResults[req.IndexNames[0]]; ok {
- return res, nil
- }
- return &types.SearchResult{}, nil
-}
-
-func (m *listTagsMockEngine) GetAggregation(chunks []map[string]interface{}, fieldName string) []map[string]interface{} {
- counts := make(map[string]int)
- for _, chunk := range chunks {
- raw, ok := chunk[fieldName]
- if !ok || raw == nil {
- continue
- }
- switch value := raw.(type) {
- case string:
- for _, tag := range strings.Split(value, "###") {
- tag = strings.TrimSpace(tag)
- if tag != "" {
- counts[tag]++
- }
- }
- case []string:
- for _, tag := range value {
- tag = strings.TrimSpace(tag)
- if tag != "" {
- counts[tag]++
- }
- }
- }
- }
-
- result := make([]map[string]interface{}, 0, len(counts))
- for tag, count := range counts {
- result = append(result, map[string]interface{}{
- "key": tag,
- "count": count,
- })
- }
- return result
-}
-
-func (m *listTagsMockEngine) ChunkStoreExists(ctx context.Context, baseName, datasetID string) (bool, error) {
- if m.chunkStoreErr != nil {
- return false, m.chunkStoreErr
- }
- return m.chunkStoreExists, nil
-}
-
-func (m *listTagsMockEngine) GetType() string { return "mock" }
-
-func (m *listTagsMockEngine) Ping(ctx context.Context) error { return nil }
-
-func (m *listTagsMockEngine) Close() error { return nil }
-
-func testDatasetServiceForListTags(t *testing.T, docEngine engine.DocEngine) *DatasetService {
- t.Helper()
- return &DatasetService{
- kbDAO: dao.NewKnowledgebaseDAO(),
- docEngine: docEngine,
- }
-}
-
-func insertListTagsKB(t *testing.T, datasetID, tenantID, permission string, docNum int64) {
- t.Helper()
- kb := &entity.Knowledgebase{
- ID: datasetID,
- TenantID: tenantID,
- Name: "kb-" + datasetID[:6],
- EmbdID: "embedding@OpenAI",
- CreatedBy: tenantID,
- Permission: permission,
- ParserID: "naive",
- ParserConfig: entity.JSONMap{},
- DocNum: docNum,
- Status: sptr(string(entity.StatusValid)),
- }
- if err := dao.DB.Create(kb).Error; err != nil {
- t.Fatalf("insert test kb: %v", err)
- }
-}
-
-func TestDatasetServiceListTagsSuccess(t *testing.T) {
- db := setupServiceTestDB(t)
- pushServiceDB(t, db)
-
- kbInput := "123e4567-e89b-12d3-a456-426614174000"
- kbID := strings.ReplaceAll(kbInput, "-", "")
- insertListTagsKB(t, kbID, "user-1", string(entity.TenantPermissionMe), 2)
-
- docEngine := &listTagsMockEngine{
- chunkStoreExists: true,
- searchResults: map[string]*types.SearchResult{
- "ragflow_user-1": {
- Chunks: []map[string]interface{}{
- {"tag_kwd": "finance###urgent"},
- {"tag_kwd": "finance"},
- },
- },
- },
- }
- ctx := t.Context()
-
- result, code, err := testDatasetServiceForListTags(t, docEngine).ListTags(ctx, kbInput, "user-1")
- if err != nil {
- t.Fatalf("ListTags failed: %v", err)
- }
- if code != common.CodeSuccess {
- t.Fatalf("code=%d want=%d", code, common.CodeSuccess)
- }
- if len(result) != 2 {
- t.Fatalf("len(result)=%d want=2 result=%v", len(result), result)
- }
- if result[0]["key"] != "finance" || result[0]["count"] != 2 {
- t.Fatalf("first row=%v want finance/2", result[0])
- }
- if result[1]["key"] != "urgent" || result[1]["count"] != 1 {
- t.Fatalf("second row=%v want urgent/1", result[1])
- }
- if len(docEngine.requests) != 1 {
- t.Fatalf("search requests=%d want=1", len(docEngine.requests))
- }
- req := docEngine.requests[0]
- if len(req.IndexNames) != 1 || req.IndexNames[0] != "ragflow_user-1" {
- t.Fatalf("IndexNames=%v want [ragflow_user-1]", req.IndexNames)
- }
- if len(req.KbIDs) != 1 || req.KbIDs[0] != kbID {
- t.Fatalf("KbIDs=%v want [%s]", req.KbIDs, kbID)
- }
-}
-
-func TestDatasetServiceListTagsReturnsEmptyWhenChunkStoreMissing(t *testing.T) {
- db := setupServiceTestDB(t)
- pushServiceDB(t, db)
-
- kbInput := "123e4567-e89b-12d3-a456-426614174000"
- kbID := strings.ReplaceAll(kbInput, "-", "")
- insertListTagsKB(t, kbID, "user-1", string(entity.TenantPermissionMe), 1)
-
- docEngine := &listTagsMockEngine{chunkStoreExists: false}
-
- ctx := t.Context()
-
- result, code, err := testDatasetServiceForListTags(t, docEngine).ListTags(ctx, kbInput, "user-1")
- if err != nil {
- t.Fatalf("ListTags failed: %v", err)
- }
- if code != common.CodeSuccess {
- t.Fatalf("code=%d want=%d", code, common.CodeSuccess)
- }
- if len(result) != 0 {
- t.Fatalf("len(result)=%d want=0 result=%v", len(result), result)
- }
- if len(docEngine.requests) != 0 {
- t.Fatalf("search requests=%d want=0", len(docEngine.requests))
- }
-}
-
-func TestDatasetServiceListTagsRejectsUnauthorizedDataset(t *testing.T) {
- db := setupServiceTestDB(t)
- pushServiceDB(t, db)
-
- kbInput := "123e4567-e89b-12d3-a456-426614174000"
- kbID := strings.ReplaceAll(kbInput, "-", "")
- insertListTagsKB(t, kbID, "tenant-9", string(entity.TenantPermissionMe), 1)
-
- docEngine := &listTagsMockEngine{chunkStoreExists: true}
-
- ctx := t.Context()
-
- _, code, err := testDatasetServiceForListTags(t, docEngine).ListTags(ctx, kbInput, "user-1")
- if err == nil {
- t.Fatal("expected unauthorized error")
- }
- if code != common.CodeDataError {
- t.Fatalf("code=%d want=%d", code, common.CodeDataError)
- }
- if err.Error() != "no authorization" {
- t.Fatalf("error=%q want=%q", err.Error(), "no authorization")
- }
-}
-
-func TestDatasetServiceListTagsReturnsChunkStoreError(t *testing.T) {
- db := setupServiceTestDB(t)
- pushServiceDB(t, db)
-
- kbInput := "123e4567-e89b-12d3-a456-426614174000"
- kbID := strings.ReplaceAll(kbInput, "-", "")
- insertListTagsKB(t, kbID, "user-1", string(entity.TenantPermissionMe), 1)
-
- docEngine := &listTagsMockEngine{
- chunkStoreErr: errors.New("boom"),
- }
-
- ctx := t.Context()
-
- _, code, err := testDatasetServiceForListTags(t, docEngine).ListTags(ctx, kbInput, "user-1")
- if err == nil {
- t.Fatal("expected chunk store error")
- }
- if code != common.CodeServerError {
- t.Fatalf("code=%d want=%d", code, common.CodeServerError)
- }
- if !strings.Contains(err.Error(), "failed to inspect chunk store: boom") {
- t.Fatalf("err=%q want contains %q", err.Error(), "failed to inspect chunk store: boom")
- }
-}
diff --git a/internal/service/dataset/tags_rename_test.go b/internal/service/dataset/tags_rename_test.go
deleted file mode 100644
index 033aac38e3..0000000000
--- a/internal/service/dataset/tags_rename_test.go
+++ /dev/null
@@ -1,160 +0,0 @@
-package dataset
-
-import (
- "context"
- "errors"
- "strings"
- "testing"
-
- "ragflow/internal/common"
- "ragflow/internal/dao"
- "ragflow/internal/engine"
- "ragflow/internal/entity"
-)
-
-type renameTagUpdateCall struct {
- Condition map[string]interface{}
- NewValue map[string]interface{}
- BaseName string
- DatasetID string
-}
-
-type renameTagMockEngine struct {
- engine.DocEngine
- updateCalls []renameTagUpdateCall
- updateErr error
-}
-
-func (m *renameTagMockEngine) UpdateChunks(ctx context.Context, condition map[string]interface{}, newValue map[string]interface{}, baseName string, datasetID string) error {
- m.updateCalls = append(m.updateCalls, renameTagUpdateCall{
- Condition: condition,
- NewValue: newValue,
- BaseName: baseName,
- DatasetID: datasetID,
- })
- return m.updateErr
-}
-
-func (m *renameTagMockEngine) GetType() string { return "mock" }
-func (m *renameTagMockEngine) Ping(ctx context.Context) error { return nil }
-func (m *renameTagMockEngine) Close() error { return nil }
-
-func testDatasetServiceForRenameTag(t *testing.T, docEngine engine.DocEngine) *DatasetService {
- t.Helper()
- return &DatasetService{
- kbDAO: dao.NewKnowledgebaseDAO(),
- docEngine: docEngine,
- }
-}
-
-func insertRenameTagKB(t *testing.T, datasetID, tenantID, permission string) {
- t.Helper()
- kb := &entity.Knowledgebase{
- ID: datasetID,
- TenantID: tenantID,
- Name: "kb-" + datasetID[:6],
- EmbdID: "embedding@OpenAI",
- CreatedBy: tenantID,
- Permission: permission,
- ParserID: "naive",
- ParserConfig: entity.JSONMap{},
- Status: sptr(string(entity.StatusValid)),
- }
- if err := dao.DB.Create(kb).Error; err != nil {
- t.Fatalf("insert test kb: %v", err)
- }
-}
-
-func TestDatasetServiceRenameTagSuccess(t *testing.T) {
- db := setupServiceTestDB(t)
- pushServiceDB(t, db)
-
- kbInput := "123e4567-e89b-12d3-a456-426614174000"
- kbID := strings.ReplaceAll(kbInput, "-", "")
- insertRenameTagKB(t, kbID, "user-1", string(entity.TenantPermissionMe))
-
- docEngine := &renameTagMockEngine{}
- ctx := t.Context()
-
- result, code, err := testDatasetServiceForRenameTag(t, docEngine).RenameTag(ctx, kbInput, "user-1", "old-tag ", "new-tag")
- if err != nil {
- t.Fatalf("RenameTag failed: %v", err)
- }
- if code != common.CodeSuccess {
- t.Fatalf("code=%d want=%d", code, common.CodeSuccess)
- }
- if result["from"] != "old-tag" || result["to"] != "new-tag" {
- t.Fatalf("result=%v", result)
- }
- if len(docEngine.updateCalls) != 1 {
- t.Fatalf("update calls=%d want=1", len(docEngine.updateCalls))
- }
-
- call := docEngine.updateCalls[0]
- if call.BaseName != "ragflow_user-1" {
- t.Fatalf("baseName=%q want=%q", call.BaseName, "ragflow_user-1")
- }
- if call.DatasetID != kbID {
- t.Fatalf("datasetID=%q want=%q", call.DatasetID, kbID)
- }
- if got := call.Condition["tag_kwd"]; got != "old-tag" {
- t.Fatalf("condition tag_kwd=%v want=%q", got, "old-tag")
- }
- if got := call.Condition["kb_id"]; got != kbID {
- t.Fatalf("condition kb_id=%v want=%q", got, kbID)
- }
-
- remove, _ := call.NewValue["remove"].(map[string]interface{})
- add, _ := call.NewValue["add"].(map[string]interface{})
- if got := remove["tag_kwd"]; got != "old-tag" {
- t.Fatalf("remove tag_kwd=%v want=%q", got, "old-tag")
- }
- if got := add["tag_kwd"]; got != "new-tag" {
- t.Fatalf("add tag_kwd=%v want=%q", got, "new-tag")
- }
-}
-
-func TestDatasetServiceRenameTagUnauthorized(t *testing.T) {
- db := setupServiceTestDB(t)
- pushServiceDB(t, db)
-
- kbInput := "123e4567-e89b-12d3-a456-426614174000"
- kbID := strings.ReplaceAll(kbInput, "-", "")
- insertRenameTagKB(t, kbID, "tenant-9", string(entity.TenantPermissionMe))
-
- ctx := t.Context()
-
- _, code, err := testDatasetServiceForRenameTag(t, &renameTagMockEngine{}).RenameTag(ctx, kbInput, "user-1", "old", "new")
- if err == nil {
- t.Fatal("expected unauthorized error")
- }
- if code != common.CodeDataError {
- t.Fatalf("code=%d want=%d", code, common.CodeDataError)
- }
- if err.Error() != "no authorization" {
- t.Fatalf("error=%q want=%q", err.Error(), "no authorization")
- }
-}
-
-func TestDatasetServiceRenameTagUpdateError(t *testing.T) {
- db := setupServiceTestDB(t)
- pushServiceDB(t, db)
-
- kbInput := "123e4567-e89b-12d3-a456-426614174000"
- kbID := strings.ReplaceAll(kbInput, "-", "")
- insertRenameTagKB(t, kbID, "user-1", string(entity.TenantPermissionMe))
-
- docEngine := &renameTagMockEngine{updateErr: errors.New("boom")}
- ctx := t.Context()
-
- _, code, err := testDatasetServiceForRenameTag(t, docEngine).RenameTag(ctx, kbInput, "user-1", "old", "new")
- if err == nil {
- t.Fatal("expected update error")
- }
- if code != common.CodeServerError {
- t.Fatalf("code=%d want=%d", code, common.CodeServerError)
- }
- if !strings.Contains(err.Error(), "failed to rename tag") {
- t.Fatalf("error=%q want contains %q", err.Error(), "failed to rename tag")
- }
-}
diff --git a/internal/service/nlp/retrieval.go b/internal/service/nlp/retrieval.go
index 58a4080bf1..a4b7c76217 100644
--- a/internal/service/nlp/retrieval.go
+++ b/internal/service/nlp/retrieval.go
@@ -301,9 +301,6 @@ func (s *RetrievalService) Retrieval(ctx context.Context, req *RetrievalRequest)
if v, ok := chunk["important_kwd"]; ok {
resultChunk["important_kwd"] = v
}
- if v, ok := chunk["tag_kwd"]; ok {
- resultChunk["tag_kwd"] = v
- }
if v, ok := chunk["img_id"]; ok {
resultChunk["image_id"] = v
} else {
@@ -361,11 +358,10 @@ func (s *RetrievalService) Retrieval(ctx context.Context, req *RetrievalRequest)
} else {
resultChunk["row_id"] = nil
}
- if v, ok := chunk["tag_kwd"]; ok {
- resultChunk["tag_kwd"] = v
- } else {
- resultChunk["tag_kwd"] = []string{}
- }
+ // Mirrors rag/nlp/search.py's chunk.get("tag_kwd", []): neither side
+ // selects tag_kwd (this file's src, search.py's default src), so the
+ // engine never returns it even when a legacy chunk carries it.
+ resultChunk["tag_kwd"] = []string{}
vectorColumn := fmt.Sprintf("q_%d_vec", dim)
if v, ok := chunk[vectorColumn]; ok {
diff --git a/internal/service/tag.go b/internal/service/tag.go
index 4190235221..a6b57bdf8d 100644
--- a/internal/service/tag.go
+++ b/internal/service/tag.go
@@ -19,343 +19,119 @@ package service
import (
"context"
"encoding/json"
- "fmt"
- "ragflow/internal/common"
- "ragflow/internal/engine/kvrocks"
- "sort"
- "strings"
- "time"
"go.uber.org/zap"
- "ragflow/internal/engine/types"
+ "ragflow/internal/common"
"ragflow/internal/entity"
- "ragflow/internal/service/nlp"
-
- "github.com/cespare/xxhash/v2"
+ "ragflow/internal/ingestion/component"
)
-// getTagsCacheKey generates a cache key from kb_ids using xxhash64
-func getTagsCacheKey(kbIDs []string) string {
- // Normalize: unique + sorted so the key is set-stable regardless of caller order.
- seen := make(map[string]struct{}, len(kbIDs))
- norm := make([]string, 0, len(kbIDs))
- for _, id := range kbIDs {
- if _, ok := seen[id]; ok {
- continue
- }
- seen[id] = struct{}{}
- norm = append(norm, id)
- }
- sort.Strings(norm)
- hasher := xxhash.New()
- hasher.Write([]byte(strings.Join(norm, "\x00")))
- return fmt.Sprintf("%x", hasher.Sum64())
-}
-
-// GetTagsFromCache retrieves cached tags for given kb_ids
-// Returns nil if not found (cache miss)
-func GetTagsFromCache(ctx context.Context, kbIDs []string) (map[string]float64, error) {
- if len(kbIDs) == 0 {
- return nil, nil
- }
-
- redisClient := kvrocks.Get()
- if redisClient == nil {
- common.Warn("Redis client not available, skipping cache lookup")
- return nil, nil
- }
-
- key := getTagsCacheKey(kbIDs)
- data, err := redisClient.Get(ctx, key)
- if err != nil || data == "" {
- // Cache miss or error
- return nil, nil
- }
-
- var tags map[string]float64
- if err := json.Unmarshal([]byte(data), &tags); err != nil {
- common.Warn("Failed to unmarshal cached tags", zap.Error(err))
- return nil, nil
- }
-
- return tags, nil
-}
-
-// SetTagsToCache stores tags in cache for given kb_ids with 10 minute expiry
-func SetTagsToCache(ctx context.Context, kbIDs []string, tags map[string]float64) error {
- if len(kbIDs) == 0 || tags == nil {
- return nil
- }
-
- redisClient := kvrocks.Get()
- if redisClient == nil {
- common.Warn("Redis client not available, skipping cache store")
- return nil
- }
-
- key := getTagsCacheKey(kbIDs)
- data, err := json.Marshal(tags)
- if err != nil {
- return fmt.Errorf("failed to marshal tags for cache: %w", err)
- }
-
- // Cache for 10 minutes (600 seconds)
- ok := redisClient.Set(ctx, key, string(data), 10*time.Minute)
- if !ok {
- common.Warn("Failed to set tags cache")
- return fmt.Errorf("failed to set tags cache")
- }
-
- return nil
-}
-
// Knowledgebase type alias for entity.Knowledgebase
type Knowledgebase = entity.Knowledgebase
-// GetAllTagsInPortion returns all tag_kwd values and their occurrence counts
-// for documents belonging to the given kbIDs, aggregated across every tenant
-// index in tenantIDs — the same tenant scope TagQuery searches. The dataset
-// and chunk-search callers can supply authorized knowledgebases from multiple
-// tenants, so restricting the aggregation to a single tenant index would omit
-// tags that exist only in the other tenants' indices (leaving them absent from
-// allTags and scored with the 0.0001 fallback, which inflates their scores).
-func (s *MetadataService) GetAllTagsInPortion(ctx context.Context, tenantIDs []string, kbIDs []string) (map[string]float64, error) {
- if len(kbIDs) == 0 || len(tenantIDs) == 0 {
- return make(map[string]float64), nil
- }
-
- indexNames := make([]string, len(tenantIDs))
- for i, tenantID := range tenantIDs {
- indexNames[i] = fmt.Sprintf("ragflow_%s", tenantID)
- }
-
- searchReq := &types.SearchRequest{
- IndexNames: indexNames,
- KbIDs: kbIDs,
- Offset: 0,
- Limit: common.MAX_RESULT_WINDOW,
- SelectFields: []string{"tag_kwd"},
- }
-
- searchResp, err := s.docEngine.Search(ctx, searchReq)
- if err != nil {
- return nil, err
- }
-
- // Use GetAggregation for tag counting
- tagAgg := s.docEngine.GetAggregation(searchResp.Chunks, "tag_kwd")
- if len(tagAgg) == 0 {
- return make(map[string]float64), nil
- }
-
- // Calculate total count for proportion calculation
- total := 0
- for _, tc := range tagAgg {
- total += tc["count"].(int)
- }
- if total == 0 {
- return make(map[string]float64), nil
- }
-
- // Calculate tag proportions: (count + 1) / (total + 1000)
- S := 1000.0
- allTags := make(map[string]float64)
- for _, tc := range tagAgg {
- allTags[tc["key"].(string)] = float64(tc["count"].(int)+1) / (float64(total) + S)
- }
-
- return allTags, nil
-}
-
-// TagQuery returns weighted tag features for a question
-func (s *MetadataService) TagQuery(ctx context.Context, question string, tenantIDs []string, kbIDs []string, allTags map[string]float64, topnTags int) (map[string]float64, error) {
- if len(kbIDs) == 0 || len(allTags) == 0 || len(tenantIDs) == 0 {
- return make(map[string]float64), nil
- }
-
- // Build index names for all tenant IDs
- indexNames := make([]string, len(tenantIDs))
- for i, tenantID := range tenantIDs {
- indexNames[i] = fmt.Sprintf("ragflow_%s", tenantID)
- }
-
- // Process question to get match text
- queryBuilder := nlp.GetQueryBuilder()
- matchTextExpr, warns := queryBuilder.Question(question, "qa", 0.0) // min_match=0.0
- if len(warns) > 0 {
- common.Warn("TagQuery: failed to build match text", zap.Any("warnings", warns))
- return make(map[string]float64), nil
- }
- matchText := matchTextExpr.MatchingText
-
- common.Debug("TagQuery match_text", zap.String("match_text", matchText))
-
- // Search with match text to get relevant docs
- searchReq := &types.SearchRequest{
- IndexNames: indexNames,
- KbIDs: kbIDs,
- Offset: 0,
- Limit: 1000,
- MatchExprs: []interface{}{matchTextExpr},
- }
-
- searchResp, err := s.docEngine.Search(ctx, searchReq)
- if err != nil {
- return nil, err
- }
-
- // Use GetAggregation for tag counting
- aggs := s.docEngine.GetAggregation(searchResp.Chunks, "tag_kwd")
- if len(aggs) == 0 {
- return make(map[string]float64), nil
- }
-
- // Calculate total count
- cnt := 0
- for _, agg := range aggs {
- cnt += agg["count"].(int)
- }
- if cnt == 0 {
- return make(map[string]float64), nil
- }
-
- // Calculate weighted tag features
- // Formula: 0.1 * (c + 1) / (cnt + S) / max(1e-6, all_tags.get(a, 0.0001))
- S := 1000.0
- type tagScore struct {
- tag string
- score float64
- }
- scoredTags := make([]tagScore, 0, len(aggs))
-
- for _, agg := range aggs {
- tag := agg["key"].(string)
- c := agg["count"].(int)
- allTagValue := allTags[tag]
- if allTagValue <= 0 {
- allTagValue = 0.0001
+// tagSourceRefs returns the tag source files configured on the queried KBs,
+// deduplicated by (tenant, file). It mirrors Python's
+// rag/app/tag.py::label_question collecting tag_kb_ids from the queried KBs:
+// Python points at tag datasets, Go points at a tag source file (parser_config
+// tags.tag_file_id) that is indexed in memory instead of a dataset.
+//
+// The last non-nil KB is returned so the caller can read topn_tags from it, as
+// Python does with the loop's final kb.
+func tagSourceRefs(kbs []*Knowledgebase) ([]component.TagSourceRef, *Knowledgebase) {
+ seen := make(map[string]struct{}, len(kbs))
+ refs := make([]component.TagSourceRef, 0, len(kbs))
+ var last *Knowledgebase
+ for _, kb := range kbs {
+ if kb == nil {
+ continue
}
- score := 0.1 * float64(c+1) / (float64(cnt) + S) / max(1e-6, allTagValue)
- scoredTags = append(scoredTags, tagScore{tag: tag, score: score})
+ last = kb
+ fileID := component.TagFileIDFromParserConfig(map[string]any(kb.ParserConfig))
+ if fileID == "" {
+ continue
+ }
+ key := kb.TenantID + "\x00" + fileID
+ if _, dup := seen[key]; dup {
+ continue
+ }
+ seen[key] = struct{}{}
+ refs = append(refs, component.TagSourceRef{FileID: fileID, TenantID: kb.TenantID})
}
+ return refs, last
+}
- // Sort by score descending
- sort.Slice(scoredTags, func(i, j int) bool {
- return scoredTags[i].score > scoredTags[j].score
- })
-
- // Take top N tags and normalize dot notation
- resultTags := make(map[string]float64)
- for i := 0; i < topnTags && i < len(scoredTags); i++ {
- normalizedTag := strings.ReplaceAll(scoredTags[i].tag, ".", "_")
- score := max(1.0, scoredTags[i].score)
- if existing, ok := resultTags[normalizedTag]; !ok || score > existing {
- resultTags[normalizedTag] = score
+// topnTagsFromKB mirrors Python's parser_config.get("topn_tags", 3).
+// JSON-decoded numbers arrive as float64; also tolerate int/int64/json.Number.
+func topnTagsFromKB(kb *Knowledgebase) int {
+ topnTags := 3
+ if kb == nil || kb.ParserConfig == nil {
+ return topnTags
+ }
+ switch v := kb.ParserConfig["topn_tags"].(type) {
+ case float64:
+ topnTags = int(v)
+ case int:
+ topnTags = v
+ case int64:
+ topnTags = int(v)
+ case json.Number:
+ if n, err := v.Int64(); err == nil {
+ topnTags = int(n)
}
}
-
- return resultTags, nil
+ return topnTags
}
-// LabelQuestion returns rank features for a question based on the dataset's own
-// tags.
+// LabelQuestion returns weighted tag rank features for a question, the Go
+// equivalent of Python's rag/app/tag.py::label_question. Go has no tag
+// dataset, so the vocabulary comes from the KBs' tag source files
+// (parser_config tags.tag_file_id) indexed in memory: the question is matched
+// against the file's records and the background proportions (Python's
+// all_tags_in_portion) come from TagProportions. There is no tag_kwd column to
+// aggregate - auto-tagging writes tag_feas.
//
-// Flow:
-// 1. Use the queried KBs themselves as the tag source and search scope
-// 2. Try to get all_tags from cache (via GetTagsFromCache)
-// 3. If cache miss, call GetAllTagsInPortion and cache the result (via SetTagsToCache)
-// 4. Call TagQuery to get weighted tag features for the question
-//
-// The Go backend has no separate tag-library dataset as the Python backend
-// does. Instead the Go extractor (extractor_tag.go) writes tag_kwd onto each
-// chunk during ingestion, so the authoritative tag vocabulary lives on the
-// dataset's own chunks and is aggregated from the KBs being queried.
+// Logging: this runs once per retrieval, so the common no-tag-source case stays
+// at debug to avoid flooding the chat path; only a successful match is logged at
+// info, because that is the signal needed to confirm tagging took effect. The
+// question itself is not logged here - callers already log it and it is user
+// data; use common.IsDebugEnabled() below if it is ever needed.
func (s *MetadataService) LabelQuestion(ctx context.Context, question string, kbs []*Knowledgebase) map[string]float64 {
if len(kbs) == 0 || question == "" {
+ common.DebugCtx(ctx, "LabelQuestion skipped",
+ zap.Int("kbCount", len(kbs)), zap.Bool("emptyQuestion", question == ""))
return nil
}
-
- // Use the queried KBs themselves as both the tag source and the search
- // scope. Track the last KB (for tenant_id / topn_tags) and the unique
- // tenant IDs spanned by the KBs.
- var kbIDs []string
- var lastKB *Knowledgebase
- tenantIDSet := make(map[string]bool)
- for _, kb := range kbs {
- if kb == nil {
- continue
- }
- lastKB = kb
- kbIDs = append(kbIDs, kb.ID)
- if kb.TenantID != "" {
- tenantIDSet[kb.TenantID] = true
- }
- }
- if len(kbIDs) == 0 {
- return nil
- }
- uniqueTenantIDs := make([]string, 0, len(tenantIDSet))
- for tid := range tenantIDSet {
- uniqueTenantIDs = append(uniqueTenantIDs, tid)
- }
- if len(uniqueTenantIDs) == 0 {
+ refs, lastKB := tagSourceRefs(kbs)
+ if len(refs) == 0 {
+ // No tag source configured on any KB: the normal case, keep it quiet.
+ common.DebugCtx(ctx, "LabelQuestion skipped: no tag source configured",
+ zap.Int("kbCount", len(kbs)))
return nil
}
-
- // Aggregate tag_kwd across the dataset's own chunks (cached by KB set).
- allTags, err := GetTagsFromCache(ctx, kbIDs)
+ idx, err := component.LoadTagQueryIndex(ctx, refs)
if err != nil {
- common.Warn("Failed to get tags from cache", zap.Error(err))
- }
- if allTags == nil {
- // Cache miss - compute all_tags_in_portion
- allTags, err = s.GetAllTagsInPortion(ctx, uniqueTenantIDs, kbIDs)
- if err != nil {
- common.Warn("Failed to get all tags in portion", zap.Error(err))
- return nil
- }
- // Store in cache for future lookups
- if err = SetTagsToCache(ctx, kbIDs, allTags); err != nil {
- common.Warn("Failed to set tags cache", zap.Error(err))
- }
- }
-
- // No tag_kwd on the dataset's chunks means tagging is not in effect for
- // this query: return nil so the caller applies no tag boost (Python's
- // label_question returning None).
- if len(allTags) == 0 {
+ common.WarnCtx(ctx, "LabelQuestion: failed to load tag source index",
+ zap.Int("tagSources", len(refs)), zap.Error(err))
return nil
}
-
- // Get topn_tags from last KB's parser_config
- // JSON-decoded numbers arrive as float64; also tolerate int/int64/json.Number for safety
- topnTags := 3
- if lastKB != nil && lastKB.ParserConfig != nil {
- switch v := lastKB.ParserConfig["topn_tags"].(type) {
- case float64:
- topnTags = int(v)
- case int:
- topnTags = v
- case int64:
- topnTags = int(v)
- case json.Number:
- if n, err := v.Int64(); err == nil {
- topnTags = int(n)
- }
- }
- }
-
- // Query tags for the question across the dataset's own chunks.
- tagFeatures, err := s.TagQuery(ctx, question, uniqueTenantIDs, kbIDs, allTags, topnTags)
- if err != nil {
+ if idx == nil {
+ common.DebugCtx(ctx, "LabelQuestion: tag source index unavailable",
+ zap.Int("tagSources", len(refs)))
return nil
}
+ topN := topnTagsFromKB(lastKB)
+ // The index tokenizes the question with the analyzer it was built with, so
+ // retrieval cannot drift onto a different one.
+ tagFeatures := idx.MatchTagQuery(question, topN)
if len(tagFeatures) == 0 {
- // Tags configured but the question matched none - return empty map
+ // Tags configured but the question matched none - return an empty map
// (not nil) so the caller knows tagging was active for this dataset.
+ common.DebugCtx(ctx, "LabelQuestion: no tag matched",
+ zap.Int("tagSources", len(refs)), zap.Int("topnTags", topN))
return make(map[string]float64)
}
-
+ common.InfoCtx(ctx, "LabelQuestion result",
+ zap.Int("tagSources", len(refs)), zap.Int("topnTags", topN), zap.Any("labels", tagFeatures))
return tagFeatures
}
diff --git a/test/testcases/restful_api/test_datasets.py b/test/testcases/restful_api/test_datasets.py
index 4f53449ff4..067afe99e4 100644
--- a/test/testcases/restful_api/test_datasets.py
+++ b/test/testcases/restful_api/test_datasets.py
@@ -14,19 +14,19 @@
# limitations under the License.
#
-from concurrent.futures import ThreadPoolExecutor, as_completed
import os
import uuid
+from concurrent.futures import ThreadPoolExecutor, as_completed
import pytest
from configs import DATASET_NAME_LIMIT, DEFAULT_PARSER_CONFIG
+
from test.testcases.configs import INVALID_API_TOKEN, IS_GO_PROXY
from test.testcases.restful_api.helpers.assertions import assert_auth_error
from test.testcases.restful_api.helpers.client import RestClient
from test.testcases.utils import encode_avatar
from test.testcases.utils.file_utils import create_image_file, create_txt_file
-
ARGUMENT_ERROR_CODE = 102 if IS_GO_PROXY else 101
PARSER_ID_FIELD = "parser_id" if IS_GO_PROXY else "chunk_method"
@@ -2511,6 +2511,30 @@ def test_dataset_tags_and_aggregation(rest_client, create_dataset):
dataset_id = create_dataset("dataset_tags")
second_dataset_id = create_dataset("dataset_tags_second")
+ # The aggregation route is served by both backends, so it is asserted
+ # before the backend-specific tag list contract below.
+ aggregate_res = rest_client.get(
+ "/datasets/tags/aggregation",
+ params={"dataset_ids": f"{dataset_id},{second_dataset_id}"},
+ )
+ assert aggregate_res.status_code == 200
+ aggregate_payload = aggregate_res.json()
+ assert aggregate_payload["code"] in (0, 102), aggregate_payload
+
+ empty_aggregate_res = rest_client.get("/datasets/tags/aggregation")
+ assert empty_aggregate_res.status_code == 200
+ empty_aggregate_payload = empty_aggregate_res.json()
+ assert empty_aggregate_payload["code"] != 0, empty_aggregate_payload
+
+ if IS_GO_PROXY:
+ # Go keeps no tag dataset, so the per-dataset tag routes are not served
+ # at all; tagging is driven by the dataset's tag source file and only
+ # the aggregation route survives. Assert the contract that replaced the
+ # old 200 responses instead of the route's payload.
+ assert rest_client.get(f"/datasets/{dataset_id}/tags").status_code == 404
+ assert rest_client.get("/datasets/invalid_id/tags").status_code == 404
+ return
+
list_tags_res = rest_client.get(f"/datasets/{dataset_id}/tags")
assert list_tags_res.status_code == 200
list_tags_payload = list_tags_res.json()
@@ -2525,24 +2549,20 @@ def test_dataset_tags_and_aggregation(rest_client, create_dataset):
invalid_list_tags_payload = invalid_list_tags_res.json()
assert invalid_list_tags_payload["code"] != 0, invalid_list_tags_payload
- aggregate_res = rest_client.get(
- "/datasets/tags/aggregation",
- params={"dataset_ids": f"{dataset_id},{second_dataset_id}"},
- )
- assert aggregate_res.status_code == 200
- aggregate_payload = aggregate_res.json()
- assert aggregate_payload["code"] in (0, 102), aggregate_payload
-
- empty_aggregate_res = rest_client.get("/datasets/tags/aggregation")
- assert empty_aggregate_res.status_code == 200
- empty_aggregate_payload = empty_aggregate_res.json()
- assert empty_aggregate_payload["code"] != 0, empty_aggregate_payload
-
@pytest.mark.p2
def test_dataset_tags_delete_and_rename_validation(rest_client, create_dataset):
dataset_id = create_dataset("dataset_tag_mutation")
+ if IS_GO_PROXY:
+ # Same removal as above: with no tag dataset there is nothing to rename
+ # or delete, so both the validation cases and the invalid-dataset cases
+ # are now unrouted instead of argument errors.
+ for url in (f"/datasets/{dataset_id}/tags", "/datasets/invalid_id/tags"):
+ assert rest_client.delete(url, json={"tags": ["tag1"]}).status_code == 404
+ assert rest_client.put(url, json={"from_tag": "old", "to_tag": "new"}).status_code == 404
+ return
+
delete_missing_tags = rest_client.delete(f"/datasets/{dataset_id}/tags", json={})
assert delete_missing_tags.status_code == 200
delete_missing_tags_payload = delete_missing_tags.json()