WeKnora/internal/application/service/knowledge_process.go

4699 lines
182 KiB
Go
Raw Normal View History

refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
package service
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"sort"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/application/access"
"github.com/Tencent/WeKnora/internal/application/repository"
fix(summary): 坏 JSON 不再冒充文档摘要(截断/畸形 JSON 走失败路径,纯文本兜底保留) (#3769) * fix(summary): 坏 JSON 不再冒充文档摘要 非流式文档摘要(Chat)解析失败时原先把模型原文当摘要落库:被 MaxTokens 截断的半截 JSON 会写进 knowledges.description、置 SummaryStatus=Completed (Asynq 不再重试),同一段文本还会被 buildSummaryChunkContent 索引进 RAG。 - parseDocumentSummaryOutput 改为返回 (*documentSummaryResult, error): 回复形如 JSON(含 markdown 代码围栏)却解析失败、或解析成功但取不到 summary/gist 时返回 errSummaryOutputNotParsable,绝不回退成原文; 非 JSON 的纯文本仍走原有的原文兜底,自定义模板 / 老模型不受影响。 - validateSummaryOutput 复用 chatpipeline.IsLengthFinishReason, FinishReason 为 length 类取值时返回 errSummaryOutputTruncated。 - 两个 sentinel 经 getSummary 汇入既有失败路径(ProcessSummaryGeneration 的 handleRetryableSummaryFailure、RegenerateKnowledgeSummary 的 handleGenerationFailure):保留旧描述、置 pending/failed 交给 Asynq 重试, 不再以 Completed 落库。 测试:TestParseDocumentSummaryOutput 改为表驱动(截断 JSON、含裸换行 JSON、 无文本 JSON 必须报错且不能把原文当 Summary;纯文本兜底继续通过); TestValidateSummaryOutput 增加 length / max_tokens 截断用例; TestGetSummaryRejectsUnusableModelOutput 锁住 getSummary 的错误传播。 * fix(summary): length 截断判定收窄到 JSON 形状回复 非流式文档摘要在校验模型回复时先看 finish_reason:只要 provider 报告 length/max_tokens 就返回 errSummaryOutputTruncated。该判定不认识内容形状, 于是自定义纯文本模板一旦顶到输出预算,就从「截断但可用」变成重试直到 SummaryStatusFailed,与上一提交承诺的「非 JSON 的纯文本仍走原兜底」相反。 - validateSummaryOutput 恢复为只看内容是否为空;新增 validateStructuredSummaryDocument 供 getSummary 使用:先判形状再判 length,只有确实在产结构化摘要(能解析成对象/数组,或 { 开头、[ 开头接 对象/数组/字符串元素)且被预算截断时才返回 errSummaryOutputTruncated。 - 形状判定剥离 UTF-8 BOM、前后空白与一层 markdown 围栏后再尝试 json.Unmarshal;「[文档摘要] …」「[1] …」这类带方括号引用的纯文本不再被 误判成坏 JSON,而截断的 {summary: 与截断的 JSON 数组仍然报错。 - parseDocumentSummaryOutput 同步剥离 BOM:BOM 前缀的截断 JSON 之前会被 当成纯文本落库。 - 表格描述 / 列描述仍走 validateSummaryOutput,截断的描述照旧可索引。 --------- Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 17:21:01 +00:00
chatpipeline "github.com/Tencent/WeKnora/internal/application/service/chat_pipeline"
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
"github.com/Tencent/WeKnora/internal/application/service/retriever"
"github.com/Tencent/WeKnora/internal/common"
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
werrors "github.com/Tencent/WeKnora/internal/errors"
"github.com/Tencent/WeKnora/internal/infrastructure/chunker"
"github.com/Tencent/WeKnora/internal/infrastructure/docparser"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/asr"
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
"github.com/Tencent/WeKnora/internal/models/chat"
"github.com/Tencent/WeKnora/internal/models/embedding"
"github.com/Tencent/WeKnora/internal/searchutil"
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
"github.com/Tencent/WeKnora/internal/sourceloc"
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
"github.com/Tencent/WeKnora/internal/tracing/langfuse"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
secutils "github.com/Tencent/WeKnora/internal/utils"
"github.com/google/uuid"
"github.com/hibiken/asynq"
)
func (s *knowledgeService) cloneKnowledge(
ctx context.Context,
src *types.Knowledge,
targetKB *types.KnowledgeBase,
) (err error) {
sourceKB, err := knowledgeWriteKB(ctx, s.kbService, src)
if err != nil {
return err
}
if err := access.RequireKBTransfer(ctx, sourceKB, targetKB, access.KBTransferClone); err != nil {
return err
}
if src.ParseStatus != types.ParseStatusCompleted {
return fmt.Errorf("source knowledge %s is not completed", src.ID)
}
if _, err := s.transferChunks(ctx, src, sourceKB.ID); err != nil {
return err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
dst := &types.Knowledge{
ID: uuid.NewString(),
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
TenantID: targetKB.TenantID,
KnowledgeBaseID: targetKB.ID,
Type: src.Type,
Channel: src.Channel,
Title: src.Title,
Description: src.Description,
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
Profile: src.Profile.Clone(),
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
Source: src.Source,
ParseStatus: "processing",
EnableStatus: "disabled",
EmbeddingModelID: targetKB.EmbeddingModelID,
FileName: src.FileName,
FolderPath: src.FolderPath,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
FileType: src.FileType,
FileSize: src.FileSize,
FileHash: src.FileHash,
FilePath: src.FilePath,
StorageSize: 0,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
Metadata: src.Metadata,
CustomMetadata: src.CustomMetadata,
}
state := knowledgeTransferState{
TaskID: access.TransferTaskID(ctx),
Operation: access.KBTransferClone,
SourceKB: sourceKB.ID,
TargetKB: targetKB.ID,
SourceID: src.ID,
Phase: "cloning",
}
if err := setTransferState(dst, state); err != nil {
return err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
fix: deep-copy stored files and images when cloning a knowledge base Cloning a knowledge base previously copied only the storage path strings (knowledge.FilePath and chunk.ImageInfo.URL), so the source and the clone shared the same physical objects in the storage backend. Once the original file and extracted images are deleted on source removal, the clone is left with dangling references and its document and images become unreadable — data loss that occurs even for same-store clones. Add a CopyFile primitive to the FileService interface and implement it in every backend: server-side CopyObject on the object stores (s3/obs/cos/oss/tos/ks3/minio), io.Copy on local, and a no-op on dummy. Destinations use the knowledge-owned layout and reuse the existing path/object-key guards; a sentinel ErrCrossBackendCopy is returned when the source scheme does not match the backend. Use CopyFile to deep-copy the document file in cloneKnowledge and the extracted images in CloneChunk and cloneFAQKnowledgeBase via a shared cloneChunkImageInfo helper that deduplicates identical image URLs per clone and rewrites them to the new objects. Copied objects are cleaned up best-effort if a clone fails partway through. A clone-time preflight rejects cloning into a target bound to a different storage backend when the tenant pins providers via StorageEngineConfig. Adds unit tests for local CopyFile (independent copy survives source deletion, traversal rejection, cross-backend rejection), cloneChunkImageInfo (empty/multi/dedup/parse-failure/OriginalURL handling), and the storage provider preflight.
2026-06-02 11:25:38 +00:00
// Deep-copy the source document file into an object owned by the destination
// knowledge. Without this the clone only shares the source's storage path, so
// deleting the source knowledge would destroy the clone's file too. The new
// object is tracked for cleanup if the clone fails downstream.
var copiedFilePaths []string
if src.FilePath != "" {
srcKB, kbErr := s.kbService.GetKnowledgeBaseByID(ctx, src.KnowledgeBaseID)
if kbErr != nil {
return fmt.Errorf("clone knowledge: failed to load source knowledge base: %w", kbErr)
}
srcSvc := s.resolveFileServiceForPath(ctx, srcKB, src.FilePath)
dstSvc := s.resolveFileService(ctx, targetKB)
newPath, copyErr := copyOwnedObject(ctx, srcSvc, dstSvc, src.FilePath, targetKB.TenantID, dst.ID)
if copyErr != nil {
return fmt.Errorf("clone knowledge file copy failed: %w", copyErr)
}
dst.FilePath = newPath
copiedFilePaths = append(copiedFilePaths, newPath)
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
defer func() {
if err == nil {
return
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
stored, loadErr := s.repo.GetKnowledgeByID(ctx, dst.TenantID, dst.ID)
if errors.Is(loadErr, repository.ErrKnowledgeNotFound) {
cleanupCopiedObjects(ctx, s.resolveFileService(ctx, targetKB), copiedFilePaths)
return
}
// An uncertain save/read must not delete objects that may be referenced.
if loadErr != nil || stored == nil || validateTransferKnowledge(stored, targetKB) != nil {
return
}
marker, markerErr := transferState(stored)
if markerErr != nil || !matchesTransfer(ctx, marker, sourceKB, targetKB, access.KBTransferClone, src.ID, "") ||
stored.ParseStatus == types.ParseStatusCompleted {
return
}
before, after := *stored, *stored
after.ParseStatus = types.ParseStatusFailed
after.ErrorMessage = err.Error()
_ = s.repo.UpdateKnowledgeForTransfer(ctx, &before, &after)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}()
if err = s.repo.CreateKnowledge(ctx, dst); err != nil {
return err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// Create timestamps can be rounded by the database before the first CAS.
persisted, err := s.repo.GetKnowledgeByID(ctx, dst.TenantID, dst.ID)
if err != nil {
return err
}
if err := validateTransferKnowledge(persisted, targetKB); err != nil {
return err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
dst.UpdatedAt = persisted.UpdatedAt
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err = s.CloneChunk(ctx, src, dst); err != nil {
return err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
before := *dst
state.Phase = "done"
if err = setTransferState(dst, state); err != nil {
return err
}
dst.ParseStatus = types.ParseStatusCompleted
dst.EnableStatus = "enabled"
dst.StorageSize = src.StorageSize
return s.repo.UpdateKnowledgeForTransfer(ctx, &before, dst)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// processDocumentFromPassage handles asynchronous processing of text passages
func (s *knowledgeService) processDocumentFromPassage(ctx context.Context,
kb *types.KnowledgeBase, knowledge *types.Knowledge, passage []string,
) {
// Update status to processing
knowledge.ParseStatus = "processing"
knowledge.UpdatedAt = time.Now()
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
return
}
// Convert passages to chunks
chunks := make([]types.ParsedChunk, 0, len(passage))
start, end := 0, 0
for i, p := range passage {
if p == "" {
continue
}
end += len([]rune(p))
chunks = append(chunks, types.ParsedChunk{
Content: p,
Seq: i,
Start: start,
End: end,
})
start = end
}
// Process and store chunks
var opts ProcessChunksOptions
if kb.QuestionGenerationConfig != nil && kb.QuestionGenerationConfig.Enabled {
opts.EnableQuestionGeneration = true
opts.QuestionCount = kb.QuestionGenerationConfig.QuestionCount
if opts.QuestionCount <= 0 {
opts.QuestionCount = 3
}
}
if err := s.processChunks(ctx, kb, knowledge, chunks, opts); err != nil {
logger.Warnf(ctx, "process passages for knowledge %s: %v", knowledge.ID, err)
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// ProcessChunksOptions contains options for processing chunks
type ProcessChunksOptions struct {
EnableQuestionGeneration bool
QuestionCount int
EnableMultimodel bool
StoredImages []docparser.StoredImage
// ParentChunks holds parent chunk data when parent-child chunking is enabled.
// When set, the chunks passed to processChunks are child chunks, and each
// child's ParentIndex references an entry in this slice.
ParentChunks []types.ParsedParentChunk
Metadata map[string]string
}
// finalizeIndexedKnowledgeState makes a document retrievable as soon as chunks
// and indexes are persisted (enable_status=enabled), but it deliberately does
// NOT mark the row completed when enrichment is still expected. Whenever the
// document still has work to fan out — pending multimodal image tasks, or text
// chunks that feed summary/question/graph generation — parse_status stays
// "processing" so KnowledgePostProcess remains the single authority that drives
// processing → finalizing → completed. Marking the row completed here would make
// post-process hit its "non-processing status" guard and skip the summary
// fan-out, stranding summary_status on "pending" forever.
func finalizeIndexedKnowledgeState(
knowledge *types.Knowledge,
totalStorageSize int64,
textChunkCount int,
hasPendingMultimodal bool,
now time.Time,
) {
if hasPendingMultimodal || textChunkCount > 0 {
knowledge.ParseStatus = types.ParseStatusProcessing
knowledge.SummaryStatus = types.SummaryStatusNone
} else {
// No text chunks and no pending multimodal work: there is nothing for
// post-process to enrich, so complete immediately. This is the only
// route to 'completed' that bypasses FinalizeSubtask, so it has to
// clear error_message itself — otherwise a successfully indexed row
// keeps reporting a failure from an earlier attempt.
knowledge.ParseStatus = types.ParseStatusCompleted
knowledge.SummaryStatus = types.SummaryStatusNone
knowledge.ErrorMessage = ""
}
knowledge.EnableStatus = "enabled"
knowledge.StorageSize = totalStorageSize
knowledge.ProcessedAt = &now
knowledge.UpdatedAt = now
}
// markKnowledgeProcessing makes the top-level knowledge state describe the
// attempt that is starting now. Clearing error_message is part of that: the
// column is only meaningful for the attempt that produced it, so a row
// re-entering processing must not keep surfacing the previous attempt's
// failure while it is visibly running again.
func markKnowledgeProcessing(knowledge *types.Knowledge, now time.Time) {
knowledge.ParseStatus = types.ParseStatusProcessing
knowledge.ErrorMessage = ""
knowledge.UpdatedAt = now
}
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
// failKnowledgeOnEmbeddingModel records an unresolvable embedding model as this
// attempt's terminal state.
//
// It re-reads the row instead of trusting the entry guard, because resolving a
// model reads the database: a cancel or a ReplaceKnowledgeFile can land in the
// window between that guard and this write. Both would be clobbered otherwise —
// UpdateKnowledge is a full-row Save and file_path is not among the omitted
// columns, so a stale in-memory row would roll file_path back over the
// replacement and mark the replacement's live attempt failed.
func (s *knowledgeService) failKnowledgeOnEmbeddingModel(
ctx context.Context, kb *types.KnowledgeBase, knowledge *types.Knowledge, cause error,
) error {
return s.failKnowledgeAtEmbedding(ctx, kb, knowledge, werrors.ErrCodeEmbeddingProviderFail,
"failed to get embedding model", cause)
}
// failKnowledgeAtEmbedding records cause as this attempt's terminal state at
// the embedding stage; see failKnowledgeOnEmbeddingModel for the guards. It
// returns nil once the attempt is settled (failure recorded, or the row was
// cancelled / deleted / replaced) and an error when nothing could be
// recorded, so the task is retried instead of acked with the row in flight.
func (s *knowledgeService) failKnowledgeAtEmbedding(
ctx context.Context, kb *types.KnowledgeBase, knowledge *types.Knowledge, code, what string, cause error,
) error {
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
// A cancelled or expired context means the run was interrupted — the user
// cancelled (asynq CancelProcessing cancels the handler context), the
// worker was preempted, the process is shutting down. The model itself is
// not implicated, so recording "failed to get embedding model" would both
// mislabel the cause and overwrite the cancelled status the abort path
// just wrote. Leave the row to the abort path, or to the housekeeping
// sweep when nothing else claims it.
if ctx.Err() != nil || errors.Is(cause, context.Canceled) || errors.Is(cause, context.DeadlineExceeded) {
logger.Infof(ctx,
"%s interrupted for %s (%v); leaving parse status untouched",
what, knowledge.ID, cause)
return fmt.Errorf("%s: %w", what, cause)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
}
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
logger.Infof(ctx,
"Knowledge aborted (%s), not recording %q: %s", status, what, knowledge.ID)
return abortRetryErr(ctx, knowledge.ID, status)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
}
knowledge.ParseStatus = types.ParseStatusFailed
knowledge.ErrorMessage = fmt.Sprintf("%s: %v", what, cause)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
knowledge.UpdatedAt = time.Now()
if err := s.updateKnowledgeUnlessSourceReplaced(ctx, knowledge); err != nil {
logger.Errorf(ctx, "failed to persist %q for %s: %v", what, knowledge.ID, err)
return fmt.Errorf("persist %s: %w", what, err)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
}
s.beginStage(ctx, knowledge.ID, types.StageEmbedding, types.JSONMap{
"model_id": kb.EmbeddingModelID,
})
// The span's error_message is what the timeline renders, and its
// error_detail is withheld from non-admin responses — so carry the same
// text the document list shows rather than a fixed generic string.
s.failStage(ctx, knowledge.ID, types.StageEmbedding, code, knowledge.ErrorMessage, cause)
return nil
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
}
// buildSplitterConfigFromChunking normalizes effective chunking settings with
// the shared chunker defaults.
func buildSplitterConfigFromChunking(cc types.ChunkingConfig) chunker.SplitterConfig {
return chunker.NormalizeSplitterConfig(chunker.SplitterConfig{
ChunkSize: cc.ChunkSize,
ChunkOverlap: cc.ChunkOverlap,
Separators: cc.Separators,
Strategy: cc.Strategy,
TokenLimit: cc.TokenLimit,
Languages: cc.Languages,
})
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// buildParentChildConfigs derives parent and child SplitterConfig from ChunkingConfig.
// The base config (already validated with defaults) is used for separators and
// the splitting strategy. Strategy must be propagated: an empty Strategy resolves
// to the legacy tier (see resolveChainWithProfile), which never runs the heading
// splitter, so parent-child chunks would silently lose heading alignment and
// ContextHeader breadcrumbs regardless of the configured strategy.
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
func buildParentChildConfigs(cc types.ChunkingConfig, base chunker.SplitterConfig) (parent, child chunker.SplitterConfig) {
return chunker.DeriveParentChildConfigs(base, cc.ParentChunkSize, cc.ChildChunkSize)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// processChunks processes chunks and creates embeddings for knowledge content
func (s *knowledgeService) processChunks(ctx context.Context,
kb *types.KnowledgeBase, knowledge *types.Knowledge, chunks []types.ParsedChunk,
opts ...ProcessChunksOptions,
) error {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Get options
var options ProcessChunksOptions
if len(opts) > 0 {
options = opts[0]
}
// Parser output and manually supplied passages can contain malformed byte
// sequences. Clean them before logging, chunk persistence, or embedding;
// the embedding provider and tracing/database drivers expect valid UTF-8.
for i := range chunks {
chunks[i].Content = common.CleanInvalidUTF8(chunks[i].Content)
chunks[i].ContextHeader = common.CleanInvalidUTF8(chunks[i].ContextHeader)
for j := range chunks[i].Images {
chunks[i].Images[j].URL = common.CleanInvalidUTF8(chunks[i].Images[j].URL)
chunks[i].Images[j].Caption = common.CleanInvalidUTF8(chunks[i].Images[j].Caption)
chunks[i].Images[j].OCRText = common.CleanInvalidUTF8(chunks[i].Images[j].OCRText)
chunks[i].Images[j].OriginalURL = common.CleanInvalidUTF8(chunks[i].Images[j].OriginalURL)
}
}
for i := range options.ParentChunks {
options.ParentChunks[i].Content = common.CleanInvalidUTF8(options.ParentChunks[i].Content)
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// Check if knowledge is being deleted/cancelled before processing.
// Both statuses short-circuit identically here — there's nothing to clean
// up yet so the branch is purely "stop early".
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
logger.Infof(ctx, "Knowledge aborted (%s), skipping chunk processing: %s", status, knowledge.ID)
return abortRetryErr(ctx, knowledge.ID, status)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
if s.isKnowledgeSourceReplaced(ctx, knowledge) {
logger.Infof(ctx, "Knowledge source replaced, skipping chunk processing: %s", knowledge.ID)
return nil
}
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
// A reparse started after this run: the cleanup below would wipe the
// new attempt's chunks and the final save would put its status back.
if s.currentAttemptSuperseded(ctx, knowledge.ID) {
logger.Infof(ctx, "Parse attempt superseded, skipping chunk processing: %s", knowledge.ID)
return nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Get embedding model for vectorization — only needed when vector/keyword indexing is enabled
var embeddingModel embedding.Embedder
if kb.NeedsEmbeddingModel() {
var err error
embeddingModel, err = s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
if err != nil {
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
// Terminal for this attempt, and it has to be recorded as such.
// A KB that indexes vectors cannot proceed without an embedder;
// returning without a status leaves parse_status on "processing",
// so the row hangs until the housekeeping sweep fails it hours
// later with a generic "stuck in processing" message. Failing
// here names the real cause instead: a model row that was
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
// deleted or deactivated, or a configuration the embedder factory
// refuses. (Credential and connectivity problems surface later, on
// the first BatchIndex round-trip — resolving a model only reads
// the row and constructs a client.)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.GetLogger(ctx).WithField("error", err).Errorf("processChunks get embedding model failed")
return s.failKnowledgeOnEmbeddingModel(ctx, kb, knowledge, err)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
} else {
logger.Infof(ctx, "Vector/keyword indexing disabled for KB %s, skipping embedding model", kb.ID)
}
// Resolve the vector store before deleting anything: failing after the
// cleanup below would leave the document with neither old nor new chunks.
tenantInfo := ctx.Value(types.TenantInfoContextKey).(*types.Tenant)
retrieveEngine, err := retriever.CreateRetrieveEngineForKB(
ctx, s.retrieveEngine, s.ownership, tenantInfo.ID, kb.VectorStoreID)
if err != nil && embeddingModel != nil {
// Indexing below dereferences the engine; a nil one would panic.
logger.Errorf(ctx, "processChunks resolve vector store for KB %s failed: %v", kb.ID, err)
if errors.Is(err, retriever.ErrVectorStoreUnavailable) {
// The lookup failed, not the store: retry rather than fail.
return fmt.Errorf("resolve vector store: %w", err)
}
return s.failKnowledgeAtEmbedding(ctx, kb, knowledge, werrors.ErrCodeVectorStoreWriteFailed,
"failed to resolve vector store", err)
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// 幂等性处理:清理旧的chunks和索引数据,避免重复数据
logger.Infof(ctx, "Cleaning up existing chunks and index data for knowledge: %s", knowledge.ID)
// 删除旧的chunks
if err := s.chunkRepo.DeleteChunksByKnowledgeID(ctx, knowledge.TenantID, knowledge.ID); err != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Warnf(ctx, "Failed to delete existing chunks (may not exist): %v", err)
// 不返回错误,继续处理(可能没有旧数据)
}
// 删除旧的索引数据 — only when vector/keyword indexing is enabled
if embeddingModel != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err := retrieveEngine.DeleteByKnowledgeIDList(ctx, []string{knowledge.ID}, embeddingModel.GetDimensions(), knowledge.Type); err != nil {
logger.Warnf(ctx, "Failed to delete existing index data (may not exist): %v", err)
// 不返回错误,继续处理(可能没有旧数据)
} else {
logger.Infof(ctx, "Successfully deleted existing index data for knowledge: %s", knowledge.ID)
}
}
// 删除知识图谱数据(如果存在)
namespace := types.NameSpace{KnowledgeBase: knowledge.KnowledgeBaseID, Knowledge: knowledge.ID}
if err := s.graphEngine.DelGraph(ctx, []types.NameSpace{namespace}); err != nil {
logger.Warnf(ctx, "Failed to delete existing graph data (may not exist): %v", err)
// 不返回错误,继续处理
}
logger.Infof(ctx, "Cleanup completed, starting to process new chunks")
// ========== DocReader 解析结果日志 ==========
logger.Infof(ctx, "[DocReader] ========== 解析结果概览 ==========")
logger.Infof(ctx, "[DocReader] 知识ID: %s, 知识库ID: %s", knowledge.ID, knowledge.KnowledgeBaseID)
logger.Infof(ctx, "[DocReader] 总Chunk数量: %d", len(chunks))
// 统计图片信息
totalImages := 0
chunksWithImages := 0
for _, chunkData := range chunks {
if len(chunkData.Images) > 0 {
chunksWithImages++
totalImages += len(chunkData.Images)
}
}
logger.Infof(ctx, "[DocReader] 包含图片的Chunk数: %d, 总图片数: %d", chunksWithImages, totalImages)
// 打印每个Chunk的详细信息
for idx, chunkData := range chunks {
contentPreview := chunkData.Content
if len(contentPreview) > 200 {
contentPreview = contentPreview[:200] + "..."
}
logger.Infof(ctx, "[DocReader] Chunk #%d (seq=%d): 内容长度=%d, 图片数=%d, 范围=[%d-%d]",
idx, chunkData.Seq, len(chunkData.Content), len(chunkData.Images), chunkData.Start, chunkData.End)
logger.Debugf(ctx, "[DocReader] Chunk #%d 内容预览: %s", idx, contentPreview)
// 打印图片详细信息
for imgIdx, img := range chunkData.Images {
logger.Infof(ctx, "[DocReader] 图片 #%d: URL=%s", imgIdx, img.URL)
logger.Infof(ctx, "[DocReader] 图片 #%d: OriginalURL=%s", imgIdx, img.OriginalURL)
if img.Caption != "" {
captionPreview := img.Caption
if len(captionPreview) > 100 {
captionPreview = captionPreview[:100] + "..."
}
logger.Infof(ctx, "[DocReader] 图片 #%d: Caption=%s", imgIdx, captionPreview)
}
if img.OCRText != "" {
ocrPreview := img.OCRText
if len(ocrPreview) > 100 {
ocrPreview = ocrPreview[:100] + "..."
}
logger.Infof(ctx, "[DocReader] 图片 #%d: OCRText=%s", imgIdx, ocrPreview)
}
logger.Infof(ctx, "[DocReader] 图片 #%d: 位置=[%d-%d]", imgIdx, img.Start, img.End)
}
}
logger.Infof(ctx, "[DocReader] ========== 解析结果概览结束 ==========")
// Create chunk objects from proto chunks
maxSeq := 0
// 统计图片相关的子Chunk数量,用于扩展insertChunks的容量
imageChunkCount := 0
for _, chunkData := range chunks {
if len(chunkData.Images) > 0 {
// 为每个图片的OCR和Caption分别创建一个Chunk
imageChunkCount += len(chunkData.Images) * 2
}
if int(chunkData.Seq) > maxSeq {
maxSeq = int(chunkData.Seq)
}
}
// === Parent-Child Chunking: create parent chunks first ===
hasParentChild := len(options.ParentChunks) > 0
var parentDBChunks []*types.Chunk // indexed by ParsedParentChunk position
if hasParentChild {
parentDBChunks = make([]*types.Chunk, len(options.ParentChunks))
for i, pc := range options.ParentChunks {
parentDBChunks[i] = &types.Chunk{
ID: uuid.New().String(),
TenantID: knowledge.TenantID,
KnowledgeID: knowledge.ID,
KnowledgeBaseID: knowledge.KnowledgeBaseID,
Content: pc.Content,
ChunkIndex: pc.Seq,
IsEnabled: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
StartAt: pc.Start,
EndAt: pc.End,
ChunkType: types.ChunkTypeParentText,
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
SourceLocators: pc.SourceLocators,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
}
// Set prev/next links for parent chunks
for i := range parentDBChunks {
if i > 0 {
parentDBChunks[i-1].NextChunkID = parentDBChunks[i].ID
parentDBChunks[i].PreChunkID = parentDBChunks[i-1].ID
}
}
logger.Infof(ctx, "Created %d parent chunks for parent-child strategy", len(parentDBChunks))
}
// 重新分配容量,考虑图片相关的Chunk + parent chunks
parentCount := len(options.ParentChunks)
insertChunks := make([]*types.Chunk, 0, len(chunks)+imageChunkCount+parentCount)
// Add parent chunks first (they go into DB but NOT into the vector index)
if hasParentChild {
insertChunks = append(insertChunks, parentDBChunks...)
}
for idx, chunkData := range chunks {
if strings.TrimSpace(chunkData.Content) == "" {
continue
}
// 创建主文本Chunk
textChunk := &types.Chunk{
ID: uuid.New().String(),
TenantID: knowledge.TenantID,
KnowledgeID: knowledge.ID,
KnowledgeBaseID: knowledge.KnowledgeBaseID,
Content: chunkData.Content,
ContextHeader: chunkData.ContextHeader,
ChunkIndex: int(chunkData.Seq),
IsEnabled: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
StartAt: int(chunkData.Start),
EndAt: int(chunkData.End),
ChunkType: types.ChunkTypeText,
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
SourceLocators: chunkData.SourceLocators,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// Wire up ParentChunkID for child chunks
if hasParentChild && chunkData.ParentIndex >= 0 && chunkData.ParentIndex < len(parentDBChunks) {
textChunk.ParentChunkID = parentDBChunks[chunkData.ParentIndex].ID
}
chunks[idx].ChunkID = textChunk.ID
insertChunks = append(insertChunks, textChunk)
}
// Sort chunks by index for proper ordering
sort.Slice(insertChunks, func(i, j int) bool {
return insertChunks[i].ChunkIndex < insertChunks[j].ChunkIndex
})
// Collect retrievable text chunks only. ParentChunkID only controls parent expansion after retrieval.
// When ParentChunkID is empty, retrieval keeps the standalone child content without loading a parent.
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
textChunks := make([]*types.Chunk, 0, len(chunks))
for _, chunk := range insertChunks {
if chunk.ChunkType == types.ChunkTypeText {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
textChunks = append(textChunks, chunk)
}
}
// 设置文本Chunk之间的前后关系 (skip if parent-child, children don't need prev/next links)
if !hasParentChild {
for i, chunk := range textChunks {
if i > 0 {
textChunks[i-1].NextChunkID = chunk.ID
}
if i < len(textChunks)-1 {
textChunks[i+1].PreChunkID = chunk.ID
}
}
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// Check if knowledge is being deleted/cancelled before writing chunks.
// Nothing has been persisted yet, so both branches just bail.
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
logger.Infof(ctx, "Knowledge aborted (%s), skipping chunk write: %s", status, knowledge.ID)
return abortRetryErr(ctx, knowledge.ID, status)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
if s.isKnowledgeSourceReplaced(ctx, knowledge) {
logger.Infof(ctx, "Knowledge source replaced, skipping chunk write: %s", knowledge.ID)
return nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Save chunks to database — ALWAYS, regardless of indexing strategy.
// Chunks are needed for wiki generation, graph extraction, and summary generation
// even when vector/keyword indexing is disabled.
fix(knowledge): close root span on terminal state, enrich stage metadata The root span created by OpenAttempt was never closed: PostProcess only ended the postprocess stage, so the root row stayed at status=running forever even after parse_status flipped to completed/failed. The timeline rendered "进行中" indefinitely on the root, defeating the whole "is the document done" question the timeline is meant to answer. - SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg): closes the root row idempotently. Re-closing a terminal root no-ops so success / cascade-fail / dead-letter paths can fire without coordination. - PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess) on the success path. Async downstream work (summary/question/wiki/ graph) still records its own spans; their completion extends the trace's wall-clock end-time but doesn't reopen the root. - FailSpan auto-closes the root when a MAIN pipeline stage fails (docreader / chunking / embedding / multimodal / postprocess). Cascade-cancelled siblings stay closed-with-the-cascade as before. - Dead-letter callback (router/task.go) accepts the SpanTracker via DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a document-related task exhausts retries. The probe payload now extracts the Attempt field that Document/Manual/PostProcess payloads already thread through. Stage spans were also being recorded with nil input/output, leaving the new detail panel with timestamps only. Each Begin/End site now emits useful work metrics: - DocReader input: file_name, file_type, is_url, url output: text_length, images_found, is_audio, pages - Chunking input: chunks_planned output: chunks_written, total_text_chars - Embedding input: chunks_to_embed, model_id, dim output: vectors_written, storage_bytes - Multimodal input: image_count, enable_ocr, enable_caption - PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph i18n: add knowledgeStages.root ("Knowledge processing") so the UI can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
s.beginStage(ctx, knowledge.ID, types.StageChunking, types.JSONMap{
"chunks_planned": len(insertChunks),
})
if err := s.chunkRepo.CreateChunks(ctx, insertChunks); err != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
knowledge.ParseStatus = types.ParseStatusFailed
knowledge.ErrorMessage = err.Error()
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
s.failStage(ctx, knowledge.ID, types.StageChunking,
werrors.ErrCodeChunkingFailed, "create chunks failed", err)
return nil
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
fix(knowledge): close root span on terminal state, enrich stage metadata The root span created by OpenAttempt was never closed: PostProcess only ended the postprocess stage, so the root row stayed at status=running forever even after parse_status flipped to completed/failed. The timeline rendered "进行中" indefinitely on the root, defeating the whole "is the document done" question the timeline is meant to answer. - SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg): closes the root row idempotently. Re-closing a terminal root no-ops so success / cascade-fail / dead-letter paths can fire without coordination. - PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess) on the success path. Async downstream work (summary/question/wiki/ graph) still records its own spans; their completion extends the trace's wall-clock end-time but doesn't reopen the root. - FailSpan auto-closes the root when a MAIN pipeline stage fails (docreader / chunking / embedding / multimodal / postprocess). Cascade-cancelled siblings stay closed-with-the-cascade as before. - Dead-letter callback (router/task.go) accepts the SpanTracker via DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a document-related task exhausts retries. The probe payload now extracts the Attempt field that Document/Manual/PostProcess payloads already thread through. Stage spans were also being recorded with nil input/output, leaving the new detail panel with timestamps only. Each Begin/End site now emits useful work metrics: - DocReader input: file_name, file_type, is_url, url output: text_length, images_found, is_audio, pages - Chunking input: chunks_planned output: chunks_written, total_text_chars - Embedding input: chunks_to_embed, model_id, dim output: vectors_written, storage_bytes - Multimodal input: image_count, enable_ocr, enable_caption - PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph i18n: add knowledgeStages.root ("Knowledge processing") so the UI can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
totalChunkChars := 0
for _, c := range insertChunks {
totalChunkChars += len(c.Content)
}
s.endStage(ctx, knowledge.ID, types.StageChunking, types.JSONMap{
"chunks_written": len(insertChunks),
"total_text_chars": totalChunkChars,
})
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Create index information and perform vector indexing — only when vector/keyword is enabled.
// Chunks are ALWAYS saved to DB (above) because wiki and graph need them even without vector indexing.
var totalStorageSize int64
if kb.NeedsEmbeddingModel() && embeddingModel != nil {
fix(knowledge): close root span on terminal state, enrich stage metadata The root span created by OpenAttempt was never closed: PostProcess only ended the postprocess stage, so the root row stayed at status=running forever even after parse_status flipped to completed/failed. The timeline rendered "进行中" indefinitely on the root, defeating the whole "is the document done" question the timeline is meant to answer. - SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg): closes the root row idempotently. Re-closing a terminal root no-ops so success / cascade-fail / dead-letter paths can fire without coordination. - PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess) on the success path. Async downstream work (summary/question/wiki/ graph) still records its own spans; their completion extends the trace's wall-clock end-time but doesn't reopen the root. - FailSpan auto-closes the root when a MAIN pipeline stage fails (docreader / chunking / embedding / multimodal / postprocess). Cascade-cancelled siblings stay closed-with-the-cascade as before. - Dead-letter callback (router/task.go) accepts the SpanTracker via DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a document-related task exhausts retries. The probe payload now extracts the Attempt field that Document/Manual/PostProcess payloads already thread through. Stage spans were also being recorded with nil input/output, leaving the new detail panel with timestamps only. Each Begin/End site now emits useful work metrics: - DocReader input: file_name, file_type, is_url, url output: text_length, images_found, is_audio, pages - Chunking input: chunks_planned output: chunks_written, total_text_chars - Embedding input: chunks_to_embed, model_id, dim output: vectors_written, storage_bytes - Multimodal input: image_count, enable_ocr, enable_caption - PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph i18n: add knowledgeStages.root ("Knowledge processing") so the UI can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
embedInput := types.JSONMap{
"chunks_to_embed": len(textChunks),
"model_id": kb.EmbeddingModelID,
}
if dim := embeddingModel.GetDimensions(); dim > 0 {
embedInput["dim"] = dim
}
s.beginStage(ctx, knowledge.ID, types.StageEmbedding, embedInput)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Create index information — only for child/flat chunks, NOT parent chunks.
// Parent chunks are stored for context retrieval but do not need vector embeddings.
// Prepend the document title to improve semantic alignment between
// question-style queries and statement-style chunk content.
indexInfoList := make([]*types.IndexInfo, 0, len(textChunks))
for _, chunk := range textChunks {
// chunk.EmbeddingContent prepends ContextHeader (heading breadcrumb)
// when the chunker populated it during Tier-1 splitting; falls back
// to plain Content otherwise. The document title sits outermost;
// custom metadata remains document-scoped model context.
indexContent := buildKnowledgeIndexContent(knowledge, chunk.EmbeddingContent())
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
indexInfoList = append(indexInfoList, &types.IndexInfo{
Content: indexContent,
SourceID: chunk.ID,
SourceType: types.ChunkSourceType,
ChunkID: chunk.ID,
KnowledgeID: knowledge.ID,
KnowledgeBaseID: knowledge.KnowledgeBaseID,
IsEnabled: true,
})
}
// Calculate storage size required for embeddings
totalStorageSize = retrieveEngine.EstimateStorageSize(ctx, embeddingModel, indexInfoList)
if tenantInfo.StorageQuota > 0 {
// Re-fetch tenant storage information
tenantInfo, err = s.tenantRepo.GetTenantByID(ctx, tenantInfo.ID)
if err != nil {
knowledge.ParseStatus = types.ParseStatusFailed
knowledge.ErrorMessage = err.Error()
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// Check if there's enough storage quota available
if tenantInfo.StorageUsed+totalStorageSize > tenantInfo.StorageQuota {
knowledge.ParseStatus = types.ParseStatusFailed
knowledge.ErrorMessage = "存储空间不足"
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// Check again before batch indexing (heavy operation).
// deleting → row is going away anyway, drop the chunks we just wrote.
// cancelled → user wants to keep what was already persisted, just stop.
if s.isKnowledgeSourceReplaced(ctx, knowledge) {
logger.Infof(ctx, "Knowledge source replaced, skipping indexing: %s", knowledge.ID)
return nil
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
logger.Infof(ctx, "Knowledge aborted (%s) before indexing: %s", status, knowledge.ID)
if status == types.ParseStatusDeleting {
if err := s.chunkRepo.DeleteChunksByKnowledgeID(ctx, knowledge.TenantID, knowledge.ID); err != nil {
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
logger.Warnf(ctx, "Failed to cleanup chunks after deletion detected: %v", err)
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
return abortRetryErr(ctx, knowledge.ID, status)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
err = retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfoList)
if err != nil {
// Embedding and vector-store errors are often transient. While the
// task has attempts left, leave the row processing and hand the
// error to the queue so the idempotent parse runs again; only the
// final attempt (or a caller without a retry loop) records failure.
willRetry := summaryTaskWillRetry(ctx)
if !willRetry {
knowledge.ParseStatus = types.ParseStatusFailed
knowledge.ErrorMessage = err.Error()
knowledge.UpdatedAt = time.Now()
if updateErr := s.repo.UpdateKnowledge(ctx, knowledge); updateErr != nil {
logger.Errorf(ctx, "Update knowledge status failed after batch index error: %v", updateErr)
}
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// delete failed chunks
if err := s.chunkRepo.DeleteChunksByKnowledgeID(ctx, knowledge.TenantID, knowledge.ID); err != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Errorf(ctx, "Delete chunks failed: %v", err)
}
// delete index
if err := retrieveEngine.DeleteByKnowledgeIDList(
ctx, []string{knowledge.ID}, embeddingModel.GetDimensions(), kb.Type,
); err != nil {
logger.Errorf(ctx, "Delete index failed: %v", err)
}
// Map vector store / embedding rate-limit errors to a
// stable code so the UI can offer "retry later" hints.
code := werrors.ErrCodeVectorStoreWriteFailed
if isLikelyRateLimitError(err) {
code = werrors.ErrCodeEmbeddingRateLimit
}
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
s.failStage(ctx, knowledge.ID, types.StageEmbedding,
code, "batch index failed", err)
if willRetry {
return fmt.Errorf("batch index: %w", err)
}
return nil
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
logger.GetLogger(ctx).Infof("processChunks batch index successfully, with %d index", len(indexInfoList))
fix(knowledge): close root span on terminal state, enrich stage metadata The root span created by OpenAttempt was never closed: PostProcess only ended the postprocess stage, so the root row stayed at status=running forever even after parse_status flipped to completed/failed. The timeline rendered "进行中" indefinitely on the root, defeating the whole "is the document done" question the timeline is meant to answer. - SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg): closes the root row idempotently. Re-closing a terminal root no-ops so success / cascade-fail / dead-letter paths can fire without coordination. - PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess) on the success path. Async downstream work (summary/question/wiki/ graph) still records its own spans; their completion extends the trace's wall-clock end-time but doesn't reopen the root. - FailSpan auto-closes the root when a MAIN pipeline stage fails (docreader / chunking / embedding / multimodal / postprocess). Cascade-cancelled siblings stay closed-with-the-cascade as before. - Dead-letter callback (router/task.go) accepts the SpanTracker via DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a document-related task exhausts retries. The probe payload now extracts the Attempt field that Document/Manual/PostProcess payloads already thread through. Stage spans were also being recorded with nil input/output, leaving the new detail panel with timestamps only. Each Begin/End site now emits useful work metrics: - DocReader input: file_name, file_type, is_url, url output: text_length, images_found, is_audio, pages - Chunking input: chunks_planned output: chunks_written, total_text_chars - Embedding input: chunks_to_embed, model_id, dim output: vectors_written, storage_bytes - Multimodal input: image_count, enable_ocr, enable_caption - PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph i18n: add knowledgeStages.root ("Knowledge processing") so the UI can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
s.endStage(ctx, knowledge.ID, types.StageEmbedding, types.JSONMap{
"vectors_written": len(indexInfoList),
"storage_bytes": totalStorageSize,
})
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// Final check before marking as completed.
// deleting → drop chunks+index we just wrote.
// cancelled → keep persisted data; the row stays in cancelled status
// and downstream stages skip via the entry guards.
if s.isKnowledgeSourceReplaced(ctx, knowledge) {
logger.Infof(ctx, "Knowledge source replaced, skipping completion: %s", knowledge.ID)
return nil
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
logger.Infof(ctx, "Knowledge aborted (%s) after indexing: %s", status, knowledge.ID)
if status == types.ParseStatusDeleting {
if err := s.chunkRepo.DeleteChunksByKnowledgeID(ctx, knowledge.TenantID, knowledge.ID); err != nil {
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
logger.Warnf(ctx, "Failed to cleanup chunks after deletion detected: %v", err)
}
if err := retrieveEngine.DeleteByKnowledgeIDList(ctx, []string{knowledge.ID}, embeddingModel.GetDimensions(), kb.Type); err != nil {
logger.Warnf(ctx, "Failed to cleanup index after deletion detected: %v", err)
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
return abortRetryErr(ctx, knowledge.ID, status)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
} else {
logger.Infof(ctx, "Vector/keyword indexing disabled for KB %s, skipping BatchIndex", kb.ID)
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
s.skipStage(ctx, knowledge.ID, types.StageEmbedding, "skipped")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// Check if this document has extracted images that will be processed asynchronously
isImage := IsImageType(knowledge.FileType)
isVideo := IsVideoType(knowledge.FileType)
pendingMultimodal := isImage && options.EnableMultimodel && len(options.StoredImages) > 0
pendingPDFMultimodal := !isImage && !isVideo && options.EnableMultimodel && len(options.StoredImages) > 0
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if s.currentAttemptSuperseded(ctx, knowledge.ID) {
logger.Infof(ctx, "Parse attempt superseded, skipping completion: %s", knowledge.ID)
return nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
now := time.Now()
finalizeIndexedKnowledgeState(
knowledge,
totalStorageSize,
len(textChunks),
pendingMultimodal || pendingPDFMultimodal,
now,
)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err := s.updateKnowledgeUnlessSourceReplaced(ctx, knowledge); err != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.GetLogger(ctx).WithField("error", err).Errorf("processChunks update knowledge failed")
}
// Enqueue multimodal tasks for images (async, non-blocking)
if options.EnableMultimodel && len(options.StoredImages) > 0 {
feat(gallery): add an image gallery tab with schema-driven filters (#3694) * feat(image): observe image attributes and let the policy decide OCR Describe each image with the VLM as before, but ask it to also observe two attributes about the image in the same round — how much body text it carries (contain.text) and whether it presents data visually (contain.data_visual) — then let a small pure function decide whether that image is worth a second, separate OCR round. Per-class OCR was the first shape of this idea; a class (chart / photo / logo) is only an indirect proxy for 'is there text worth reading here', and the class table has to grow whenever a new kind of image shows up. The decision actually needs the observed attributes, so it reads them directly, and the attribute set is a backend registry row rather than a new class. The observation and the caption share one VLM call; OCR stays a separate call (prompt isolation, see #3291). An attribute the model does not answer for is left absent rather than filled with a conservative default, so the trace never claims an observation that did not happen, and an incomplete observation falls back to the on_unobserved policy (OCR still runs). The registry also carries the panel's display text, so a new attribute needs no frontend change. Off by default: image_attrs_enabled=false keeps today's behaviour (one caption and one OCR per image). KB config: image_processing_config.image_attrs_enabled / image_actions; per-upload override via process_config. Registry: GET /api/v1/image-attrs/schema. * feat(gallery): add image gallery tab with schema-driven filters Adds a 4th knowledge-base tab parallel to Documents/Wiki/Graph that browses every image asset in a KB. Backend: - GET /api/v1/knowledge-bases/:id/images lists image assets projected from chunks.image_info, with keyword (caption/OCR), multi-value attribute (attr_<name>=<value>), is_enabled and sort filters applied in memory, plus pagination. - Resolves the source knowledge item title (SourceName) via a batched GetKnowledgeBatch so the viewer can show a human-readable source. Frontend: - ImageGallery.vue: thumbnail grid + search/sort + schema-driven filter panel (from GET /image-attrs/schema) + single-image viewer with prev/next, attributes/caption/OCR/source. - Wired as the gallery tab in KnowledgeBase.vue; i18n keys in all 5 locales. * feat(gallery): drive filters/search/sort from a configurable attribute contract The gallery UI is no longer hardcoded: it renders from a self-describing contract served by GET /knowledge-bases/:id/gallery-config (live attribute sources, every attribute's definition with usage flags merged across the config tiers, and the caller's search activation state). - Attribute sources form an open registry (types.RegisterGalleryAttrSource); a builtin source models caption/ocr_text/timestamps/enabled so the gallery has zero special cases. - Usage resolution: user > KB > system > source, field by field; the system tier lives in system_settings (gallery.policy, JSON, no rebuild), the KB tier slot is wired in the engine but not stored yet. - Search activation is the user's own record: mode (all|custom) plus per-field on/off in users.preferences.gallery; source declarations never set defaults (unrecorded = off in custom mode). - image_info is read through a gallery-local struct, removing the compile dependency on the attribute-pipeline types; the gallery builds and runs with or without that feature deployed. - ListImages validates search_in / sort_by / attr_filters against the contract; ineligible fields are dropped, not served. * fix(frontend): inline the shared graph-drawer stylesheet (@import instead of <style src>) plugin-vue 6.0.6 keys unscoped src-style descriptors by the imported file path, so AgentStreamDisplay.vue and WikiBrowser.vue — both importing components/css/wiki-graph-drawer.less — overwrite each other during the build and the second one crashes with "reading 'scoped'". Adding the gallery changed the module order enough to make the collision hit every time. Inlining the same stylesheet keeps the emitted CSS identical and removes the shared descriptor key. * feat(gallery): render attributes from short labels with descriptions in tooltips A source could only say one thing about a value, so the filter panel had to put a full sentence inside a checkbox. Attributes and their values now carry two pieces of text: a short label for the space-constrained controls (checkbox, search field, sort option) and a description for wherever there is room (tooltip, detail panel). The contract's value list becomes an array of {value, label, description}, and the display helpers resolve each field separately: the gallery stamps the short name on a control and moves the sentence into a tooltip. Translation overlays are looked up per field, so a source that ships no gallery-specific text still picks up the attribute pipeline's own wording. * fix(gallery): let locale text win over the contract's wording The filter panel read the backend's own label before asking the locale, so a translated value never got a chance: the contract ships its own default-language wording, and it shadowed the overlay for every locale. Built keys were also off by a segment — imageAttr.<name> has to be imageAttr.<name>.label, and the gallery's own keys live under knowledgeEditor.wikiBrowser.gallery.attr — so builtin and system attributes fell through to English on a Chinese UI. * feat(gallery): top bar layout, pinned panels and per-value verdicts The toolbar moves onto its own row above the grid, so the controls no longer eat into the space the images are there for: search box, the two scope switches, sort field and direction, and the result count all sit in one flex row. The settings behind them are no longer inline either — each opens as a popover under its control and can be pinned to a right-hand rail, where the two panels take turns as tabs instead of both claiming width at once. Filtering gains a third state per attribute value. Where a value could only be picked or not picked, it can now be "off" (hide those images), "on" (show them whatever else says) or neutral (leave them alone), which is what lets one attribute's rules talk about an image another attribute tried to hide without the pair of them cancelling each other out: a forced display outranks a forced hide, and anything no rule speaks about stays visible. The switch that used to only exist inside the panel now has a toolbar home as well. "筛选:全显示" genuinely drops the attribute constraint instead of imposing it against a panel the user cannot see. Filtering used to empty the list the moment it was switched on. Any image whose attribute was never observed — every image ingested before the attribute pipeline existed — read as a mismatch for every filter, which is not narrowing a list but losing it. Absence now stays silence: an attribute no image carries places no constraint on it, until the pipeline catches up and fills the value in. Co-authored-by: WorkBuddy * feat(gallery): expose the image attribute pipeline as a gallery source The gallery's contract resolved to a single source, so the filter panel could only offer "Enabled" while the attributes the observe-and-describe pipeline fills in — contain.text, contain.data_visual — never reached the UI. The registry is a gallery attribute source like any other: every attribute it declares is offered to the gallery, filterable by default, with the config tiers able to override the usage flags at runtime. The registration lives in the attribute pipeline's own commit; this branch carried an earlier, squapshot of that work which predated the split of an attribute value into a short label and a description, so the registry's value shape and this file have been brought in line with it. Both PRs now hold byte-identical copies of the source hook, which is what lets either one land first and the other merge cleanly afterwards. Co-authored-by: WorkBuddy * fix(gallery): viewer race, pin icon, panel anchoring and scope wording Opening the viewer rendered the img element with the previous or empty source while the proxy fetch was still producing a blob, and the error that empty source fired locked the viewer in its failure state even after the real image arrived. The resolved source now lands before the flag is consulted, and a token keeps a slow fetch of one image from overwriting a faster one that navigated past it. The pin button drew nothing: TDesign has no "pushpin" glyph, so the button rendered as an empty shell. It now uses pin / pin-filled, keeps its place beside the tab bar, and a pinned rail assigns its columns explicitly — the panel precedes the main section in the DOM, so leaving the grid to source order handed the wide column to the panel and squeezed the images into the rail. The floating panel no longer appears at a hardcoded offset: it anchors just below the arrow that summoned it, the arrow flips up while its panel is out, a second press retracts, and any click elsewhere in the toolbar closes it. When a rail is pinned the arrows turn to the requested tab instead of spawning a second surface. The scope words (全部 / 全显示 / 自定义) become plain status text rather than a second dropdown — they name the current mode, and only the arrow beside them opens the panel that changes it. Co-authored-by: WorkBuddy * fix(web): align the OCR-on-unobserved switch with the other setting rows The switch sat bare inside its setting-row while every other switch on the page is wrapped in setting-control, which is what reserves the right column and centers the control vertically. With the row laid out from the top, the bare switch hugged the row's upper edge and crowded the description text — visibly out of place next to its neighbors. Wrapping it in setting-control gives it the same right-aligned, centered slot as the rest. Co-authored-by: WorkBuddy * fix(web): move the OCR-on-unobserved row out of the vertical schema row The row lived inside setting-row-vertical, whose descendant rule stretches every setting-info and setting-control beneath it to 100% width. Two full-width flex children side by side cannot fit, so the control overflowed the container and the switch landed past the right edge — visibly further out than the switch on the row above. The row and its note now sit beside the vertical block instead of inside it, under their own condition, so the switch shares the ordinary row layout and its right edge lines up with the "image attribute observation" switch above. Co-authored-by: WorkBuddy * fix(gallery): applying a verdict now activates the filter scope Setting an off/on verdict while the panel's master switch was off silently ignored it: buildParams only attaches attr_rules in custom scope, and setVerdict never flipped the scope. A verdict the user just expressed now switches the scope to custom; clearing the last meaningful verdict returns to all, since custom with no rules constrains nothing. * fix(gallery): search checkboxes stay visible and idle panels read as dimmed The search panel hid its field checkboxes while the master switch was on, so the only way to reach them was to flip the switch first. They now sit next to the switch like the filter panel's verdicts do: dimmed in all-field mode (where they carry no weight) yet clickable, and touching one drops the mode to custom. The filter panel's verdict rows dim the same way while the filter switch is off. * fix(gallery): bulk verdict row, neutral default mark, panel polish The clear-filters button never matched what the panel is for, so it is now a bulk verdict row: one set of -/off/on buttons that applies the chosen position to every value of every value-typed attribute, with the default mark turned into a language-neutral dash. The panel head drops its second divider (the tab bar already draws one) and the tabs follow the toolbar's order: search left, filter right. * fix(gallery): drop the all-fields caption and center the order arrow The caption above the search checkboxes showed and hid with the master switch, shoving the checkboxes down on every flip; it said nothing the dimmed state doesn't, so it is gone. The order button's arrow is an inline svg, which sits on the text baseline and reads as riding high; it now centers against the label. * fix(gallery): center the order arrow for real vertical-align never applied: the icon is a flex item inside the button's inline-flex text wrapper, and the wrapper's default stretch pins the explicitly-sized 16px icon to the top of the 22px line box. align-items: center on the wrapper is what actually centers it. * fix(gallery): shorten panel tab labels in en and ru The two-word labels overflowed the 300px panel and forced the tab bar into scroll arrows; single-word labels fit in every locale that was affected. * docs: drop the image pipeline rewrite from this branch The rewritten 'Go 侧接手后' paragraph belongs to the image attribute observation work (#3635), which this branch carries as a prerequisite and which already documents the caption_ocr / observation_driven split. Keeping a competing rewrite of the same paragraph on the gallery branch makes it collide with upstream, which extended that paragraph with the custom_instructions and inline HTML table notes. Restoring the shared wording keeps the gallery branch free of this file so upstream's edits merge cleanly. * style: gofmt the gallery attribute types Struct field tags in the resolved gallery config were one column narrow, so gofmt rebroke the alignment block. Whitespace only. * style(gallery): use design tokens in the gallery styles The style guard ratchet fails on any new violation. ImageGallery.vue shipped with 47 TDesign token fallbacks, 21 literal font sizes, 4 literal radii and a 0.15s transition; all of them now read the --app-* / --td-* tokens, which is what the guard asks for and what dark mode depends on. * lint(gallery): fix the golangci-lint findings in the gallery code lll: the three over-long swagger @Param lines and one registry row were shortened. ineffassign: ctx was assigned before the access check and then reassigned, so the first value was dead; it is now declared once, after the check. errcheck: the three unchecked c.Error calls in ListImages. revive: the AttrSpec / AttrValue doc comment block was attached to the wrong type and split into one block each. staticcheck S1016: the gallery registration converts the registry value instead of restating its fields. * lint(gallery): wrap the image query select and check the last c.Error * style: reformat the wrapped image select in chunk.go * fix(gallery): address review findings on ordering, KB switch and blob lifetime - sortImageAssets: swap operands for desc instead of negating, keeping a strict weak ordering so ties page stably - ImageGallery: reload on knowledgeBaseId change, drop stale list responses, fetch thumbnails in parallel with one cached blob per URL, revoke blobs on unmount, default sort to builtin:created_at - KnowledgeBase: non-wiki KBs with a stale wiki/graph tab fall back to documents again - handler: move ListImages godoc out of ListKnowledgeFolders' block and document attr_filters / attr_rules - DecideOCR: a payload with no OCR conditions uses the built-in policy instead of silently skipping OCR * docs(parsing): describe the caption_ocr and observation_driven image pipelines Carried over from #3635, which this PR supersedes. * fix(gallery): load local:// and other storage handles through the KB file proxy The gallery's own scheme check only caught resource://, provider:// and storage://, so local:// (the default storage), minio://, cos:// and s3:// images went straight into <img src> and never rendered. Resolve through isProviderFileURL, the scheme list chat and wiki already use, and lock the routing with a test. * fix(kb-editor): keep API-customised OCR conditions on save and upload The KB editor always wrote the registry default into image_actions.ocr.on, so any unrelated edit replaced a knowledge base's custom OCR conditions with the default table; the upload dialog did the same for the per-document override. Keep a stored custom list and fall back to the registry default only when there is none, and show the conditions actually in effect instead of the default table in both panels. * perf(gallery): de-duplicate, filter, sort and page images in SQL Every gallery request used to read every image-bearing chunk of the KB, OCR text included, decode it in Go and page in memory. A single query now expands the image_info arrays, keeps one row per image URL, applies the keyword / attribute / verdict / enabled filters and the sort, and returns only the page with the filtered total. The expansion carries narrow scalars only; filters and JSON sort keys are evaluated on the winning entry of each image, and the page's JSON is read back for its rows alone. Postgres runs the query with JIT off, since the fixed 100-rows-per-call estimate of jsonb_array_elements otherwise prices it ~100x high and compilation dominates. On 20k images with 2 KB of OCR text each (40k chunks), a page drops from ~750 ms to ~100-200 ms on postgres and ~200 ms on sqlite; keyword search over OCR text stays a full scan (~400-600 ms) until the text is indexed. The filter semantics are pinned against both databases. * perf(gallery): serve the gallery from a trigger-maintained chunk_images table Reading images out of chunks.image_info meant parsing every image chunk of the knowledge base on each request, so a page still cost time in proportion to the KB. chunk_images (versioned/000113, sqlite/000032) keeps one row per image_info entry with caption, OCR text and attributes as columns; triggers on chunks keep it in step with every write path, and the migration backfills existing chunks. Copies of one image stay separate rows and the query lists the copy on the most recently updated chunk through an indexed anti-join, so writes decide nothing and concurrent writers need no locking. On postgres, caption and OCR text get pg_trgm indexes when the extension is available. On 20k images with 2 KB of OCR text each (40k chunks): postgres first page 10 ms, page 500 41 ms, keyword 2 ms, filters 23 ms sqlite first page 3 ms, page 500 39 ms, keyword 147 ms, filters 51 ms down from ~100-600 ms. Writing those 40k image chunks costs 7.0 s instead of 1.3 s on postgres (1.9 s instead of 1.0 s on sqlite), mostly the trigram indexes; status and enable-flag updates patch rows in place. --------- Co-authored-by: tayadwx <tayadwx@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-25 04:33:59 +00:00
// Counts only, no policy claims: whether a given image is OCR'd is
// decided per image once its attributes are observed, so a boolean here
// would assert something the pipeline has not decided yet — and would
// drift from what actually happened.
fix(knowledge): close root span on terminal state, enrich stage metadata The root span created by OpenAttempt was never closed: PostProcess only ended the postprocess stage, so the root row stayed at status=running forever even after parse_status flipped to completed/failed. The timeline rendered "进行中" indefinitely on the root, defeating the whole "is the document done" question the timeline is meant to answer. - SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg): closes the root row idempotently. Re-closing a terminal root no-ops so success / cascade-fail / dead-letter paths can fire without coordination. - PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess) on the success path. Async downstream work (summary/question/wiki/ graph) still records its own spans; their completion extends the trace's wall-clock end-time but doesn't reopen the root. - FailSpan auto-closes the root when a MAIN pipeline stage fails (docreader / chunking / embedding / multimodal / postprocess). Cascade-cancelled siblings stay closed-with-the-cascade as before. - Dead-letter callback (router/task.go) accepts the SpanTracker via DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a document-related task exhausts retries. The probe payload now extracts the Attempt field that Document/Manual/PostProcess payloads already thread through. Stage spans were also being recorded with nil input/output, leaving the new detail panel with timestamps only. Each Begin/End site now emits useful work metrics: - DocReader input: file_name, file_type, is_url, url output: text_length, images_found, is_audio, pages - Chunking input: chunks_planned output: chunks_written, total_text_chars - Embedding input: chunks_to_embed, model_id, dim output: vectors_written, storage_bytes - Multimodal input: image_count, enable_ocr, enable_caption - PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph i18n: add knowledgeStages.root ("Knowledge processing") so the UI can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
s.beginStage(ctx, knowledge.ID, types.StageMultimodal, types.JSONMap{
feat(gallery): add an image gallery tab with schema-driven filters (#3694) * feat(image): observe image attributes and let the policy decide OCR Describe each image with the VLM as before, but ask it to also observe two attributes about the image in the same round — how much body text it carries (contain.text) and whether it presents data visually (contain.data_visual) — then let a small pure function decide whether that image is worth a second, separate OCR round. Per-class OCR was the first shape of this idea; a class (chart / photo / logo) is only an indirect proxy for 'is there text worth reading here', and the class table has to grow whenever a new kind of image shows up. The decision actually needs the observed attributes, so it reads them directly, and the attribute set is a backend registry row rather than a new class. The observation and the caption share one VLM call; OCR stays a separate call (prompt isolation, see #3291). An attribute the model does not answer for is left absent rather than filled with a conservative default, so the trace never claims an observation that did not happen, and an incomplete observation falls back to the on_unobserved policy (OCR still runs). The registry also carries the panel's display text, so a new attribute needs no frontend change. Off by default: image_attrs_enabled=false keeps today's behaviour (one caption and one OCR per image). KB config: image_processing_config.image_attrs_enabled / image_actions; per-upload override via process_config. Registry: GET /api/v1/image-attrs/schema. * feat(gallery): add image gallery tab with schema-driven filters Adds a 4th knowledge-base tab parallel to Documents/Wiki/Graph that browses every image asset in a KB. Backend: - GET /api/v1/knowledge-bases/:id/images lists image assets projected from chunks.image_info, with keyword (caption/OCR), multi-value attribute (attr_<name>=<value>), is_enabled and sort filters applied in memory, plus pagination. - Resolves the source knowledge item title (SourceName) via a batched GetKnowledgeBatch so the viewer can show a human-readable source. Frontend: - ImageGallery.vue: thumbnail grid + search/sort + schema-driven filter panel (from GET /image-attrs/schema) + single-image viewer with prev/next, attributes/caption/OCR/source. - Wired as the gallery tab in KnowledgeBase.vue; i18n keys in all 5 locales. * feat(gallery): drive filters/search/sort from a configurable attribute contract The gallery UI is no longer hardcoded: it renders from a self-describing contract served by GET /knowledge-bases/:id/gallery-config (live attribute sources, every attribute's definition with usage flags merged across the config tiers, and the caller's search activation state). - Attribute sources form an open registry (types.RegisterGalleryAttrSource); a builtin source models caption/ocr_text/timestamps/enabled so the gallery has zero special cases. - Usage resolution: user > KB > system > source, field by field; the system tier lives in system_settings (gallery.policy, JSON, no rebuild), the KB tier slot is wired in the engine but not stored yet. - Search activation is the user's own record: mode (all|custom) plus per-field on/off in users.preferences.gallery; source declarations never set defaults (unrecorded = off in custom mode). - image_info is read through a gallery-local struct, removing the compile dependency on the attribute-pipeline types; the gallery builds and runs with or without that feature deployed. - ListImages validates search_in / sort_by / attr_filters against the contract; ineligible fields are dropped, not served. * fix(frontend): inline the shared graph-drawer stylesheet (@import instead of <style src>) plugin-vue 6.0.6 keys unscoped src-style descriptors by the imported file path, so AgentStreamDisplay.vue and WikiBrowser.vue — both importing components/css/wiki-graph-drawer.less — overwrite each other during the build and the second one crashes with "reading 'scoped'". Adding the gallery changed the module order enough to make the collision hit every time. Inlining the same stylesheet keeps the emitted CSS identical and removes the shared descriptor key. * feat(gallery): render attributes from short labels with descriptions in tooltips A source could only say one thing about a value, so the filter panel had to put a full sentence inside a checkbox. Attributes and their values now carry two pieces of text: a short label for the space-constrained controls (checkbox, search field, sort option) and a description for wherever there is room (tooltip, detail panel). The contract's value list becomes an array of {value, label, description}, and the display helpers resolve each field separately: the gallery stamps the short name on a control and moves the sentence into a tooltip. Translation overlays are looked up per field, so a source that ships no gallery-specific text still picks up the attribute pipeline's own wording. * fix(gallery): let locale text win over the contract's wording The filter panel read the backend's own label before asking the locale, so a translated value never got a chance: the contract ships its own default-language wording, and it shadowed the overlay for every locale. Built keys were also off by a segment — imageAttr.<name> has to be imageAttr.<name>.label, and the gallery's own keys live under knowledgeEditor.wikiBrowser.gallery.attr — so builtin and system attributes fell through to English on a Chinese UI. * feat(gallery): top bar layout, pinned panels and per-value verdicts The toolbar moves onto its own row above the grid, so the controls no longer eat into the space the images are there for: search box, the two scope switches, sort field and direction, and the result count all sit in one flex row. The settings behind them are no longer inline either — each opens as a popover under its control and can be pinned to a right-hand rail, where the two panels take turns as tabs instead of both claiming width at once. Filtering gains a third state per attribute value. Where a value could only be picked or not picked, it can now be "off" (hide those images), "on" (show them whatever else says) or neutral (leave them alone), which is what lets one attribute's rules talk about an image another attribute tried to hide without the pair of them cancelling each other out: a forced display outranks a forced hide, and anything no rule speaks about stays visible. The switch that used to only exist inside the panel now has a toolbar home as well. "筛选:全显示" genuinely drops the attribute constraint instead of imposing it against a panel the user cannot see. Filtering used to empty the list the moment it was switched on. Any image whose attribute was never observed — every image ingested before the attribute pipeline existed — read as a mismatch for every filter, which is not narrowing a list but losing it. Absence now stays silence: an attribute no image carries places no constraint on it, until the pipeline catches up and fills the value in. Co-authored-by: WorkBuddy * feat(gallery): expose the image attribute pipeline as a gallery source The gallery's contract resolved to a single source, so the filter panel could only offer "Enabled" while the attributes the observe-and-describe pipeline fills in — contain.text, contain.data_visual — never reached the UI. The registry is a gallery attribute source like any other: every attribute it declares is offered to the gallery, filterable by default, with the config tiers able to override the usage flags at runtime. The registration lives in the attribute pipeline's own commit; this branch carried an earlier, squapshot of that work which predated the split of an attribute value into a short label and a description, so the registry's value shape and this file have been brought in line with it. Both PRs now hold byte-identical copies of the source hook, which is what lets either one land first and the other merge cleanly afterwards. Co-authored-by: WorkBuddy * fix(gallery): viewer race, pin icon, panel anchoring and scope wording Opening the viewer rendered the img element with the previous or empty source while the proxy fetch was still producing a blob, and the error that empty source fired locked the viewer in its failure state even after the real image arrived. The resolved source now lands before the flag is consulted, and a token keeps a slow fetch of one image from overwriting a faster one that navigated past it. The pin button drew nothing: TDesign has no "pushpin" glyph, so the button rendered as an empty shell. It now uses pin / pin-filled, keeps its place beside the tab bar, and a pinned rail assigns its columns explicitly — the panel precedes the main section in the DOM, so leaving the grid to source order handed the wide column to the panel and squeezed the images into the rail. The floating panel no longer appears at a hardcoded offset: it anchors just below the arrow that summoned it, the arrow flips up while its panel is out, a second press retracts, and any click elsewhere in the toolbar closes it. When a rail is pinned the arrows turn to the requested tab instead of spawning a second surface. The scope words (全部 / 全显示 / 自定义) become plain status text rather than a second dropdown — they name the current mode, and only the arrow beside them opens the panel that changes it. Co-authored-by: WorkBuddy * fix(web): align the OCR-on-unobserved switch with the other setting rows The switch sat bare inside its setting-row while every other switch on the page is wrapped in setting-control, which is what reserves the right column and centers the control vertically. With the row laid out from the top, the bare switch hugged the row's upper edge and crowded the description text — visibly out of place next to its neighbors. Wrapping it in setting-control gives it the same right-aligned, centered slot as the rest. Co-authored-by: WorkBuddy * fix(web): move the OCR-on-unobserved row out of the vertical schema row The row lived inside setting-row-vertical, whose descendant rule stretches every setting-info and setting-control beneath it to 100% width. Two full-width flex children side by side cannot fit, so the control overflowed the container and the switch landed past the right edge — visibly further out than the switch on the row above. The row and its note now sit beside the vertical block instead of inside it, under their own condition, so the switch shares the ordinary row layout and its right edge lines up with the "image attribute observation" switch above. Co-authored-by: WorkBuddy * fix(gallery): applying a verdict now activates the filter scope Setting an off/on verdict while the panel's master switch was off silently ignored it: buildParams only attaches attr_rules in custom scope, and setVerdict never flipped the scope. A verdict the user just expressed now switches the scope to custom; clearing the last meaningful verdict returns to all, since custom with no rules constrains nothing. * fix(gallery): search checkboxes stay visible and idle panels read as dimmed The search panel hid its field checkboxes while the master switch was on, so the only way to reach them was to flip the switch first. They now sit next to the switch like the filter panel's verdicts do: dimmed in all-field mode (where they carry no weight) yet clickable, and touching one drops the mode to custom. The filter panel's verdict rows dim the same way while the filter switch is off. * fix(gallery): bulk verdict row, neutral default mark, panel polish The clear-filters button never matched what the panel is for, so it is now a bulk verdict row: one set of -/off/on buttons that applies the chosen position to every value of every value-typed attribute, with the default mark turned into a language-neutral dash. The panel head drops its second divider (the tab bar already draws one) and the tabs follow the toolbar's order: search left, filter right. * fix(gallery): drop the all-fields caption and center the order arrow The caption above the search checkboxes showed and hid with the master switch, shoving the checkboxes down on every flip; it said nothing the dimmed state doesn't, so it is gone. The order button's arrow is an inline svg, which sits on the text baseline and reads as riding high; it now centers against the label. * fix(gallery): center the order arrow for real vertical-align never applied: the icon is a flex item inside the button's inline-flex text wrapper, and the wrapper's default stretch pins the explicitly-sized 16px icon to the top of the 22px line box. align-items: center on the wrapper is what actually centers it. * fix(gallery): shorten panel tab labels in en and ru The two-word labels overflowed the 300px panel and forced the tab bar into scroll arrows; single-word labels fit in every locale that was affected. * docs: drop the image pipeline rewrite from this branch The rewritten 'Go 侧接手后' paragraph belongs to the image attribute observation work (#3635), which this branch carries as a prerequisite and which already documents the caption_ocr / observation_driven split. Keeping a competing rewrite of the same paragraph on the gallery branch makes it collide with upstream, which extended that paragraph with the custom_instructions and inline HTML table notes. Restoring the shared wording keeps the gallery branch free of this file so upstream's edits merge cleanly. * style: gofmt the gallery attribute types Struct field tags in the resolved gallery config were one column narrow, so gofmt rebroke the alignment block. Whitespace only. * style(gallery): use design tokens in the gallery styles The style guard ratchet fails on any new violation. ImageGallery.vue shipped with 47 TDesign token fallbacks, 21 literal font sizes, 4 literal radii and a 0.15s transition; all of them now read the --app-* / --td-* tokens, which is what the guard asks for and what dark mode depends on. * lint(gallery): fix the golangci-lint findings in the gallery code lll: the three over-long swagger @Param lines and one registry row were shortened. ineffassign: ctx was assigned before the access check and then reassigned, so the first value was dead; it is now declared once, after the check. errcheck: the three unchecked c.Error calls in ListImages. revive: the AttrSpec / AttrValue doc comment block was attached to the wrong type and split into one block each. staticcheck S1016: the gallery registration converts the registry value instead of restating its fields. * lint(gallery): wrap the image query select and check the last c.Error * style: reformat the wrapped image select in chunk.go * fix(gallery): address review findings on ordering, KB switch and blob lifetime - sortImageAssets: swap operands for desc instead of negating, keeping a strict weak ordering so ties page stably - ImageGallery: reload on knowledgeBaseId change, drop stale list responses, fetch thumbnails in parallel with one cached blob per URL, revoke blobs on unmount, default sort to builtin:created_at - KnowledgeBase: non-wiki KBs with a stale wiki/graph tab fall back to documents again - handler: move ListImages godoc out of ListKnowledgeFolders' block and document attr_filters / attr_rules - DecideOCR: a payload with no OCR conditions uses the built-in policy instead of silently skipping OCR * docs(parsing): describe the caption_ocr and observation_driven image pipelines Carried over from #3635, which this PR supersedes. * fix(gallery): load local:// and other storage handles through the KB file proxy The gallery's own scheme check only caught resource://, provider:// and storage://, so local:// (the default storage), minio://, cos:// and s3:// images went straight into <img src> and never rendered. Resolve through isProviderFileURL, the scheme list chat and wiki already use, and lock the routing with a test. * fix(kb-editor): keep API-customised OCR conditions on save and upload The KB editor always wrote the registry default into image_actions.ocr.on, so any unrelated edit replaced a knowledge base's custom OCR conditions with the default table; the upload dialog did the same for the per-document override. Keep a stored custom list and fall back to the registry default only when there is none, and show the conditions actually in effect instead of the default table in both panels. * perf(gallery): de-duplicate, filter, sort and page images in SQL Every gallery request used to read every image-bearing chunk of the KB, OCR text included, decode it in Go and page in memory. A single query now expands the image_info arrays, keeps one row per image URL, applies the keyword / attribute / verdict / enabled filters and the sort, and returns only the page with the filtered total. The expansion carries narrow scalars only; filters and JSON sort keys are evaluated on the winning entry of each image, and the page's JSON is read back for its rows alone. Postgres runs the query with JIT off, since the fixed 100-rows-per-call estimate of jsonb_array_elements otherwise prices it ~100x high and compilation dominates. On 20k images with 2 KB of OCR text each (40k chunks), a page drops from ~750 ms to ~100-200 ms on postgres and ~200 ms on sqlite; keyword search over OCR text stays a full scan (~400-600 ms) until the text is indexed. The filter semantics are pinned against both databases. * perf(gallery): serve the gallery from a trigger-maintained chunk_images table Reading images out of chunks.image_info meant parsing every image chunk of the knowledge base on each request, so a page still cost time in proportion to the KB. chunk_images (versioned/000113, sqlite/000032) keeps one row per image_info entry with caption, OCR text and attributes as columns; triggers on chunks keep it in step with every write path, and the migration backfills existing chunks. Copies of one image stay separate rows and the query lists the copy on the most recently updated chunk through an indexed anti-join, so writes decide nothing and concurrent writers need no locking. On postgres, caption and OCR text get pg_trgm indexes when the extension is available. On 20k images with 2 KB of OCR text each (40k chunks): postgres first page 10 ms, page 500 41 ms, keyword 2 ms, filters 23 ms sqlite first page 3 ms, page 500 39 ms, keyword 147 ms, filters 51 ms down from ~100-600 ms. Writing those 40k image chunks costs 7.0 s instead of 1.3 s on postgres (1.9 s instead of 1.0 s on sqlite), mostly the trigram indexes; status and enable-flag updates patch rows in place. --------- Co-authored-by: tayadwx <tayadwx@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-25 04:33:59 +00:00
"image_count": len(options.StoredImages),
fix(knowledge): close root span on terminal state, enrich stage metadata The root span created by OpenAttempt was never closed: PostProcess only ended the postprocess stage, so the root row stayed at status=running forever even after parse_status flipped to completed/failed. The timeline rendered "进行中" indefinitely on the root, defeating the whole "is the document done" question the timeline is meant to answer. - SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg): closes the root row idempotently. Re-closing a terminal root no-ops so success / cascade-fail / dead-letter paths can fire without coordination. - PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess) on the success path. Async downstream work (summary/question/wiki/ graph) still records its own spans; their completion extends the trace's wall-clock end-time but doesn't reopen the root. - FailSpan auto-closes the root when a MAIN pipeline stage fails (docreader / chunking / embedding / multimodal / postprocess). Cascade-cancelled siblings stay closed-with-the-cascade as before. - Dead-letter callback (router/task.go) accepts the SpanTracker via DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a document-related task exhausts retries. The probe payload now extracts the Attempt field that Document/Manual/PostProcess payloads already thread through. Stage spans were also being recorded with nil input/output, leaving the new detail panel with timestamps only. Each Begin/End site now emits useful work metrics: - DocReader input: file_name, file_type, is_url, url output: text_length, images_found, is_audio, pages - Chunking input: chunks_planned output: chunks_written, total_text_chars - Embedding input: chunks_to_embed, model_id, dim output: vectors_written, storage_bytes - Multimodal input: image_count, enable_ocr, enable_caption - PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph i18n: add knowledgeStages.root ("Knowledge processing") so the UI can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
})
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if err := s.enqueueImageMultimodalTasks(
ctx, knowledge, kb, options.StoredImages, chunks, options.Metadata,
); err != nil {
// Nothing else moves the row out of "processing"; let asynq
// run the (idempotent) parse again, or dead-letter it.
return err
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
} else {
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
s.skipStage(ctx, knowledge.ID, types.StageMultimodal, "skipped")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// If there are no multimodal tasks, enqueue the post process task immediately
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if err := s.enqueueKnowledgePostProcessTask(ctx, knowledge); err != nil {
return err
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// Update tenant's storage usage
tenantInfo.StorageUsed += totalStorageSize
if err := s.tenantRepo.AdjustStorageUsed(ctx, tenantInfo.ID, totalStorageSize); err != nil {
logger.GetLogger(ctx).WithField("error", err).Errorf("processChunks update tenant storage used failed")
}
logger.GetLogger(ctx).Infof("processChunks successfully")
return nil
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
// defaultMaxInputChars is the default maximum characters used as input for
// summary generation. The document profile (short summary, gist, topics,
// type, one question) is decided by the head of a document; 8k characters
// keeps the per-document cost a quarter of the previous 24k without changing
// what the profile can say.
const defaultMaxInputChars = 1024 * 8
// defaultSummaryMaxTokens bounds the JSON profile reply; every field is short.
const defaultSummaryMaxTokens = 1024
// documentSummaryResult is what one profiling call yields: the short summary
// stored in knowledge.Description plus the structured profile, when the model
// returned parseable JSON.
type documentSummaryResult struct {
Summary string
Profile *types.KnowledgeProfile
}
// documentProfileOutput mirrors the JSON contract of generate_summary.yaml.
type documentProfileOutput struct {
Summary string `json:"summary"`
Gist string `json:"gist"`
Topics []string `json:"topics"`
DocType string `json:"doc_type"`
TypicalQuestion string `json:"typical_question"`
}
fix(summary): 坏 JSON 不再冒充文档摘要(截断/畸形 JSON 走失败路径,纯文本兜底保留) (#3769) * fix(summary): 坏 JSON 不再冒充文档摘要 非流式文档摘要(Chat)解析失败时原先把模型原文当摘要落库:被 MaxTokens 截断的半截 JSON 会写进 knowledges.description、置 SummaryStatus=Completed (Asynq 不再重试),同一段文本还会被 buildSummaryChunkContent 索引进 RAG。 - parseDocumentSummaryOutput 改为返回 (*documentSummaryResult, error): 回复形如 JSON(含 markdown 代码围栏)却解析失败、或解析成功但取不到 summary/gist 时返回 errSummaryOutputNotParsable,绝不回退成原文; 非 JSON 的纯文本仍走原有的原文兜底,自定义模板 / 老模型不受影响。 - validateSummaryOutput 复用 chatpipeline.IsLengthFinishReason, FinishReason 为 length 类取值时返回 errSummaryOutputTruncated。 - 两个 sentinel 经 getSummary 汇入既有失败路径(ProcessSummaryGeneration 的 handleRetryableSummaryFailure、RegenerateKnowledgeSummary 的 handleGenerationFailure):保留旧描述、置 pending/failed 交给 Asynq 重试, 不再以 Completed 落库。 测试:TestParseDocumentSummaryOutput 改为表驱动(截断 JSON、含裸换行 JSON、 无文本 JSON 必须报错且不能把原文当 Summary;纯文本兜底继续通过); TestValidateSummaryOutput 增加 length / max_tokens 截断用例; TestGetSummaryRejectsUnusableModelOutput 锁住 getSummary 的错误传播。 * fix(summary): length 截断判定收窄到 JSON 形状回复 非流式文档摘要在校验模型回复时先看 finish_reason:只要 provider 报告 length/max_tokens 就返回 errSummaryOutputTruncated。该判定不认识内容形状, 于是自定义纯文本模板一旦顶到输出预算,就从「截断但可用」变成重试直到 SummaryStatusFailed,与上一提交承诺的「非 JSON 的纯文本仍走原兜底」相反。 - validateSummaryOutput 恢复为只看内容是否为空;新增 validateStructuredSummaryDocument 供 getSummary 使用:先判形状再判 length,只有确实在产结构化摘要(能解析成对象/数组,或 { 开头、[ 开头接 对象/数组/字符串元素)且被预算截断时才返回 errSummaryOutputTruncated。 - 形状判定剥离 UTF-8 BOM、前后空白与一层 markdown 围栏后再尝试 json.Unmarshal;「[文档摘要] …」「[1] …」这类带方括号引用的纯文本不再被 误判成坏 JSON,而截断的 {summary: 与截断的 JSON 数组仍然报错。 - parseDocumentSummaryOutput 同步剥离 BOM:BOM 前缀的截断 JSON 之前会被 当成纯文本落库。 - 表格描述 / 列描述仍走 validateSummaryOutput,截断的描述照旧可索引。 --------- Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 17:21:01 +00:00
// normalizeSummaryReplyContent strips a UTF-8 BOM, the surrounding whitespace
// and one markdown code fence from a summary reply, so shape detection and
// parsing look at the same text. A fence without a newline carries no payload
// we can classify, so it normalizes to the empty string.
func normalizeSummaryReplyContent(content string) string {
content = strings.TrimSpace(strings.TrimPrefix(content, "\uFEFF"))
if rest, ok := strings.CutPrefix(content, "```"); ok {
// Drop the fence's info string (```json) and the newline after it.
idx := strings.IndexByte(rest, '\n')
if idx < 0 {
return ""
}
content = strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(rest[idx+1:]), "```"))
}
return content
}
// summaryReplyIsJSONShaped reports whether the reply really is a structured
// JSON payload, either directly or inside a markdown code fence. Only such
// replies are held to the structured contract below; anything else is a
// legacy plain-text summary.
//
// An object opening ("{") always counts, parseable or not: half an object is
// exactly the reply that must never be stored as a summary. A bracket opening
// is ambiguous — "[1] …" and "[文档摘要] …" are prose with a leading citation,
// not broken JSON — so it only counts when the reply is a JSON array or opens
// an array of objects/strings.
func summaryReplyIsJSONShaped(content string) bool {
content = normalizeSummaryReplyContent(content)
if content == "" {
return false
}
switch content[0] {
case '{':
return true
case '[':
var arr []json.RawMessage
if json.Unmarshal([]byte(content), &arr) == nil {
return true
}
first := strings.TrimLeft(content[1:], " \t\r\n")
return strings.HasPrefix(first, "{") ||
strings.HasPrefix(first, "[") ||
strings.HasPrefix(first, `"`)
default:
return false
}
}
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
// parseDocumentSummaryOutput accepts both the structured JSON reply and a
// legacy plain-text summary (custom templates, older models). Plain text is
// stored as the summary with no profile, so nothing that worked before
// regresses; only the knowledge-base aggregation loses that document's topics.
fix(summary): 坏 JSON 不再冒充文档摘要(截断/畸形 JSON 走失败路径,纯文本兜底保留) (#3769) * fix(summary): 坏 JSON 不再冒充文档摘要 非流式文档摘要(Chat)解析失败时原先把模型原文当摘要落库:被 MaxTokens 截断的半截 JSON 会写进 knowledges.description、置 SummaryStatus=Completed (Asynq 不再重试),同一段文本还会被 buildSummaryChunkContent 索引进 RAG。 - parseDocumentSummaryOutput 改为返回 (*documentSummaryResult, error): 回复形如 JSON(含 markdown 代码围栏)却解析失败、或解析成功但取不到 summary/gist 时返回 errSummaryOutputNotParsable,绝不回退成原文; 非 JSON 的纯文本仍走原有的原文兜底,自定义模板 / 老模型不受影响。 - validateSummaryOutput 复用 chatpipeline.IsLengthFinishReason, FinishReason 为 length 类取值时返回 errSummaryOutputTruncated。 - 两个 sentinel 经 getSummary 汇入既有失败路径(ProcessSummaryGeneration 的 handleRetryableSummaryFailure、RegenerateKnowledgeSummary 的 handleGenerationFailure):保留旧描述、置 pending/failed 交给 Asynq 重试, 不再以 Completed 落库。 测试:TestParseDocumentSummaryOutput 改为表驱动(截断 JSON、含裸换行 JSON、 无文本 JSON 必须报错且不能把原文当 Summary;纯文本兜底继续通过); TestValidateSummaryOutput 增加 length / max_tokens 截断用例; TestGetSummaryRejectsUnusableModelOutput 锁住 getSummary 的错误传播。 * fix(summary): length 截断判定收窄到 JSON 形状回复 非流式文档摘要在校验模型回复时先看 finish_reason:只要 provider 报告 length/max_tokens 就返回 errSummaryOutputTruncated。该判定不认识内容形状, 于是自定义纯文本模板一旦顶到输出预算,就从「截断但可用」变成重试直到 SummaryStatusFailed,与上一提交承诺的「非 JSON 的纯文本仍走原兜底」相反。 - validateSummaryOutput 恢复为只看内容是否为空;新增 validateStructuredSummaryDocument 供 getSummary 使用:先判形状再判 length,只有确实在产结构化摘要(能解析成对象/数组,或 { 开头、[ 开头接 对象/数组/字符串元素)且被预算截断时才返回 errSummaryOutputTruncated。 - 形状判定剥离 UTF-8 BOM、前后空白与一层 markdown 围栏后再尝试 json.Unmarshal;「[文档摘要] …」「[1] …」这类带方括号引用的纯文本不再被 误判成坏 JSON,而截断的 {summary: 与截断的 JSON 数组仍然报错。 - parseDocumentSummaryOutput 同步剥离 BOM:BOM 前缀的截断 JSON 之前会被 当成纯文本落库。 - 表格描述 / 列描述仍走 validateSummaryOutput,截断的描述照旧可索引。 --------- Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 17:21:01 +00:00
//
// A reply that opens like JSON is held to the JSON contract instead: a broken
// object (output cut off at MaxTokens, an unescaped newline inside a string)
// or an object with no usable text returns errSummaryOutputNotParsable. The
// raw reply used to be stored as the summary, which put half a JSON object in
// knowledges.description, marked the summary completed so Asynq never retried
// it, and embedded the same fragment into the RAG index.
func parseDocumentSummaryOutput(content string) (*documentSummaryResult, error) {
// Some providers prefix the reply with a UTF-8 BOM; TrimSpace alone would
// leave it in place, hide the "{" and let half an object through as prose.
content = strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(content), "\uFEFF"))
if content == "" {
return nil, errEmptySummaryOutput
}
jsonShaped := summaryReplyIsJSONShaped(content)
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
var out documentProfileOutput
if err := common.ParseLLMJsonResponse(content, &out); err != nil {
fix(summary): 坏 JSON 不再冒充文档摘要(截断/畸形 JSON 走失败路径,纯文本兜底保留) (#3769) * fix(summary): 坏 JSON 不再冒充文档摘要 非流式文档摘要(Chat)解析失败时原先把模型原文当摘要落库:被 MaxTokens 截断的半截 JSON 会写进 knowledges.description、置 SummaryStatus=Completed (Asynq 不再重试),同一段文本还会被 buildSummaryChunkContent 索引进 RAG。 - parseDocumentSummaryOutput 改为返回 (*documentSummaryResult, error): 回复形如 JSON(含 markdown 代码围栏)却解析失败、或解析成功但取不到 summary/gist 时返回 errSummaryOutputNotParsable,绝不回退成原文; 非 JSON 的纯文本仍走原有的原文兜底,自定义模板 / 老模型不受影响。 - validateSummaryOutput 复用 chatpipeline.IsLengthFinishReason, FinishReason 为 length 类取值时返回 errSummaryOutputTruncated。 - 两个 sentinel 经 getSummary 汇入既有失败路径(ProcessSummaryGeneration 的 handleRetryableSummaryFailure、RegenerateKnowledgeSummary 的 handleGenerationFailure):保留旧描述、置 pending/failed 交给 Asynq 重试, 不再以 Completed 落库。 测试:TestParseDocumentSummaryOutput 改为表驱动(截断 JSON、含裸换行 JSON、 无文本 JSON 必须报错且不能把原文当 Summary;纯文本兜底继续通过); TestValidateSummaryOutput 增加 length / max_tokens 截断用例; TestGetSummaryRejectsUnusableModelOutput 锁住 getSummary 的错误传播。 * fix(summary): length 截断判定收窄到 JSON 形状回复 非流式文档摘要在校验模型回复时先看 finish_reason:只要 provider 报告 length/max_tokens 就返回 errSummaryOutputTruncated。该判定不认识内容形状, 于是自定义纯文本模板一旦顶到输出预算,就从「截断但可用」变成重试直到 SummaryStatusFailed,与上一提交承诺的「非 JSON 的纯文本仍走原兜底」相反。 - validateSummaryOutput 恢复为只看内容是否为空;新增 validateStructuredSummaryDocument 供 getSummary 使用:先判形状再判 length,只有确实在产结构化摘要(能解析成对象/数组,或 { 开头、[ 开头接 对象/数组/字符串元素)且被预算截断时才返回 errSummaryOutputTruncated。 - 形状判定剥离 UTF-8 BOM、前后空白与一层 markdown 围栏后再尝试 json.Unmarshal;「[文档摘要] …」「[1] …」这类带方括号引用的纯文本不再被 误判成坏 JSON,而截断的 {summary: 与截断的 JSON 数组仍然报错。 - parseDocumentSummaryOutput 同步剥离 BOM:BOM 前缀的截断 JSON 之前会被 当成纯文本落库。 - 表格描述 / 列描述仍走 validateSummaryOutput,截断的描述照旧可索引。 --------- Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 17:21:01 +00:00
if jsonShaped {
return nil, fmt.Errorf("%w: %w", errSummaryOutputNotParsable, err)
}
// Legacy plain text: keep it as the summary with no profile.
return &documentSummaryResult{Summary: content}, nil
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
}
summary := strings.TrimSpace(out.Summary)
profile := (&types.KnowledgeProfile{
Gist: out.Gist,
Topics: out.Topics,
DocType: out.DocType,
TypicalQuestion: out.TypicalQuestion,
}).Normalize()
if summary == "" && profile != nil {
summary = profile.Gist
}
if summary == "" {
fix(summary): 坏 JSON 不再冒充文档摘要(截断/畸形 JSON 走失败路径,纯文本兜底保留) (#3769) * fix(summary): 坏 JSON 不再冒充文档摘要 非流式文档摘要(Chat)解析失败时原先把模型原文当摘要落库:被 MaxTokens 截断的半截 JSON 会写进 knowledges.description、置 SummaryStatus=Completed (Asynq 不再重试),同一段文本还会被 buildSummaryChunkContent 索引进 RAG。 - parseDocumentSummaryOutput 改为返回 (*documentSummaryResult, error): 回复形如 JSON(含 markdown 代码围栏)却解析失败、或解析成功但取不到 summary/gist 时返回 errSummaryOutputNotParsable,绝不回退成原文; 非 JSON 的纯文本仍走原有的原文兜底,自定义模板 / 老模型不受影响。 - validateSummaryOutput 复用 chatpipeline.IsLengthFinishReason, FinishReason 为 length 类取值时返回 errSummaryOutputTruncated。 - 两个 sentinel 经 getSummary 汇入既有失败路径(ProcessSummaryGeneration 的 handleRetryableSummaryFailure、RegenerateKnowledgeSummary 的 handleGenerationFailure):保留旧描述、置 pending/failed 交给 Asynq 重试, 不再以 Completed 落库。 测试:TestParseDocumentSummaryOutput 改为表驱动(截断 JSON、含裸换行 JSON、 无文本 JSON 必须报错且不能把原文当 Summary;纯文本兜底继续通过); TestValidateSummaryOutput 增加 length / max_tokens 截断用例; TestGetSummaryRejectsUnusableModelOutput 锁住 getSummary 的错误传播。 * fix(summary): length 截断判定收窄到 JSON 形状回复 非流式文档摘要在校验模型回复时先看 finish_reason:只要 provider 报告 length/max_tokens 就返回 errSummaryOutputTruncated。该判定不认识内容形状, 于是自定义纯文本模板一旦顶到输出预算,就从「截断但可用」变成重试直到 SummaryStatusFailed,与上一提交承诺的「非 JSON 的纯文本仍走原兜底」相反。 - validateSummaryOutput 恢复为只看内容是否为空;新增 validateStructuredSummaryDocument 供 getSummary 使用:先判形状再判 length,只有确实在产结构化摘要(能解析成对象/数组,或 { 开头、[ 开头接 对象/数组/字符串元素)且被预算截断时才返回 errSummaryOutputTruncated。 - 形状判定剥离 UTF-8 BOM、前后空白与一层 markdown 围栏后再尝试 json.Unmarshal;「[文档摘要] …」「[1] …」这类带方括号引用的纯文本不再被 误判成坏 JSON,而截断的 {summary: 与截断的 JSON 数组仍然报错。 - parseDocumentSummaryOutput 同步剥离 BOM:BOM 前缀的截断 JSON 之前会被 当成纯文本落库。 - 表格描述 / 列描述仍走 validateSummaryOutput,截断的描述照旧可索引。 --------- Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 17:21:01 +00:00
if jsonShaped {
// JSON without usable text is as unusable as broken JSON: the
// caller must fail the attempt instead of storing the object.
return nil, errSummaryOutputNotParsable
}
// Plain text that happened to contain balanced JSON punctuation.
return &documentSummaryResult{Summary: content}, nil
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
}
fix(summary): 坏 JSON 不再冒充文档摘要(截断/畸形 JSON 走失败路径,纯文本兜底保留) (#3769) * fix(summary): 坏 JSON 不再冒充文档摘要 非流式文档摘要(Chat)解析失败时原先把模型原文当摘要落库:被 MaxTokens 截断的半截 JSON 会写进 knowledges.description、置 SummaryStatus=Completed (Asynq 不再重试),同一段文本还会被 buildSummaryChunkContent 索引进 RAG。 - parseDocumentSummaryOutput 改为返回 (*documentSummaryResult, error): 回复形如 JSON(含 markdown 代码围栏)却解析失败、或解析成功但取不到 summary/gist 时返回 errSummaryOutputNotParsable,绝不回退成原文; 非 JSON 的纯文本仍走原有的原文兜底,自定义模板 / 老模型不受影响。 - validateSummaryOutput 复用 chatpipeline.IsLengthFinishReason, FinishReason 为 length 类取值时返回 errSummaryOutputTruncated。 - 两个 sentinel 经 getSummary 汇入既有失败路径(ProcessSummaryGeneration 的 handleRetryableSummaryFailure、RegenerateKnowledgeSummary 的 handleGenerationFailure):保留旧描述、置 pending/failed 交给 Asynq 重试, 不再以 Completed 落库。 测试:TestParseDocumentSummaryOutput 改为表驱动(截断 JSON、含裸换行 JSON、 无文本 JSON 必须报错且不能把原文当 Summary;纯文本兜底继续通过); TestValidateSummaryOutput 增加 length / max_tokens 截断用例; TestGetSummaryRejectsUnusableModelOutput 锁住 getSummary 的错误传播。 * fix(summary): length 截断判定收窄到 JSON 形状回复 非流式文档摘要在校验模型回复时先看 finish_reason:只要 provider 报告 length/max_tokens 就返回 errSummaryOutputTruncated。该判定不认识内容形状, 于是自定义纯文本模板一旦顶到输出预算,就从「截断但可用」变成重试直到 SummaryStatusFailed,与上一提交承诺的「非 JSON 的纯文本仍走原兜底」相反。 - validateSummaryOutput 恢复为只看内容是否为空;新增 validateStructuredSummaryDocument 供 getSummary 使用:先判形状再判 length,只有确实在产结构化摘要(能解析成对象/数组,或 { 开头、[ 开头接 对象/数组/字符串元素)且被预算截断时才返回 errSummaryOutputTruncated。 - 形状判定剥离 UTF-8 BOM、前后空白与一层 markdown 围栏后再尝试 json.Unmarshal;「[文档摘要] …」「[1] …」这类带方括号引用的纯文本不再被 误判成坏 JSON,而截断的 {summary: 与截断的 JSON 数组仍然报错。 - parseDocumentSummaryOutput 同步剥离 BOM:BOM 前缀的截断 JSON 之前会被 当成纯文本落库。 - 表格描述 / 列描述仍走 validateSummaryOutput,截断的描述照旧可索引。 --------- Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 17:21:01 +00:00
return &documentSummaryResult{Summary: summary, Profile: profile}, nil
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
}
// buildSummaryChunkContent is the text embedded for the document-level
// summary chunk. The gist leads so the vector reflects the headline first.
func buildSummaryChunkContent(summary string, profile *types.KnowledgeProfile) string {
summary = strings.TrimSpace(summary)
if profile != nil {
gist := strings.TrimSpace(profile.Gist)
if gist != "" && !strings.EqualFold(gist, summary) {
return "# Summary\n" + gist + "\n\n" + summary
}
}
return "# Summary\n" + summary
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// imageDominatedTextThreshold is the rune count below which a document is
// considered "image-dominated" — i.e. the body text is so sparse that we
// should fall back to full image enrichment (caption + OCR) for the summary
// LLM call. Above this threshold the document has enough native text that
// caption-only enrichment is preferable (OCR text from incidental figures
// would otherwise add noise without contributing to the main topic).
const imageDominatedTextThreshold = 200
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// errInsufficientSummaryContent signals that getSummary refused to call the
// LLM because the document had no usable text after image markup was stripped
// (typical for scanned PDFs where VLM OCR yielded nothing). Callers should
// mark the knowledge's summary as failed instead of falling back to the first
// chunk's raw content (which would just be a bare image reference).
var (
errInsufficientSummaryContent = errors.New("insufficient text content for summary generation")
errEmptySummaryOutput = errors.New("summary model returned empty output")
fix(summary): 坏 JSON 不再冒充文档摘要(截断/畸形 JSON 走失败路径,纯文本兜底保留) (#3769) * fix(summary): 坏 JSON 不再冒充文档摘要 非流式文档摘要(Chat)解析失败时原先把模型原文当摘要落库:被 MaxTokens 截断的半截 JSON 会写进 knowledges.description、置 SummaryStatus=Completed (Asynq 不再重试),同一段文本还会被 buildSummaryChunkContent 索引进 RAG。 - parseDocumentSummaryOutput 改为返回 (*documentSummaryResult, error): 回复形如 JSON(含 markdown 代码围栏)却解析失败、或解析成功但取不到 summary/gist 时返回 errSummaryOutputNotParsable,绝不回退成原文; 非 JSON 的纯文本仍走原有的原文兜底,自定义模板 / 老模型不受影响。 - validateSummaryOutput 复用 chatpipeline.IsLengthFinishReason, FinishReason 为 length 类取值时返回 errSummaryOutputTruncated。 - 两个 sentinel 经 getSummary 汇入既有失败路径(ProcessSummaryGeneration 的 handleRetryableSummaryFailure、RegenerateKnowledgeSummary 的 handleGenerationFailure):保留旧描述、置 pending/failed 交给 Asynq 重试, 不再以 Completed 落库。 测试:TestParseDocumentSummaryOutput 改为表驱动(截断 JSON、含裸换行 JSON、 无文本 JSON 必须报错且不能把原文当 Summary;纯文本兜底继续通过); TestValidateSummaryOutput 增加 length / max_tokens 截断用例; TestGetSummaryRejectsUnusableModelOutput 锁住 getSummary 的错误传播。 * fix(summary): length 截断判定收窄到 JSON 形状回复 非流式文档摘要在校验模型回复时先看 finish_reason:只要 provider 报告 length/max_tokens 就返回 errSummaryOutputTruncated。该判定不认识内容形状, 于是自定义纯文本模板一旦顶到输出预算,就从「截断但可用」变成重试直到 SummaryStatusFailed,与上一提交承诺的「非 JSON 的纯文本仍走原兜底」相反。 - validateSummaryOutput 恢复为只看内容是否为空;新增 validateStructuredSummaryDocument 供 getSummary 使用:先判形状再判 length,只有确实在产结构化摘要(能解析成对象/数组,或 { 开头、[ 开头接 对象/数组/字符串元素)且被预算截断时才返回 errSummaryOutputTruncated。 - 形状判定剥离 UTF-8 BOM、前后空白与一层 markdown 围栏后再尝试 json.Unmarshal;「[文档摘要] …」「[1] …」这类带方括号引用的纯文本不再被 误判成坏 JSON,而截断的 {summary: 与截断的 JSON 数组仍然报错。 - parseDocumentSummaryOutput 同步剥离 BOM:BOM 前缀的截断 JSON 之前会被 当成纯文本落库。 - 表格描述 / 列描述仍走 validateSummaryOutput,截断的描述照旧可索引。 --------- Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 17:21:01 +00:00
// errSummaryOutputNotParsable marks a reply that is JSON-shaped but yields
// no usable summary text — broken JSON (cut off at the completion budget,
// unescaped newline) or an object without summary/gist. It is deliberately
// not stored: the raw reply is not a summary.
errSummaryOutputNotParsable = errors.New("summary model returned JSON without a usable summary")
// errSummaryOutputTruncated marks a reply the provider stopped at the
// completion budget, so its JSON can never be trusted as complete.
errSummaryOutputTruncated = errors.New("summary model output was truncated at the completion budget")
)
const summaryFallbackMaxRunes = 500
// validateSummaryOutput rejects successful model responses that contain no
fix(summary): 坏 JSON 不再冒充文档摘要(截断/畸形 JSON 走失败路径,纯文本兜底保留) (#3769) * fix(summary): 坏 JSON 不再冒充文档摘要 非流式文档摘要(Chat)解析失败时原先把模型原文当摘要落库:被 MaxTokens 截断的半截 JSON 会写进 knowledges.description、置 SummaryStatus=Completed (Asynq 不再重试),同一段文本还会被 buildSummaryChunkContent 索引进 RAG。 - parseDocumentSummaryOutput 改为返回 (*documentSummaryResult, error): 回复形如 JSON(含 markdown 代码围栏)却解析失败、或解析成功但取不到 summary/gist 时返回 errSummaryOutputNotParsable,绝不回退成原文; 非 JSON 的纯文本仍走原有的原文兜底,自定义模板 / 老模型不受影响。 - validateSummaryOutput 复用 chatpipeline.IsLengthFinishReason, FinishReason 为 length 类取值时返回 errSummaryOutputTruncated。 - 两个 sentinel 经 getSummary 汇入既有失败路径(ProcessSummaryGeneration 的 handleRetryableSummaryFailure、RegenerateKnowledgeSummary 的 handleGenerationFailure):保留旧描述、置 pending/failed 交给 Asynq 重试, 不再以 Completed 落库。 测试:TestParseDocumentSummaryOutput 改为表驱动(截断 JSON、含裸换行 JSON、 无文本 JSON 必须报错且不能把原文当 Summary;纯文本兜底继续通过); TestValidateSummaryOutput 增加 length / max_tokens 截断用例; TestGetSummaryRejectsUnusableModelOutput 锁住 getSummary 的错误传播。 * fix(summary): length 截断判定收窄到 JSON 形状回复 非流式文档摘要在校验模型回复时先看 finish_reason:只要 provider 报告 length/max_tokens 就返回 errSummaryOutputTruncated。该判定不认识内容形状, 于是自定义纯文本模板一旦顶到输出预算,就从「截断但可用」变成重试直到 SummaryStatusFailed,与上一提交承诺的「非 JSON 的纯文本仍走原兜底」相反。 - validateSummaryOutput 恢复为只看内容是否为空;新增 validateStructuredSummaryDocument 供 getSummary 使用:先判形状再判 length,只有确实在产结构化摘要(能解析成对象/数组,或 { 开头、[ 开头接 对象/数组/字符串元素)且被预算截断时才返回 errSummaryOutputTruncated。 - 形状判定剥离 UTF-8 BOM、前后空白与一层 markdown 围栏后再尝试 json.Unmarshal;「[文档摘要] …」「[1] …」这类带方括号引用的纯文本不再被 误判成坏 JSON,而截断的 {summary: 与截断的 JSON 数组仍然报错。 - parseDocumentSummaryOutput 同步剥离 BOM:BOM 前缀的截断 JSON 之前会被 当成纯文本落库。 - 表格描述 / 列描述仍走 validateSummaryOutput,截断的描述照旧可索引。 --------- Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 17:21:01 +00:00
// user-visible text. It only looks at the content shape: a provider that
// stopped at the completion budget can still return usable text, and the older
// plain-text consumers (custom summary templates, table/column descriptions)
// deliberately keep whatever the model produced.
func validateSummaryOutput(response *types.ChatResponse) (string, error) {
if response == nil {
return "", errEmptySummaryOutput
}
content := strings.TrimSpace(response.Content)
if content == "" {
return "", errEmptySummaryOutput
}
return content, nil
}
fix(summary): 坏 JSON 不再冒充文档摘要(截断/畸形 JSON 走失败路径,纯文本兜底保留) (#3769) * fix(summary): 坏 JSON 不再冒充文档摘要 非流式文档摘要(Chat)解析失败时原先把模型原文当摘要落库:被 MaxTokens 截断的半截 JSON 会写进 knowledges.description、置 SummaryStatus=Completed (Asynq 不再重试),同一段文本还会被 buildSummaryChunkContent 索引进 RAG。 - parseDocumentSummaryOutput 改为返回 (*documentSummaryResult, error): 回复形如 JSON(含 markdown 代码围栏)却解析失败、或解析成功但取不到 summary/gist 时返回 errSummaryOutputNotParsable,绝不回退成原文; 非 JSON 的纯文本仍走原有的原文兜底,自定义模板 / 老模型不受影响。 - validateSummaryOutput 复用 chatpipeline.IsLengthFinishReason, FinishReason 为 length 类取值时返回 errSummaryOutputTruncated。 - 两个 sentinel 经 getSummary 汇入既有失败路径(ProcessSummaryGeneration 的 handleRetryableSummaryFailure、RegenerateKnowledgeSummary 的 handleGenerationFailure):保留旧描述、置 pending/failed 交给 Asynq 重试, 不再以 Completed 落库。 测试:TestParseDocumentSummaryOutput 改为表驱动(截断 JSON、含裸换行 JSON、 无文本 JSON 必须报错且不能把原文当 Summary;纯文本兜底继续通过); TestValidateSummaryOutput 增加 length / max_tokens 截断用例; TestGetSummaryRejectsUnusableModelOutput 锁住 getSummary 的错误传播。 * fix(summary): length 截断判定收窄到 JSON 形状回复 非流式文档摘要在校验模型回复时先看 finish_reason:只要 provider 报告 length/max_tokens 就返回 errSummaryOutputTruncated。该判定不认识内容形状, 于是自定义纯文本模板一旦顶到输出预算,就从「截断但可用」变成重试直到 SummaryStatusFailed,与上一提交承诺的「非 JSON 的纯文本仍走原兜底」相反。 - validateSummaryOutput 恢复为只看内容是否为空;新增 validateStructuredSummaryDocument 供 getSummary 使用:先判形状再判 length,只有确实在产结构化摘要(能解析成对象/数组,或 { 开头、[ 开头接 对象/数组/字符串元素)且被预算截断时才返回 errSummaryOutputTruncated。 - 形状判定剥离 UTF-8 BOM、前后空白与一层 markdown 围栏后再尝试 json.Unmarshal;「[文档摘要] …」「[1] …」这类带方括号引用的纯文本不再被 误判成坏 JSON,而截断的 {summary: 与截断的 JSON 数组仍然报错。 - parseDocumentSummaryOutput 同步剥离 BOM:BOM 前缀的截断 JSON 之前会被 当成纯文本落库。 - 表格描述 / 列描述仍走 validateSummaryOutput,截断的描述照旧可索引。 --------- Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 17:21:01 +00:00
// validateStructuredSummaryDocument is the validator for the document-summary
// entry point (getSummary). On top of validateSummaryOutput it rejects a reply
// the provider cut off at the completion budget — but only when the reply was
// producing a structured summary, because that is the case where the truncated
// text is half a JSON object. A plain-text summary that hit the budget is
// still usable text and keeps the legacy fallback.
//
// The shape is judged before the finish reason, so "finish_reason=length" can
// never turn a plain-text reply into a failure on its own.
func validateStructuredSummaryDocument(response *types.ChatResponse) (string, error) {
content, err := validateSummaryOutput(response)
if err != nil {
return "", err
}
structured := summaryReplyIsJSONShaped(content)
if structured && chatpipeline.IsLengthFinishReason(response.FinishReason) {
return "", errSummaryOutputTruncated
}
return content, nil
}
// firstTextChunkSummaryFallback preserves the existing deterministic fallback:
// use the first already-ordered text chunk and cap it by runes so Chinese and
// emoji are never cut in the middle of a UTF-8 sequence.
func firstTextChunkSummaryFallback(textChunks []*types.Chunk) string {
if len(textChunks) == 0 || textChunks[0] == nil {
return ""
}
fallback := strings.TrimSpace(textChunks[0].Content)
runes := []rune(fallback)
if len(runes) > summaryFallbackMaxRunes {
fallback = string(runes[:summaryFallbackMaxRunes])
}
return fallback
}
// applyRetryableSummaryFailureState keeps an existing description visible
// while another attempt is queued, then publishes the deterministic fallback
// and marks only the summary subtask failed after the retry budget is exhausted.
func applyRetryableSummaryFailureState(
knowledge *types.Knowledge, textChunks []*types.Chunk, willRetry bool,
) string {
knowledge.UpdatedAt = time.Now()
if willRetry {
knowledge.SummaryStatus = types.SummaryStatusPending
return ""
}
fallback := firstTextChunkSummaryFallback(textChunks)
knowledge.Description = fallback
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
knowledge.Profile = nil
knowledge.SummaryStatus = types.SummaryStatusFailed
return fallback
}
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
// saveSummaryState persists only the columns the summary task owns. The task
// holds a row snapshot across its LLM call; a full-row save of it wrote the
// parse status of that moment back over a cancel, a housekeeping failure or
// a reparse that landed meanwhile. Over a reparse it put "finalizing" on the
// new run's "processing" row, whose post-process then found the row no
// longer processing, skipped its fan-out and left it stuck.
func (s *knowledgeService) saveSummaryState(ctx context.Context, knowledge *types.Knowledge) error {
if knowledge.UpdatedAt.IsZero() {
knowledge.UpdatedAt = time.Now()
}
return s.repo.UpdateKnowledgeColumns(ctx, knowledge.ID, map[string]interface{}{
"description": knowledge.Description,
"profile": knowledge.Profile,
"summary_status": knowledge.SummaryStatus,
"updated_at": knowledge.UpdatedAt,
})
}
// summaryTaskWillRetry reports whether the current Asynq delivery has another
// configured attempt remaining. Calls outside an Asynq worker are terminal.
// Despite the name it is not summary-specific; processChunks uses it too.
func summaryTaskWillRetry(ctx context.Context) bool {
retried, retryOK := asynq.GetRetryCount(ctx)
maxRetry, maxRetryOK := asynq.GetMaxRetry(ctx)
if retryOK && maxRetryOK {
return retried < maxRetry
}
retried, maxRetry, ok := types.TaskRetryMetadataFromContext(ctx)
return ok && retried < maxRetry
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// checkSufficientSummaryContent returns errInsufficientSummaryContent if the
// given content does not carry enough real text (after stripping image markup)
// for an LLM summary call, and logs a warning at the call site. Returns nil
// when the content passes the threshold.
//
// Extracted so the threshold gate can be unit-tested without standing up the
// full ProcessSummaryGeneration dependency graph.
func checkSufficientSummaryContent(ctx context.Context, knowledgeID, content string) error {
realTextLen := realTextRuneCount(content)
if realTextLen < minTextContentRunes {
logger.GetLogger(ctx).Warnf(
"summary content check: knowledge %s has insufficient text after stripping image markup (real_text_runes=%d, min=%d); skipping LLM call",
knowledgeID, realTextLen, minTextContentRunes,
)
return errInsufficientSummaryContent
}
return nil
}
// sortChunksForSummary orders chunks for document reconstruction. Parser
// StartAt offsets stay authoritative until any chunk has been manually edited;
// after that ChunkIndex is the safer reading order.
func sortChunksForSummary(chunks []*types.Chunk) []*types.Chunk {
sorted := make([]*types.Chunk, len(chunks))
copy(sorted, chunks)
edited := false
for _, chunk := range sorted {
if chunk.ContentRevision > 0 {
edited = true
break
}
}
sort.Slice(sorted, func(i, j int) bool {
if edited {
if sorted[i].ChunkIndex != sorted[j].ChunkIndex {
return sorted[i].ChunkIndex < sorted[j].ChunkIndex
}
return sorted[i].ID < sorted[j].ID
}
return sorted[i].StartAt < sorted[j].StartAt
})
return sorted
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// getSummary generates a summary for knowledge content using an AI model
func (s *knowledgeService) getSummary(ctx context.Context,
summaryModel chat.Chat, knowledge *types.Knowledge, chunks []*types.Chunk,
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
) (*documentSummaryResult, error) {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Get knowledge info from the first chunk
if len(chunks) == 0 {
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
return nil, fmt.Errorf("no chunks provided for summary generation")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// Determine max input chars from config
maxInputChars := defaultMaxInputChars
if s.config.Conversation.Summary != nil && s.config.Conversation.Summary.MaxInputChars > 0 {
maxInputChars = s.config.Conversation.Summary.MaxInputChars
}
// Sort chunks for reconstruction. Parser offsets remain authoritative until
// any chunk has been manually edited; after that ChunkIndex is safer.
sortedChunks := sortChunksForSummary(chunks)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Reconstruct the document before enriching it with image info. Enrichment
// must happen AFTER reconstruction because StartAt is based on original
// document offsets; enriched (longer) content would break the positioning.
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
chunkContents := ""
hasEditedChunk := false
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
for _, chunk := range sortedChunks {
if chunk.ContentRevision > 0 {
hasEditedChunk = true
break
}
}
if hasEditedChunk {
// Parser offsets describe the immutable source. Once a replacement has
// changed length they can no longer be applied to the effective content;
// concatenate current chunks instead of truncating at stale offsets.
parts := make([]string, 0, len(sortedChunks))
for _, chunk := range sortedChunks {
if chunk.IsEnabled && strings.TrimSpace(chunk.Content) != "" {
parts = append(parts, chunk.Content)
}
}
chunkContents = strings.Join(parts, "\n\n")
} else {
// Synthetic table headers are not represented in StartAt/EndAt. Match
// real text overlap instead of slicing by source offsets.
chunkContents = searchutil.MergeTextChunks(sortedChunks, "")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// Collect image_info from image_ocr/image_caption children and enrich
chunkIDs := make([]string, len(sortedChunks))
for i, c := range sortedChunks {
chunkIDs[i] = c.ID
}
imageInfoMap := searchutil.CollectImageInfoByChunkIDs(ctx, s.chunkRepo, knowledge.TenantID, chunkIDs)
mergedImageInfo := searchutil.MergeImageInfoJSON(imageInfoMap)
if mergedImageInfo != "" {
// For image-dominated documents (e.g. a docx whose only payload is a
// single embedded picture, or a screenshot-only file), captions alone
// often carry too little signal — the real content lives in OCR text.
// Detect that case by measuring the document's real (non-image-markup)
// text BEFORE enrichment, and switch to full enrichment (caption + OCR)
// when the body is essentially empty. Text-heavy documents stay on the
// caption-only path to avoid OCR noise (page headers/footers/watermarks
// from many figures diluting the main topic).
if realTextRuneCount(chunkContents) < imageDominatedTextThreshold {
// Caption + OCR (no URL/original wrappers — those are pure noise
// for the summary LLM and have been observed to trigger the
// "image reference with no extracted text" refusal heuristic).
chunkContents = searchutil.EnrichContentCaptionAndOCR(chunkContents, mergedImageInfo)
} else {
chunkContents = searchutil.EnrichContentCaptionOnly(chunkContents, mergedImageInfo)
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// Apply length limit: sample long content to fit within maxInputChars
chunkContents = sampleLongContent(chunkContents, maxInputChars)
logger.GetLogger(ctx).Infof("getSummary: content length=%d chars (max=%d) for knowledge %s",
len([]rune(chunkContents)), maxInputChars, knowledge.ID)
// Bail out before the LLM call when there is not enough actual text to
// summarise. We deliberately do not pass filename/file-type metadata to the
// LLM: scanned PDFs frequently carry filenames like "MX5280.pdf" (the
// scanner model), and feeding that to the model would invite it to
// hallucinate a scanner manual instead of admitting the document had no
// extractable text.
if err := checkSufficientSummaryContent(ctx, knowledge.ID, chunkContents); err != nil {
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
return nil, err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// User-authored metadata is trusted document context. Internal ingestion
// metadata remains excluded because it contains IDs and pipeline controls.
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
contentWithMetadata := chunkContents
if custom := knowledge.CustomMetadataText(); custom != "" {
contentWithMetadata = "Document metadata:\n" + custom + "\n\nDocument content:\n" + chunkContents
}
contentWithMetadata = sampleLongContent(contentWithMetadata, maxInputChars)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Determine max output tokens from config
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
maxTokens := defaultSummaryMaxTokens
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if s.config.Conversation.Summary != nil && s.config.Conversation.Summary.MaxCompletionTokens > 0 {
maxTokens = s.config.Conversation.Summary.MaxCompletionTokens
}
// Generate summary using AI model
summaryPrompt := types.RenderPromptPlaceholders(s.config.Conversation.GenerateSummaryPrompt, types.PlaceholderValues{
"language": types.LanguageNameFromContext(ctx),
})
thinking := false
modelCtx := types.WithLLMCallMetadata(ctx, "document_summary", "")
summary, err := summaryModel.Chat(modelCtx, []chat.Message{
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
{
Role: "system",
Content: summaryPrompt,
},
{
Role: "user",
Content: contentWithMetadata,
},
}, &chat.ChatOptions{
Temperature: 0.3,
MaxTokens: maxTokens,
Thinking: &thinking,
})
if err != nil {
logger.GetLogger(ctx).WithField("error", err).Errorf("GetSummary failed")
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
return nil, err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
fix(summary): 坏 JSON 不再冒充文档摘要(截断/畸形 JSON 走失败路径,纯文本兜底保留) (#3769) * fix(summary): 坏 JSON 不再冒充文档摘要 非流式文档摘要(Chat)解析失败时原先把模型原文当摘要落库:被 MaxTokens 截断的半截 JSON 会写进 knowledges.description、置 SummaryStatus=Completed (Asynq 不再重试),同一段文本还会被 buildSummaryChunkContent 索引进 RAG。 - parseDocumentSummaryOutput 改为返回 (*documentSummaryResult, error): 回复形如 JSON(含 markdown 代码围栏)却解析失败、或解析成功但取不到 summary/gist 时返回 errSummaryOutputNotParsable,绝不回退成原文; 非 JSON 的纯文本仍走原有的原文兜底,自定义模板 / 老模型不受影响。 - validateSummaryOutput 复用 chatpipeline.IsLengthFinishReason, FinishReason 为 length 类取值时返回 errSummaryOutputTruncated。 - 两个 sentinel 经 getSummary 汇入既有失败路径(ProcessSummaryGeneration 的 handleRetryableSummaryFailure、RegenerateKnowledgeSummary 的 handleGenerationFailure):保留旧描述、置 pending/failed 交给 Asynq 重试, 不再以 Completed 落库。 测试:TestParseDocumentSummaryOutput 改为表驱动(截断 JSON、含裸换行 JSON、 无文本 JSON 必须报错且不能把原文当 Summary;纯文本兜底继续通过); TestValidateSummaryOutput 增加 length / max_tokens 截断用例; TestGetSummaryRejectsUnusableModelOutput 锁住 getSummary 的错误传播。 * fix(summary): length 截断判定收窄到 JSON 形状回复 非流式文档摘要在校验模型回复时先看 finish_reason:只要 provider 报告 length/max_tokens 就返回 errSummaryOutputTruncated。该判定不认识内容形状, 于是自定义纯文本模板一旦顶到输出预算,就从「截断但可用」变成重试直到 SummaryStatusFailed,与上一提交承诺的「非 JSON 的纯文本仍走原兜底」相反。 - validateSummaryOutput 恢复为只看内容是否为空;新增 validateStructuredSummaryDocument 供 getSummary 使用:先判形状再判 length,只有确实在产结构化摘要(能解析成对象/数组,或 { 开头、[ 开头接 对象/数组/字符串元素)且被预算截断时才返回 errSummaryOutputTruncated。 - 形状判定剥离 UTF-8 BOM、前后空白与一层 markdown 围栏后再尝试 json.Unmarshal;「[文档摘要] …」「[1] …」这类带方括号引用的纯文本不再被 误判成坏 JSON,而截断的 {summary: 与截断的 JSON 数组仍然报错。 - parseDocumentSummaryOutput 同步剥离 BOM:BOM 前缀的截断 JSON 之前会被 当成纯文本落库。 - 表格描述 / 列描述仍走 validateSummaryOutput,截断的描述照旧可索引。 --------- Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 17:21:01 +00:00
content, err := validateStructuredSummaryDocument(summary)
if err != nil {
logger.GetLogger(ctx).WithField("error", err).Warnf("GetSummary returned no usable content")
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
return nil, err
}
fix(summary): 坏 JSON 不再冒充文档摘要(截断/畸形 JSON 走失败路径,纯文本兜底保留) (#3769) * fix(summary): 坏 JSON 不再冒充文档摘要 非流式文档摘要(Chat)解析失败时原先把模型原文当摘要落库:被 MaxTokens 截断的半截 JSON 会写进 knowledges.description、置 SummaryStatus=Completed (Asynq 不再重试),同一段文本还会被 buildSummaryChunkContent 索引进 RAG。 - parseDocumentSummaryOutput 改为返回 (*documentSummaryResult, error): 回复形如 JSON(含 markdown 代码围栏)却解析失败、或解析成功但取不到 summary/gist 时返回 errSummaryOutputNotParsable,绝不回退成原文; 非 JSON 的纯文本仍走原有的原文兜底,自定义模板 / 老模型不受影响。 - validateSummaryOutput 复用 chatpipeline.IsLengthFinishReason, FinishReason 为 length 类取值时返回 errSummaryOutputTruncated。 - 两个 sentinel 经 getSummary 汇入既有失败路径(ProcessSummaryGeneration 的 handleRetryableSummaryFailure、RegenerateKnowledgeSummary 的 handleGenerationFailure):保留旧描述、置 pending/failed 交给 Asynq 重试, 不再以 Completed 落库。 测试:TestParseDocumentSummaryOutput 改为表驱动(截断 JSON、含裸换行 JSON、 无文本 JSON 必须报错且不能把原文当 Summary;纯文本兜底继续通过); TestValidateSummaryOutput 增加 length / max_tokens 截断用例; TestGetSummaryRejectsUnusableModelOutput 锁住 getSummary 的错误传播。 * fix(summary): length 截断判定收窄到 JSON 形状回复 非流式文档摘要在校验模型回复时先看 finish_reason:只要 provider 报告 length/max_tokens 就返回 errSummaryOutputTruncated。该判定不认识内容形状, 于是自定义纯文本模板一旦顶到输出预算,就从「截断但可用」变成重试直到 SummaryStatusFailed,与上一提交承诺的「非 JSON 的纯文本仍走原兜底」相反。 - validateSummaryOutput 恢复为只看内容是否为空;新增 validateStructuredSummaryDocument 供 getSummary 使用:先判形状再判 length,只有确实在产结构化摘要(能解析成对象/数组,或 { 开头、[ 开头接 对象/数组/字符串元素)且被预算截断时才返回 errSummaryOutputTruncated。 - 形状判定剥离 UTF-8 BOM、前后空白与一层 markdown 围栏后再尝试 json.Unmarshal;「[文档摘要] …」「[1] …」这类带方括号引用的纯文本不再被 误判成坏 JSON,而截断的 {summary: 与截断的 JSON 数组仍然报错。 - parseDocumentSummaryOutput 同步剥离 BOM:BOM 前缀的截断 JSON 之前会被 当成纯文本落库。 - 表格描述 / 列描述仍走 validateSummaryOutput,截断的描述照旧可索引。 --------- Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 17:21:01 +00:00
result, err := parseDocumentSummaryOutput(content)
if err != nil {
logger.GetLogger(ctx).WithField("error", err).Warnf("GetSummary returned unusable content")
return nil, err
}
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
logger.GetLogger(ctx).WithField("summary", result.Summary).
WithField("has_profile", result.Profile != nil).Infof("GetSummary success")
return result, nil
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// sampleLongContent returns content that fits within maxChars.
// For short content (≤ maxChars), it is returned as-is.
// For long content, it samples: head (60%), tail (20%), and evenly-spaced middle (20%),
// joined by "[...content omitted...]" markers so the LLM knows content was skipped.
func sampleLongContent(content string, maxChars int) string {
runes := []rune(content)
if len(runes) <= maxChars {
return content
}
const omitMarker = "\n\n[...content omitted...]\n\n"
omitRunes := len([]rune(omitMarker))
// Reserve space for two omit markers (head→middle, middle→tail)
usable := maxChars - 2*omitRunes
if usable < 100 {
// Fallback: just truncate
return string(runes[:maxChars])
}
headLen := usable * 60 / 100
tailLen := usable * 20 / 100
midLen := usable - headLen - tailLen
head := string(runes[:headLen])
tail := string(runes[len(runes)-tailLen:])
// Sample middle portion: take a contiguous block from the center of the document
midStart := len(runes)/2 - midLen/2
if midStart < headLen {
midStart = headLen
}
midEnd := midStart + midLen
if midEnd > len(runes)-tailLen {
midEnd = len(runes) - tailLen
midStart = midEnd - midLen
if midStart < headLen {
midStart = headLen
}
}
middle := string(runes[midStart:midEnd])
return head + omitMarker + middle + omitMarker + tail
}
// ProcessSummaryGeneration handles async summary generation task
func (s *knowledgeService) ProcessSummaryGeneration(ctx context.Context, t *asynq.Task) (retErr error) {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
var payload types.SummaryGenerationPayload
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
logger.Errorf(ctx, "Failed to unmarshal summary generation payload: %v", err)
return nil // Don't retry on unmarshal error
}
logger.Infof(ctx, "Processing summary generation for knowledge: %s", payload.KnowledgeID)
// Set tenant and language context
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
if payload.Language != "" {
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
}
// A newer attempt (re-upload / edit / reparse) has superseded this one:
// skip before opening the span or registering the FinalizeSubtask defer
// so we neither read stale chunks nor decrement the new attempt's counter.
if attemptSuperseded(ctx, s.tracker(), payload.KnowledgeID, payload.Attempt) {
logger.Infof(ctx, "summary: attempt %d superseded for %s, skipping stale enrichment",
payload.Attempt, payload.KnowledgeID)
return nil
}
if payload.Refresh {
var err error
ctx, err = restoreSummaryRefreshTenantInfo(ctx, s.tenantRepo, payload.TenantID)
if err == nil {
_, err = s.RegenerateKnowledgeSummary(ctx, payload.KnowledgeID)
}
if err != nil {
if errors.Is(err, ErrSummaryRefreshStale) {
logger.Infof(ctx, "Discarding stale summary refresh for knowledge %s", payload.KnowledgeID)
return nil
}
logger.Warnf(ctx, "Summary refresh failed for knowledge %s: %v", payload.KnowledgeID, err)
if errors.Is(err, errInsufficientSummaryContent) {
return nil
}
return err
}
return nil
}
// Open a subspan under the parent attempt's postprocess stage so the
// trace surface shows the real summary-generation duration (LLM call
// + chunk write + index) instead of just the upstream's enqueue time.
// Closes via the deferred handler below — every return path lands in
// the defer, including the early returns ahead.
span := s.beginPostprocessSubspan(ctx, payload.KnowledgeID, payload.Attempt, "postprocess.summary",
feat(timeline): scale axis to async tail, enrich span payloads, polish UI The post-process stage closes in ~9ms (just enqueue work) but its async subspans (postprocess.summary, postprocess.question, postprocess.graph) keep producing rows for tens of seconds AFTER the root finalizes. The old timeline used trace.duration_ms as the time axis maximum, which clipped those subspan bars past the right edge. Timeline: - totalMs now always takes max(trace.duration_ms, observed-tail), so the axis stretches to fit the latest descendant end regardless of parse_status. - Render a faint dashed wrapping outline behind a parent span when its descendants extend past its own finished_at, so the postprocess stage row visibly spans the full window without overloading the 9ms self-time bar. - Tree expand/collapse caret bumped from 10 to 14px in a 16x16 hit area; copy icons in detail panel bumped from 11/14 to 14/18px; .kp-kv-copy button grown from 18 to 22px. - Short input/output payloads (<= 8 entries / <= 600 bytes JSON) auto-expand inline so users see the actual data without an extra click; longer payloads keep the click-to-expand summary. Span payloads (subspans only - root keeps the canonical identity, no duplicate knowledge_id/kb_id/tenant_id on every child): - extract.go: graph subspan output gains chunk_chars, chunk_preview, sample_nodes, sample_relations. - summary subspan output gains model_id, summary_preview. - question subspan output gains model_id and a sample_question captured from the first non-empty LLM response. i18n: new key knowledgeStages.detail.includingChildren for the wrapping-bar tooltip. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 14:35:16 +00:00
types.JSONMap{
"language": payload.Language,
})
var summaryErr error
summaryOut := types.JSONMap{}
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
// profileKB is the knowledge base once loaded; the deferred handler uses
// it to schedule the knowledge-base description refresh on terminal exit.
var profileKB *types.KnowledgeBase
defer func() {
// Decrement the parent's enrichment counter on terminal exit.
// "Terminal" is keyed on the value RETURNED to asynq, not on
// summaryErr: several branches record a failure on the span
// (summaryErr != nil) yet deliberately `return nil` so asynq does
// NOT retry (e.g. insufficient text content, KB/knowledge fetch
// failures). Those are terminal and must drain — keying on
// summaryErr would skip them and leave the row stuck in
// "finalizing". When we DO return an error asynq will retry, so
// we only drain on the final attempt.
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
finalizeSubtaskDetached(ctx, s.repo, payload.KnowledgeID, "summary",
retErr, false, isFinalAsynqAttempt(ctx))
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
// Every terminal exit changes what the knowledge-base aggregation
// sees (a new profile, a cleared one, or a document that will never
// get one), so the debounced refresh is requested regardless of
// outcome. It is a no-op unless the KB opted in.
if retErr == nil && profileKB != nil {
_ = requestKnowledgeBaseProfileRefresh(ctx, s.task, profileKB, false)
}
if span == nil {
return
}
if summaryErr != nil {
s.failPostprocessSubspan(ctx, span, "SUMMARY_FAILED", summaryErr.Error(), summaryErr)
} else {
s.endPostprocessSubspan(ctx, span, summaryOut)
}
}()
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Get knowledge base
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, payload.KnowledgeBaseID)
if err != nil {
logger.Errorf(ctx, "Failed to get knowledge base: %v", err)
summaryErr = err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return nil
}
feat(timeline): scale axis to async tail, enrich span payloads, polish UI The post-process stage closes in ~9ms (just enqueue work) but its async subspans (postprocess.summary, postprocess.question, postprocess.graph) keep producing rows for tens of seconds AFTER the root finalizes. The old timeline used trace.duration_ms as the time axis maximum, which clipped those subspan bars past the right edge. Timeline: - totalMs now always takes max(trace.duration_ms, observed-tail), so the axis stretches to fit the latest descendant end regardless of parse_status. - Render a faint dashed wrapping outline behind a parent span when its descendants extend past its own finished_at, so the postprocess stage row visibly spans the full window without overloading the 9ms self-time bar. - Tree expand/collapse caret bumped from 10 to 14px in a 16x16 hit area; copy icons in detail panel bumped from 11/14 to 14/18px; .kp-kv-copy button grown from 18 to 22px. - Short input/output payloads (<= 8 entries / <= 600 bytes JSON) auto-expand inline so users see the actual data without an extra click; longer payloads keep the click-to-expand summary. Span payloads (subspans only - root keeps the canonical identity, no duplicate knowledge_id/kb_id/tenant_id on every child): - extract.go: graph subspan output gains chunk_chars, chunk_preview, sample_nodes, sample_relations. - summary subspan output gains model_id, summary_preview. - question subspan output gains model_id and a sample_question captured from the first non-empty LLM response. i18n: new key knowledgeStages.detail.includingChildren for the wrapping-bar tooltip. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 14:35:16 +00:00
// Capture the resolved model id on the span output the moment we
// know it — debugging "summary stage took 60s" benefits hugely from
// seeing WHICH chat model was actually used (kb config drift, fall-
// throughs to a slow upstream, etc.).
summaryOut["model_id"] = kb.SummaryModelID
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
profileKB = kb
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if kb.SummaryModelID == "" {
logger.Warn(ctx, "Knowledge base summary model ID is empty, skipping summary generation")
_ = s.repo.UpdateKnowledgeColumn(ctx, payload.KnowledgeID, "summary_status", types.SummaryStatusFailed)
summaryOut["skipped"] = "no_summary_model"
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return nil
}
// Get knowledge
knowledge, err := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID)
if err != nil {
logger.Errorf(ctx, "Failed to get knowledge: %v", err)
summaryErr = err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return nil
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// Short-circuit when the user cancelled parsing or the row is being deleted.
if knowledge != nil {
switch knowledge.ParseStatus {
case types.ParseStatusCancelled, types.ParseStatusDeleting:
logger.Infof(ctx, "Summary generation: knowledge aborted (%s), skipping: %s",
knowledge.ParseStatus, payload.KnowledgeID)
summaryOut["skipped"] = "knowledge_" + knowledge.ParseStatus
return nil
}
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Update summary status to processing
knowledge.SummaryStatus = types.SummaryStatusProcessing
knowledge.UpdatedAt = time.Now()
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if err := s.saveSummaryState(ctx, knowledge); err != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Warnf(ctx, "Failed to update summary status to processing: %v", err)
}
// Helper function to mark summary as failed
markSummaryFailed := func() {
knowledge.SummaryStatus = types.SummaryStatusFailed
knowledge.UpdatedAt = time.Now()
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if err := s.saveSummaryState(ctx, knowledge); err != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Warnf(ctx, "Failed to update summary status to failed: %v", err)
}
}
// Get text chunks for this knowledge
chunks, err := s.chunkService.ListChunksByKnowledgeID(ctx, payload.KnowledgeID)
if err != nil {
logger.Errorf(ctx, "Failed to get chunks: %v", err)
markSummaryFailed()
summaryErr = err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return nil
}
// Filter text chunks only
textChunks := make([]*types.Chunk, 0)
for _, chunk := range chunks {
if chunk.ChunkType == types.ChunkTypeText {
textChunks = append(textChunks, chunk)
}
}
summaryOut["text_chunks"] = len(textChunks)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if len(textChunks) == 0 {
logger.Infof(ctx, "No text chunks found for knowledge: %s", payload.KnowledgeID)
knowledge.Description = ""
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
knowledge.Profile = nil
knowledge.SummaryStatus = types.SummaryStatusFailed
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
knowledge.UpdatedAt = time.Now()
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if err := s.saveSummaryState(ctx, knowledge); err != nil {
logger.Warnf(ctx, "Failed to mark summary failed for knowledge without text chunks: %v", err)
}
summaryOut["skipped"] = "no_text_chunks"
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return nil
}
// Sort chunks by ChunkIndex for proper ordering
sort.Slice(textChunks, func(i, j int) bool {
return textChunks[i].ChunkIndex < textChunks[j].ChunkIndex
})
summaryMetadataVersion := string(knowledge.CustomMetadata)
handleRetryableSummaryFailure := func(generationErr error) error {
summaryErr = generationErr
summaryOut["error"] = previewText(generationErr.Error(), 500)
summaryOut["error_type"] = fmt.Sprintf("%T", generationErr)
if summaryTaskWillRetry(ctx) {
applyRetryableSummaryFailureState(knowledge, textChunks, true)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
logger.Warnf(ctx, "Failed to mark summary pending for retry: %v", updateErr)
}
summaryOut["retrying"] = true
return fmt.Errorf("summary generation attempt failed: %w", generationErr)
}
// Before publishing the terminal fallback, make sure its source still
// matches the chunks and metadata captured for this attempt.
stale, staleErr := summarySourceChanged(
ctx, s.repo, s.chunkRepo, payload.TenantID, payload.KnowledgeID,
summaryMetadataVersion, textChunks,
)
if staleErr != nil {
logger.Errorf(ctx, "Failed to verify summary fallback freshness for knowledge %s: %v",
payload.KnowledgeID, staleErr)
markSummaryFailed()
summaryErr = staleErr
return fmt.Errorf("verify summary fallback freshness: %w", staleErr)
}
if stale {
logger.Infof(ctx, "Discarding stale summary fallback for knowledge %s", payload.KnowledgeID)
summaryOut["skipped"] = "content_revision_changed"
return nil
}
fallback := applyRetryableSummaryFailureState(knowledge, textChunks, false)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
logger.Errorf(ctx, "Failed to save terminal summary fallback: %v", updateErr)
summaryErr = updateErr
return fmt.Errorf("save terminal summary fallback: %w", updateErr)
}
if fallback == "" {
summaryOut["fallback"] = "empty"
} else {
summaryOut["fallback"] = "first_chunk"
}
summaryOut["fallback_chars"] = len([]rune(fallback))
return fmt.Errorf("summary generation exhausted retries: %w", generationErr)
}
// Initialize chat model for summary. Model resolution failures use the same
// retry budget and terminal first-chunk fallback as LLM request failures.
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
chatModel, err := s.modelService.GetChatModel(ctx, kb.SummaryModelID)
if err != nil {
logger.Errorf(ctx, "Failed to get chat model: %v", err)
return handleRetryableSummaryFailure(fmt.Errorf("get chat model: %w", err))
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// Generate summary
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
summaryResult, err := s.getSummary(ctx, chatModel, knowledge, textChunks)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
logger.Errorf(ctx, "Failed to generate summary for knowledge %s: %v", payload.KnowledgeID, err)
// Surface the underlying LLM/IO error on the span so the trace UI
// can explain "why did this stage take 60s and then fall back?"
// without forcing the operator to grep worker logs. We also capture
// the error type to disambiguate timeouts from upstream HTTP errors
// (deadline exceeded vs unexpected EOF vs 5xx, etc.).
summaryOut["error"] = previewText(err.Error(), 500)
summaryOut["error_type"] = fmt.Sprintf("%T", err)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// For the insufficient-content case (scanned PDF without OCR, etc.)
// we deliberately do NOT fall back to the first chunk's raw content,
// since that chunk is typically just a bare markdown image reference
// and surfacing it in the description is misleading.
if errors.Is(err, errInsufficientSummaryContent) {
knowledge.Description = ""
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
knowledge.Profile = nil
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
knowledge.SummaryStatus = types.SummaryStatusFailed
knowledge.UpdatedAt = time.Now()
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Errorf(ctx, "Failed to mark summary as failed: %v", updateErr)
summaryErr = updateErr
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return fmt.Errorf("failed to update knowledge: %w", updateErr)
}
summaryOut["fallback"] = "insufficient_content"
summaryErr = err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return nil
}
return handleRetryableSummaryFailure(err)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// Do not publish an answer derived from a superseded chunk or metadata
// version. A user can explicitly refresh again from the latest revision.
staleSummary, staleErr := summarySourceChanged(
ctx, s.repo, s.chunkRepo, payload.TenantID, payload.KnowledgeID, summaryMetadataVersion, textChunks,
)
if staleErr != nil {
logger.Errorf(ctx, "Failed to verify summary freshness for knowledge %s: %v", payload.KnowledgeID, staleErr)
markSummaryFailed()
summaryErr = staleErr
return fmt.Errorf("verify summary freshness: %w", staleErr)
}
if staleSummary {
logger.Infof(ctx, "Discarding stale summary for knowledge %s", payload.KnowledgeID)
summaryOut["skipped"] = "content_revision_changed"
return nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
// Update knowledge description and structured profile
summary := summaryResult.Summary
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
knowledge.Description = summary
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
knowledge.Profile = summaryResult.Profile
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
knowledge.SummaryStatus = types.SummaryStatusCompleted
knowledge.UpdatedAt = time.Now()
summaryOut["summary_chars"] = len([]rune(summary))
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
summaryOut["has_profile"] = summaryResult.Profile != nil
feat(timeline): scale axis to async tail, enrich span payloads, polish UI The post-process stage closes in ~9ms (just enqueue work) but its async subspans (postprocess.summary, postprocess.question, postprocess.graph) keep producing rows for tens of seconds AFTER the root finalizes. The old timeline used trace.duration_ms as the time axis maximum, which clipped those subspan bars past the right edge. Timeline: - totalMs now always takes max(trace.duration_ms, observed-tail), so the axis stretches to fit the latest descendant end regardless of parse_status. - Render a faint dashed wrapping outline behind a parent span when its descendants extend past its own finished_at, so the postprocess stage row visibly spans the full window without overloading the 9ms self-time bar. - Tree expand/collapse caret bumped from 10 to 14px in a 16x16 hit area; copy icons in detail panel bumped from 11/14 to 14/18px; .kp-kv-copy button grown from 18 to 22px. - Short input/output payloads (<= 8 entries / <= 600 bytes JSON) auto-expand inline so users see the actual data without an extra click; longer payloads keep the click-to-expand summary. Span payloads (subspans only - root keeps the canonical identity, no duplicate knowledge_id/kb_id/tenant_id on every child): - extract.go: graph subspan output gains chunk_chars, chunk_preview, sample_nodes, sample_relations. - summary subspan output gains model_id, summary_preview. - question subspan output gains model_id and a sample_question captured from the first non-empty LLM response. i18n: new key knowledgeStages.detail.includingChildren for the wrapping-bar tooltip. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 14:35:16 +00:00
// Preview the generated summary on the span output so the trace
// viewer can show "this is what the LLM produced" at a glance,
// without hopping to the knowledge-detail page. Capped to keep
// span rows compact.
summaryOut["summary_preview"] = previewText(summary, 240)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if err := s.saveSummaryState(ctx, knowledge); err != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Errorf(ctx, "Failed to update knowledge description: %v", err)
summaryErr = err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return fmt.Errorf("failed to update knowledge: %w", err)
}
// Create summary chunk and index it — only when RAG indexing is enabled.
// Wiki-only KBs don't need summary chunks in the vector index.
if strings.TrimSpace(summary) != "" && kb.NeedsEmbeddingModel() {
// Get max chunk index
maxChunkIndex := 0
for _, chunk := range chunks {
if chunk.ChunkIndex > maxChunkIndex {
maxChunkIndex = chunk.ChunkIndex
}
}
// Embed only the LLM-generated summary in the indexed chunk.
// We deliberately omit knowledge.FileName here: filenames are an
// unreliable signal (e.g. "MX5280.pdf" for a scanned legal letter)
// and surfacing them in retrieved RAG context can re-introduce the
// hallucination vector this branch is meant to close.
summaryChunk := &types.Chunk{
ID: uuid.New().String(),
TenantID: knowledge.TenantID,
KnowledgeID: knowledge.ID,
KnowledgeBaseID: knowledge.KnowledgeBaseID,
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
Content: buildSummaryChunkContent(summary, summaryResult.Profile),
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
ChunkIndex: maxChunkIndex + 1,
IsEnabled: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
StartAt: 0,
EndAt: 0,
ChunkType: types.ChunkTypeSummary,
ParentChunkID: textChunks[0].ID,
}
// Save summary chunk
if err := s.chunkRepo.CreateChunks(ctx, []*types.Chunk{summaryChunk}); err != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Errorf(ctx, "Failed to create summary chunk: %v", err)
summaryErr = err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return fmt.Errorf("failed to create summary chunk: %w", err)
}
// Index summary chunk
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
if err != nil {
logger.Errorf(ctx, "Failed to get tenant info: %v", err)
summaryErr = err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return fmt.Errorf("failed to get tenant info: %w", err)
}
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenantInfo)
refactor(retriever): introduce factory for KB-scoped retrieve engine resolution Extracts the 25 repeated NewCompositeRetrieveEngine call sites across seven services into two factory functions with tenant-ownership verification: CreateRetrieveEngineForKB (synchronous) and CreateRetrieveEngineFromPayload (async task handlers). Promotes GetByStoreID from concrete-only to interfaces.RetrieveEngineRegistry. Extends KBDeletePayload / IndexDeletePayload with an omitempty VectorStoreID snapshot. Design highlights - Factory verifies tenant ownership of the resolved store (defense-in-depth) so a gap in PR3 validation or a tampered Asynq payload cannot cross tenants. Cross-tenant attempts return ErrVectorStoreForbidden with a structured log entry. - Sentinel errors (ErrTenantInfoMissing, ErrVectorStoreNotFound, ErrVectorStoreForbidden) let async handlers classify non-retryable failures as asynq.SkipRetry. - nil and empty-string pointers for vectorStoreID normalize to "unbound" so callers never send an empty UUID to GetByStoreID. - resolveBoundEngine constructs engineInfos directly (with slices.Clone of Support()) instead of going through NewCompositeRetrieveEngine. The latter only reads from the byEngineType map and cannot reach DB stores in byStoreID -- multiple stores can share the same engine type. Unbound fallbacks still reuse NewCompositeRetrieveEngine so the tenant effective-engines path is byte-for-byte unchanged. - DeleteKnowledgeBase now reads the KB before soft-delete so the enqueued KBDeletePayload carries a VectorStoreID snapshot; once the row is soft-deleted GORM's default scope hides it. Cost: +1 SELECT per KB-delete request (a rare admin operation). - enqueueIndexDeleteTask gains a vectorStoreID *string parameter that the single caller (tag.go) populates from the owning KB. The worker (ProcessIndexDelete) validates ownership via the factory. - cleanupKnowledgeResources loads the KB so bound-store cleanup routes correctly. If the load fails it warns and falls back to tenant effective engines; orphan vectors become observable in logs instead of disappearing silently. - DeleteKnowledges (batch) stays on the tenant effective-engines path -- batches can span stores and multi-store fan-out is PR4 scope. Noted inline. Merge safety All knowledge bases have VectorStoreID = NULL at merge time (introduced nullable in PR1, Tencent/WeKnora#994). Every factory call falls back to NewCompositeRetrieveEngine(registry, tenantInfo.GetEffectiveEngines()), which is the existing code path for these KBs. Async payloads from before this change decode to VectorStoreID = nil (omitempty) and take the same fallback. Testing - go build ./... - go vet ./... - go test -race -count=1 ./internal/application/service/retriever/... covers unbound (nil/empty), bound, cross-tenant, unregistered store, ownership infra error, legacy payload shapes (missing field/null/ empty string/nil), tampered payload, and parallel invocation. - grep -r NewCompositeRetrieveEngine internal/application/service returns zero results outside factory.go/composite.go. Refs: Part of Tencent/WeKnora#993. Depends on Tencent/WeKnora#994.
2026-05-13 08:24:17 +00:00
retrieveEngine, err := retriever.CreateRetrieveEngineForKB(
ctx, s.retrieveEngine, s.ownership, tenantInfo.ID, kb.VectorStoreID)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
logger.Errorf(ctx, "Failed to init retrieve engine: %v", err)
summaryErr = err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return fmt.Errorf("failed to init retrieve engine: %w", err)
}
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
if err != nil {
logger.Errorf(ctx, "Failed to get embedding model: %v", err)
summaryErr = err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return fmt.Errorf("failed to get embedding model: %w", err)
}
indexInfo := []*types.IndexInfo{{
Content: summaryChunk.Content,
SourceID: summaryChunk.ID,
SourceType: types.ChunkSourceType,
ChunkID: summaryChunk.ID,
KnowledgeID: knowledge.ID,
KnowledgeBaseID: knowledge.KnowledgeBaseID,
IsEnabled: true,
}}
if err := retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfo); err != nil {
logger.Errorf(ctx, "Failed to index summary chunk: %v", err)
summaryErr = err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return fmt.Errorf("failed to index summary chunk: %w", err)
}
logger.Infof(ctx, "Successfully created and indexed summary chunk for knowledge: %s", payload.KnowledgeID)
summaryOut["summary_chunk_indexed"] = true
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
logger.Infof(ctx, "Successfully generated summary for knowledge: %s", payload.KnowledgeID)
summaryOut["status"] = "completed"
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return nil
}
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
// ProcessQuestionGeneration handles async question generation task. It
// dispatches between the batched fan-out path (current: one task per window of
// text chunks, payload.ChunkIDs set) and the legacy whole-knowledge path (kept
// for tasks enqueued before fan-out shipped, no chunk ids). A lone ChunkID
// (from an interim per-chunk build) is treated as a one-element batch.
func (s *knowledgeService) ProcessQuestionGeneration(ctx context.Context, t *asynq.Task) (retErr error) {
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
var payload types.QuestionGenerationPayload
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
logger.Errorf(ctx, "Failed to unmarshal question generation payload: %v", err)
return nil // Don't retry on unmarshal error
}
if len(payload.ChunkIDs) > 0 || payload.ChunkID != "" {
return s.processQuestionGenerationForChunks(ctx, t, payload)
}
return s.processQuestionGenerationForKnowledge(ctx, t, payload)
}
// processQuestionGenerationForKnowledge is the legacy whole-knowledge handler:
// it iterates every text chunk of the knowledge in one task. Retained for
// in-flight tasks queued before per-chunk fan-out; new enqueues always set
// payload.ChunkID and take the per-chunk path instead.
func (s *knowledgeService) processQuestionGenerationForKnowledge(ctx context.Context, t *asynq.Task, payload types.QuestionGenerationPayload) (retErr error) {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
taskStartedAt := time.Now()
retryCount, _ := asynq.GetRetryCount(ctx)
maxRetry, _ := asynq.GetMaxRetry(ctx)
exitStatus := "success"
totalChunks := 0
totalTextChunks := 0
emptyContentChunks := 0
llmCallAttempts := 0
llmCallSuccess := 0
llmCallFailed := 0
llmCallEmpty := 0
generatedQuestionsTotal := 0
chunkMetadataSetFailed := 0
chunkUpdateFailed := 0
indexEntriesPrepared := 0
indexBatchAttempted := false
indexBatchSucceeded := false
feat(timeline): scale axis to async tail, enrich span payloads, polish UI The post-process stage closes in ~9ms (just enqueue work) but its async subspans (postprocess.summary, postprocess.question, postprocess.graph) keep producing rows for tens of seconds AFTER the root finalizes. The old timeline used trace.duration_ms as the time axis maximum, which clipped those subspan bars past the right edge. Timeline: - totalMs now always takes max(trace.duration_ms, observed-tail), so the axis stretches to fit the latest descendant end regardless of parse_status. - Render a faint dashed wrapping outline behind a parent span when its descendants extend past its own finished_at, so the postprocess stage row visibly spans the full window without overloading the 9ms self-time bar. - Tree expand/collapse caret bumped from 10 to 14px in a 16x16 hit area; copy icons in detail panel bumped from 11/14 to 14/18px; .kp-kv-copy button grown from 18 to 22px. - Short input/output payloads (<= 8 entries / <= 600 bytes JSON) auto-expand inline so users see the actual data without an extra click; longer payloads keep the click-to-expand summary. Span payloads (subspans only - root keeps the canonical identity, no duplicate knowledge_id/kb_id/tenant_id on every child): - extract.go: graph subspan output gains chunk_chars, chunk_preview, sample_nodes, sample_relations. - summary subspan output gains model_id, summary_preview. - question subspan output gains model_id and a sample_question captured from the first non-empty LLM response. i18n: new key knowledgeStages.detail.includingChildren for the wrapping-bar tooltip. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 14:35:16 +00:00
// Sample question + model id surfaced on the span output so the
// trace viewer can answer "what did the LLM actually produce?" and
// "which model did it run on?" without joining back to the chunk
// store. Captured the first time we see a non-empty question batch.
var sampleQuestion string
var resolvedModelID string
// Postprocess subspan for the trace viewer. Opened lazily after we
// unmarshal the payload (so we have payload.Attempt) and closed in
// the defer below alongside the stats log so the span output mirrors
// what we already log to stdout.
var qSpan *Span
var qErr error
// Set when a newer attempt supersedes this run; suppresses the
// FinalizeSubtask decrement so a stale task can't drain the new
// attempt's counter.
superseded := false
// Decrement enrichment counter on terminal exit. Keyed on the value
// RETURNED to asynq (retErr), not qErr: some branches record a span
// failure (qErr != nil) yet `return nil` so asynq won't retry (KB /
// knowledge fetch failures); those are terminal and must drain.
// Keying on qErr would skip them and strand the row in "finalizing".
// When we return an error asynq retries, so we only drain on the
// final attempt. Runs AFTER the stats-log defer below — defers
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// unwind LIFO, so this one declared first executes last.
defer func() {
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
finalizeSubtaskDetached(ctx, s.repo, payload.KnowledgeID, "question_legacy",
retErr, superseded, isFinalAsynqAttempt(ctx))
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
}()
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
defer func() {
logger.Infof(
ctx,
"Question generation stats: knowledge=%s kb=%s retry=%d/%d status=%s elapsed=%s chunks(total=%d,text=%d,empty_text=%d) llm(attempt=%d,success=%d,empty=%d,failed=%d) generated_questions=%d chunk_update_failed=%d metadata_set_failed=%d index(prepared=%d,attempted=%v,succeeded=%v)",
payload.KnowledgeID,
payload.KnowledgeBaseID,
retryCount,
maxRetry,
exitStatus,
time.Since(taskStartedAt).Round(time.Millisecond),
totalChunks,
totalTextChunks,
emptyContentChunks,
llmCallAttempts,
llmCallSuccess,
llmCallEmpty,
llmCallFailed,
generatedQuestionsTotal,
chunkUpdateFailed,
chunkMetadataSetFailed,
indexEntriesPrepared,
indexBatchAttempted,
indexBatchSucceeded,
)
if qSpan != nil {
out := types.JSONMap{
"status": exitStatus,
"total_chunks": totalChunks,
"text_chunks": totalTextChunks,
"empty_content_chunks": emptyContentChunks,
"llm_attempts": llmCallAttempts,
"llm_success": llmCallSuccess,
"llm_empty": llmCallEmpty,
"llm_failed": llmCallFailed,
"questions_generated": generatedQuestionsTotal,
"chunk_update_failed": chunkUpdateFailed,
"metadata_set_failed": chunkMetadataSetFailed,
"index_entries_prepared": indexEntriesPrepared,
"index_batch_attempted": indexBatchAttempted,
"index_batch_succeeded": indexBatchSucceeded,
"retry": retryCount,
"max_retry": maxRetry,
}
feat(timeline): scale axis to async tail, enrich span payloads, polish UI The post-process stage closes in ~9ms (just enqueue work) but its async subspans (postprocess.summary, postprocess.question, postprocess.graph) keep producing rows for tens of seconds AFTER the root finalizes. The old timeline used trace.duration_ms as the time axis maximum, which clipped those subspan bars past the right edge. Timeline: - totalMs now always takes max(trace.duration_ms, observed-tail), so the axis stretches to fit the latest descendant end regardless of parse_status. - Render a faint dashed wrapping outline behind a parent span when its descendants extend past its own finished_at, so the postprocess stage row visibly spans the full window without overloading the 9ms self-time bar. - Tree expand/collapse caret bumped from 10 to 14px in a 16x16 hit area; copy icons in detail panel bumped from 11/14 to 14/18px; .kp-kv-copy button grown from 18 to 22px. - Short input/output payloads (<= 8 entries / <= 600 bytes JSON) auto-expand inline so users see the actual data without an extra click; longer payloads keep the click-to-expand summary. Span payloads (subspans only - root keeps the canonical identity, no duplicate knowledge_id/kb_id/tenant_id on every child): - extract.go: graph subspan output gains chunk_chars, chunk_preview, sample_nodes, sample_relations. - summary subspan output gains model_id, summary_preview. - question subspan output gains model_id and a sample_question captured from the first non-empty LLM response. i18n: new key knowledgeStages.detail.includingChildren for the wrapping-bar tooltip. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 14:35:16 +00:00
// Surface the resolved model id and a sample question on the
// span output. These help debugging "why is question generation
// slow" — both questions ("which model was hit?") and ("what
// did it produce?") are hard to answer from logs alone.
if resolvedModelID != "" {
out["model_id"] = resolvedModelID
}
if sampleQuestion != "" {
out["sample_question"] = sampleQuestion
}
// Treat any non-success exitStatus as a failed run; the
// existing stats-string already enumerates them. qErr stays
// optional for callers that want to surface a Go error.
if exitStatus != "success" || qErr != nil {
msg := exitStatus
var detailErr error = qErr
if qErr != nil {
msg = qErr.Error()
}
s.failPostprocessSubspan(ctx, qSpan, "QUESTION_FAILED", msg, detailErr)
} else {
s.endPostprocessSubspan(ctx, qSpan, out)
}
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}()
logger.Infof(ctx, "Processing question generation for knowledge: %s", payload.KnowledgeID)
// A newer attempt has superseded this one: skip before opening the span
// so we don't read stale chunks. superseded suppresses the counter
// decrement in the defer above; qSpan stays nil so the stats defer no-ops.
if attemptSuperseded(ctx, s.tracker(), payload.KnowledgeID, payload.Attempt) {
superseded = true
exitStatus = "superseded"
logger.Infof(ctx, "question: attempt %d superseded for %s, skipping stale enrichment",
payload.Attempt, payload.KnowledgeID)
return nil
}
// Open the postprocess.question subspan now that we have payload.Attempt.
// Closes via the defer above.
qSpan = s.beginPostprocessSubspan(ctx, payload.KnowledgeID, payload.Attempt, "postprocess.question",
types.JSONMap{
"question_count": payload.QuestionCount,
"language": payload.Language,
})
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Set tenant context
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
if payload.Language != "" {
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
}
if strings.TrimSpace(s.config.Conversation.GenerateQuestionsPrompt) == "" {
exitStatus = "prompt_not_configured"
logger.Errorf(ctx, "GenerateQuestionsPrompt is empty: configure conversation.generate_questions_prompt_id")
qErr = fmt.Errorf("generate questions prompt not configured")
return qErr
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// Get knowledge base
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, payload.KnowledgeBaseID)
if err != nil {
exitStatus = "kb_not_found"
logger.Errorf(ctx, "Failed to get knowledge base: %v", err)
qErr = err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return nil
}
// Get knowledge
knowledge, err := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID)
if err != nil {
exitStatus = "knowledge_not_found"
logger.Errorf(ctx, "Failed to get knowledge: %v", err)
qErr = err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return nil
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// Short-circuit when the user cancelled parsing or the row is being deleted.
if knowledge != nil {
switch knowledge.ParseStatus {
case types.ParseStatusCancelled, types.ParseStatusDeleting:
exitStatus = "knowledge_" + knowledge.ParseStatus
logger.Infof(ctx, "Question generation: knowledge aborted (%s), skipping: %s",
knowledge.ParseStatus, payload.KnowledgeID)
return nil
}
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Get text chunks for this knowledge
chunks, err := s.chunkService.ListChunksByKnowledgeID(ctx, payload.KnowledgeID)
if err != nil {
exitStatus = "list_chunks_failed"
logger.Errorf(ctx, "Failed to get chunks: %v", err)
return nil
}
totalChunks = len(chunks)
// Filter text chunks only
textChunks := make([]*types.Chunk, 0)
for _, chunk := range chunks {
if chunk.ChunkType == types.ChunkTypeText {
textChunks = append(textChunks, chunk)
}
}
totalTextChunks = len(textChunks)
if len(textChunks) == 0 {
exitStatus = "no_text_chunks"
logger.Infof(ctx, "No text chunks found for knowledge: %s", payload.KnowledgeID)
return nil
}
// Sort chunks by StartAt for context building
sort.Slice(textChunks, func(i, j int) bool {
return textChunks[i].StartAt < textChunks[j].StartAt
})
// Initialize chat model
chatModel, err := s.modelService.GetChatModel(ctx, kb.SummaryModelID)
if err != nil {
exitStatus = "get_chat_model_failed"
logger.Errorf(ctx, "Failed to get chat model: %v", err)
return fmt.Errorf("failed to get chat model: %w", err)
}
feat(timeline): scale axis to async tail, enrich span payloads, polish UI The post-process stage closes in ~9ms (just enqueue work) but its async subspans (postprocess.summary, postprocess.question, postprocess.graph) keep producing rows for tens of seconds AFTER the root finalizes. The old timeline used trace.duration_ms as the time axis maximum, which clipped those subspan bars past the right edge. Timeline: - totalMs now always takes max(trace.duration_ms, observed-tail), so the axis stretches to fit the latest descendant end regardless of parse_status. - Render a faint dashed wrapping outline behind a parent span when its descendants extend past its own finished_at, so the postprocess stage row visibly spans the full window without overloading the 9ms self-time bar. - Tree expand/collapse caret bumped from 10 to 14px in a 16x16 hit area; copy icons in detail panel bumped from 11/14 to 14/18px; .kp-kv-copy button grown from 18 to 22px. - Short input/output payloads (<= 8 entries / <= 600 bytes JSON) auto-expand inline so users see the actual data without an extra click; longer payloads keep the click-to-expand summary. Span payloads (subspans only - root keeps the canonical identity, no duplicate knowledge_id/kb_id/tenant_id on every child): - extract.go: graph subspan output gains chunk_chars, chunk_preview, sample_nodes, sample_relations. - summary subspan output gains model_id, summary_preview. - question subspan output gains model_id and a sample_question captured from the first non-empty LLM response. i18n: new key knowledgeStages.detail.includingChildren for the wrapping-bar tooltip. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 14:35:16 +00:00
resolvedModelID = kb.SummaryModelID
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Initialize embedding model and retrieval engine
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
if err != nil {
exitStatus = "get_embedding_model_failed"
logger.Errorf(ctx, "Failed to get embedding model: %v", err)
return fmt.Errorf("failed to get embedding model: %w", err)
}
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
if err != nil {
exitStatus = "get_tenant_failed"
logger.Errorf(ctx, "Failed to get tenant info: %v", err)
return fmt.Errorf("failed to get tenant info: %w", err)
}
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenantInfo)
refactor(retriever): introduce factory for KB-scoped retrieve engine resolution Extracts the 25 repeated NewCompositeRetrieveEngine call sites across seven services into two factory functions with tenant-ownership verification: CreateRetrieveEngineForKB (synchronous) and CreateRetrieveEngineFromPayload (async task handlers). Promotes GetByStoreID from concrete-only to interfaces.RetrieveEngineRegistry. Extends KBDeletePayload / IndexDeletePayload with an omitempty VectorStoreID snapshot. Design highlights - Factory verifies tenant ownership of the resolved store (defense-in-depth) so a gap in PR3 validation or a tampered Asynq payload cannot cross tenants. Cross-tenant attempts return ErrVectorStoreForbidden with a structured log entry. - Sentinel errors (ErrTenantInfoMissing, ErrVectorStoreNotFound, ErrVectorStoreForbidden) let async handlers classify non-retryable failures as asynq.SkipRetry. - nil and empty-string pointers for vectorStoreID normalize to "unbound" so callers never send an empty UUID to GetByStoreID. - resolveBoundEngine constructs engineInfos directly (with slices.Clone of Support()) instead of going through NewCompositeRetrieveEngine. The latter only reads from the byEngineType map and cannot reach DB stores in byStoreID -- multiple stores can share the same engine type. Unbound fallbacks still reuse NewCompositeRetrieveEngine so the tenant effective-engines path is byte-for-byte unchanged. - DeleteKnowledgeBase now reads the KB before soft-delete so the enqueued KBDeletePayload carries a VectorStoreID snapshot; once the row is soft-deleted GORM's default scope hides it. Cost: +1 SELECT per KB-delete request (a rare admin operation). - enqueueIndexDeleteTask gains a vectorStoreID *string parameter that the single caller (tag.go) populates from the owning KB. The worker (ProcessIndexDelete) validates ownership via the factory. - cleanupKnowledgeResources loads the KB so bound-store cleanup routes correctly. If the load fails it warns and falls back to tenant effective engines; orphan vectors become observable in logs instead of disappearing silently. - DeleteKnowledges (batch) stays on the tenant effective-engines path -- batches can span stores and multi-store fan-out is PR4 scope. Noted inline. Merge safety All knowledge bases have VectorStoreID = NULL at merge time (introduced nullable in PR1, Tencent/WeKnora#994). Every factory call falls back to NewCompositeRetrieveEngine(registry, tenantInfo.GetEffectiveEngines()), which is the existing code path for these KBs. Async payloads from before this change decode to VectorStoreID = nil (omitempty) and take the same fallback. Testing - go build ./... - go vet ./... - go test -race -count=1 ./internal/application/service/retriever/... covers unbound (nil/empty), bound, cross-tenant, unregistered store, ownership infra error, legacy payload shapes (missing field/null/ empty string/nil), tampered payload, and parallel invocation. - grep -r NewCompositeRetrieveEngine internal/application/service returns zero results outside factory.go/composite.go. Refs: Part of Tencent/WeKnora#993. Depends on Tencent/WeKnora#994.
2026-05-13 08:24:17 +00:00
retrieveEngine, err := retriever.CreateRetrieveEngineForKB(
ctx, s.retrieveEngine, s.ownership, tenantInfo.ID, kb.VectorStoreID)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
exitStatus = "init_retrieve_engine_failed"
logger.Errorf(ctx, "Failed to init retrieve engine: %v", err)
return fmt.Errorf("failed to init retrieve engine: %w", err)
}
questionCount := payload.QuestionCount
if questionCount <= 0 {
questionCount = 3
}
if questionCount > 10 {
questionCount = 10
}
processOverrides, _ := knowledge.ProcessOverrides()
questionGenCfg := ResolveProcessConfig(kb, processOverrides).QuestionGenerationConfig
customInstructions := questionGenCfg.CustomInstructions
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Collect image info for all text chunks so question generation can
// see caption / OCR text instead of bare image links.
textChunkIDs := make([]string, len(textChunks))
for i, c := range textChunks {
textChunkIDs[i] = c.ID
}
imageInfoMap := searchutil.CollectImageInfoByChunkIDs(ctx, s.chunkRepo, payload.TenantID, textChunkIDs)
enrichContent := func(chunk *types.Chunk) string {
if info, ok := imageInfoMap[chunk.ID]; ok && info != "" {
return searchutil.EnrichContentWithImageInfo(chunk.Content, info)
}
return chunk.Content
}
// Generate questions for each chunk with context
var indexInfoList []*types.IndexInfo
for i, chunk := range textChunks {
if strings.TrimSpace(chunk.Content) == "" {
emptyContentChunks++
continue
}
// Build context from adjacent chunks
var prevContent, nextContent string
if i > 0 {
prevContent = enrichContent(textChunks[i-1])
}
if i < len(textChunks)-1 {
nextContent = enrichContent(textChunks[i+1])
}
generationRevision := chunk.ContentRevision
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
llmCallAttempts++
questions, err := s.generateQuestionsWithContext(ctx, chatModel, enrichContent(chunk), prevContent, nextContent,
knowledge.Title, questionCount, customInstructions)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
llmCallFailed++
logger.Warnf(ctx, "Failed to generate questions for chunk %s: %v", chunk.ID, err)
continue
}
if len(questions) == 0 {
llmCallEmpty++
continue
}
latestChunk, latestErr := s.chunkRepo.GetChunkByID(ctx, payload.TenantID, chunk.ID)
if latestErr != nil || latestChunk.ContentRevision != generationRevision {
logger.Infof(ctx, "Skipping stale generated questions for chunk %s (revision changed)", chunk.ID)
continue
}
chunk = latestChunk
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
llmCallSuccess++
generatedQuestionsTotal += len(questions)
feat(timeline): scale axis to async tail, enrich span payloads, polish UI The post-process stage closes in ~9ms (just enqueue work) but its async subspans (postprocess.summary, postprocess.question, postprocess.graph) keep producing rows for tens of seconds AFTER the root finalizes. The old timeline used trace.duration_ms as the time axis maximum, which clipped those subspan bars past the right edge. Timeline: - totalMs now always takes max(trace.duration_ms, observed-tail), so the axis stretches to fit the latest descendant end regardless of parse_status. - Render a faint dashed wrapping outline behind a parent span when its descendants extend past its own finished_at, so the postprocess stage row visibly spans the full window without overloading the 9ms self-time bar. - Tree expand/collapse caret bumped from 10 to 14px in a 16x16 hit area; copy icons in detail panel bumped from 11/14 to 14/18px; .kp-kv-copy button grown from 18 to 22px. - Short input/output payloads (<= 8 entries / <= 600 bytes JSON) auto-expand inline so users see the actual data without an extra click; longer payloads keep the click-to-expand summary. Span payloads (subspans only - root keeps the canonical identity, no duplicate knowledge_id/kb_id/tenant_id on every child): - extract.go: graph subspan output gains chunk_chars, chunk_preview, sample_nodes, sample_relations. - summary subspan output gains model_id, summary_preview. - question subspan output gains model_id and a sample_question captured from the first non-empty LLM response. i18n: new key knowledgeStages.detail.includingChildren for the wrapping-bar tooltip. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 14:35:16 +00:00
if sampleQuestion == "" && len(questions) > 0 {
sampleQuestion = previewText(questions[0], 200)
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Update chunk metadata with unique IDs for each question
generatedQuestions := make([]types.GeneratedQuestion, len(questions))
questionRevision := chunk.ContentRevision
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
for j, question := range questions {
questionID := fmt.Sprintf("q%d", time.Now().UnixNano()+int64(j))
generatedQuestions[j] = types.GeneratedQuestion{
ID: questionID,
Question: question,
ContentRevision: &questionRevision,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
}
meta := &types.DocumentChunkMetadata{
GeneratedQuestions: generatedQuestions, GeneratedQuestionsRevision: chunk.ContentRevision,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
if err := chunk.SetDocumentMetadata(meta); err != nil {
chunkMetadataSetFailed++
logger.Warnf(ctx, "Failed to set document metadata for chunk %s: %v", chunk.ID, err)
continue
}
// Update chunk in database
if err := s.chunkRepo.UpdateChunk(ctx, chunk); err != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
chunkUpdateFailed++
logger.Warnf(ctx, "Failed to update chunk %s: %v", chunk.ID, err)
continue
}
// Create index entries for generated questions
for _, gq := range generatedQuestions {
sourceID := types.GeneratedQuestionSourceID(chunk.ID, gq.ID)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
indexInfoList = append(indexInfoList, &types.IndexInfo{
Content: buildKnowledgeIndexContent(knowledge, gq.Question),
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
SourceID: sourceID,
SourceType: types.ChunkSourceType,
ChunkID: chunk.ID,
KnowledgeID: knowledge.ID,
KnowledgeBaseID: knowledge.KnowledgeBaseID,
IsEnabled: true,
})
}
logger.Debugf(ctx, "Generated %d questions for chunk %s", len(questions), chunk.ID)
}
indexEntriesPrepared = len(indexInfoList)
// Index generated questions
if len(indexInfoList) > 0 {
indexBatchAttempted = true
if err := retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfoList); err != nil {
exitStatus = "index_questions_failed"
logger.Errorf(ctx, "Failed to index generated questions: %v", err)
return fmt.Errorf("failed to index questions: %w", err)
}
indexBatchSucceeded = true
logger.Infof(ctx, "Successfully indexed %d generated questions for knowledge: %s", len(indexInfoList), payload.KnowledgeID)
}
return nil
}
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
// processQuestionGenerationForChunks generates questions for a batch (window)
// of text chunks. This is the batched fan-out path (one asynq task per
// questionGenChunkBatchSize chunks), aligned with the graph-extract
// TypeChunkExtract pattern: independent retry, per-batch cancellation, and a
// postprocess.question.batch[i] subspan. The payload carries only chunk ids
// (never content); content is read fresh here, and all questions for the batch
// are indexed in a single embedding BatchIndex call.
func (s *knowledgeService) processQuestionGenerationForChunks(ctx context.Context, t *asynq.Task, payload types.QuestionGenerationPayload) (retErr error) {
taskStartedAt := time.Now()
retryCount, _ := asynq.GetRetryCount(ctx)
maxRetry, _ := asynq.GetMaxRetry(ctx)
// Normalize the batch: prefer ChunkIDs, fall back to a lone ChunkID
// (interim per-chunk build) so those in-flight tasks still run.
batchIDs := payload.ChunkIDs
if len(batchIDs) == 0 && payload.ChunkID != "" {
batchIDs = []string{payload.ChunkID}
}
exitStatus := "success"
chunksInBatch := len(batchIDs)
chunksProcessed := 0
emptyChunks := 0
llmCallFailed := 0
generatedQuestionsTotal := 0
indexEntriesPrepared := 0
indexBatchSucceeded := false
var sampleQuestion string
var resolvedModelID string
var qSpan *Span
var qErr error
// Suppresses the FinalizeSubtask drain when a newer attempt superseded
// this run, so a stale task can't decrement the new attempt's counter.
superseded := false
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
if payload.Language != "" {
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
}
// Drain the parent's enrichment counter on terminal exit. Keyed on the
// value RETURNED to asynq (retErr), not qErr: some branches record a
// span failure yet `return nil` (terminal, must drain). Declared first
// so it runs LAST (after the stats/span defer below).
defer func() {
finalizeSubtaskDetached(ctx, s.repo, payload.KnowledgeID,
fmt.Sprintf("question_batch[%d]", payload.BatchIndex),
retErr, superseded, isFinalAsynqAttempt(ctx))
}()
defer func() {
logger.Infof(ctx,
"Question generation (batch) stats: knowledge=%s batch=%d chunks(in_batch=%d,processed=%d,empty=%d) llm_failed=%d retry=%d/%d status=%s elapsed=%s generated_questions=%d index(entries=%d,succeeded=%v)",
payload.KnowledgeID, payload.BatchIndex, chunksInBatch, chunksProcessed, emptyChunks, llmCallFailed,
retryCount, maxRetry, exitStatus, time.Since(taskStartedAt).Round(time.Millisecond),
generatedQuestionsTotal, indexEntriesPrepared, indexBatchSucceeded,
)
if qSpan != nil {
out := types.JSONMap{
"status": exitStatus,
"batch_index": payload.BatchIndex,
"chunks_in_batch": chunksInBatch,
"chunks_processed": chunksProcessed,
"empty_chunks": emptyChunks,
"llm_failed": llmCallFailed,
"questions_generated": generatedQuestionsTotal,
"index_entries_prepared": indexEntriesPrepared,
"index_batch_succeeded": indexBatchSucceeded,
"retry": retryCount,
"max_retry": maxRetry,
}
if resolvedModelID != "" {
out["model_id"] = resolvedModelID
}
if sampleQuestion != "" {
out["sample_question"] = sampleQuestion
}
if exitStatus != "success" || qErr != nil {
msg := exitStatus
if qErr != nil {
msg = qErr.Error()
}
s.failPostprocessSubspan(ctx, qSpan, "QUESTION_FAILED", msg, qErr)
} else {
s.endPostprocessSubspan(ctx, qSpan, out)
}
}
}()
logger.Infof(ctx, "Processing question generation for knowledge=%s batch=%d chunks=%d",
payload.KnowledgeID, payload.BatchIndex, chunksInBatch)
if chunksInBatch == 0 {
exitStatus = "empty_batch"
return nil
}
// A newer attempt has superseded this one: skip before opening the span
// so we don't read stale chunks and don't drain the new attempt.
if attemptSuperseded(ctx, s.tracker(), payload.KnowledgeID, payload.Attempt) {
superseded = true
exitStatus = "superseded"
logger.Infof(ctx, "question: attempt %d superseded for %s, skipping stale enrichment",
payload.Attempt, payload.KnowledgeID)
return nil
}
qSpan = s.beginQuestionBatchSubspan(ctx, payload.KnowledgeID, payload.Attempt,
fmt.Sprintf("postprocess.question.batch[%d]", payload.BatchIndex),
types.JSONMap{
"batch_index": payload.BatchIndex,
"chunks": chunksInBatch,
"question_count": payload.QuestionCount,
"language": payload.Language,
})
if strings.TrimSpace(s.config.Conversation.GenerateQuestionsPrompt) == "" {
exitStatus = "prompt_not_configured"
logger.Errorf(ctx, "GenerateQuestionsPrompt is empty: configure conversation.generate_questions_prompt_id")
qErr = fmt.Errorf("generate questions prompt not configured")
return qErr
}
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, payload.KnowledgeBaseID)
if err != nil {
exitStatus = "kb_not_found"
logger.Errorf(ctx, "Failed to get knowledge base: %v", err)
qErr = err
return nil
}
knowledge, err := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID)
if err != nil {
exitStatus = "knowledge_not_found"
logger.Errorf(ctx, "Failed to get knowledge: %v", err)
qErr = err
return nil
}
// Short-circuit when the user cancelled parsing or the row is being
// deleted — batched fan-out means we get this check for free on every
// batch, so a cancel stops burning LLM quota on the remaining batches.
if knowledge != nil {
switch knowledge.ParseStatus {
case types.ParseStatusCancelled, types.ParseStatusDeleting:
exitStatus = "knowledge_" + knowledge.ParseStatus
logger.Infof(ctx, "Question generation: knowledge aborted (%s), skipping batch %d",
knowledge.ParseStatus, payload.BatchIndex)
return nil
}
}
chatModel, err := s.modelService.GetChatModel(ctx, kb.SummaryModelID)
if err != nil {
exitStatus = "get_chat_model_failed"
logger.Errorf(ctx, "Failed to get chat model: %v", err)
return fmt.Errorf("failed to get chat model: %w", err)
}
resolvedModelID = kb.SummaryModelID
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, kb.EmbeddingModelID)
if err != nil {
exitStatus = "get_embedding_model_failed"
logger.Errorf(ctx, "Failed to get embedding model: %v", err)
return fmt.Errorf("failed to get embedding model: %w", err)
}
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
if err != nil {
exitStatus = "get_tenant_failed"
logger.Errorf(ctx, "Failed to get tenant info: %v", err)
return fmt.Errorf("failed to get tenant info: %w", err)
}
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenantInfo)
retrieveEngine, err := retriever.CreateRetrieveEngineForKB(
ctx, s.retrieveEngine, s.ownership, tenantInfo.ID, kb.VectorStoreID)
if err != nil {
exitStatus = "init_retrieve_engine_failed"
logger.Errorf(ctx, "Failed to init retrieve engine: %v", err)
return fmt.Errorf("failed to init retrieve engine: %w", err)
}
questionCount := payload.QuestionCount
if questionCount <= 0 {
questionCount = 3
}
if questionCount > 10 {
questionCount = 10
}
processOverrides, _ := knowledge.ProcessOverrides()
questionGenCfg := ResolveProcessConfig(kb, processOverrides).QuestionGenerationConfig
customInstructions := questionGenCfg.CustomInstructions
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
// Fetch the batch chunks (in payload order) plus the two boundary
// neighbors so we can rebuild the same surrounding context the legacy
// loop used, all enriched with image OCR / caption info. A vanished
// chunk degrades gracefully (skipped / empty context).
getChunk := func(id string) *types.Chunk {
if id == "" {
return nil
}
c, gerr := s.chunkRepo.GetChunkByID(ctx, payload.TenantID, id)
if gerr != nil {
return nil
}
return c
}
batchChunks := make([]*types.Chunk, len(batchIDs))
for i, id := range batchIDs {
batchChunks[i] = getChunk(id)
}
prevChunk := getChunk(payload.PrevChunkID)
nextChunk := getChunk(payload.NextChunkID)
infoIDs := make([]string, 0, len(batchIDs)+2)
infoIDs = append(infoIDs, batchIDs...)
if payload.PrevChunkID != "" {
infoIDs = append(infoIDs, payload.PrevChunkID)
}
if payload.NextChunkID != "" {
infoIDs = append(infoIDs, payload.NextChunkID)
}
imageInfoMap := searchutil.CollectImageInfoByChunkIDs(ctx, s.chunkRepo, payload.TenantID, infoIDs)
enrich := func(c *types.Chunk) string {
if c == nil {
return ""
}
if info, ok := imageInfoMap[c.ID]; ok && info != "" {
return searchutil.EnrichContentWithImageInfo(c.Content, info)
}
return c.Content
}
// neighborContent returns the context content for position i within the
// batch: the in-batch neighbor when present, else the boundary chunk.
prevContentAt := func(i int) string {
if i > 0 {
return enrich(batchChunks[i-1])
}
return enrich(prevChunk)
}
nextContentAt := func(i int) string {
if i < len(batchChunks)-1 {
return enrich(batchChunks[i+1])
}
return enrich(nextChunk)
}
var indexInfoList []*types.IndexInfo
for i, chunk := range batchChunks {
if chunk == nil || strings.TrimSpace(chunk.Content) == "" {
emptyChunks++
continue
}
generationRevision := chunk.ContentRevision
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
questions, gerr := s.generateQuestionsWithContext(
ctx, chatModel, enrich(chunk), prevContentAt(i), nextContentAt(i), knowledge.Title, questionCount,
customInstructions)
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
if gerr != nil {
llmCallFailed++
logger.Warnf(ctx, "Failed to generate questions for chunk %s: %v", chunk.ID, gerr)
continue
}
if len(questions) == 0 {
continue
}
latestChunk, latestErr := s.chunkRepo.GetChunkByID(ctx, payload.TenantID, chunk.ID)
if latestErr != nil || latestChunk.ContentRevision != generationRevision {
logger.Infof(ctx, "Skipping stale generated questions for chunk %s (revision changed)", chunk.ID)
continue
}
chunk = latestChunk
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
chunksProcessed++
generatedQuestionsTotal += len(questions)
if sampleQuestion == "" {
sampleQuestion = previewText(questions[0], 200)
}
generatedQuestions := make([]types.GeneratedQuestion, len(questions))
questionRevision := chunk.ContentRevision
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
for j, question := range questions {
generatedQuestions[j] = types.GeneratedQuestion{
ID: fmt.Sprintf("q%d", time.Now().UnixNano()+int64(j)),
Question: question,
ContentRevision: &questionRevision,
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
}
}
meta := &types.DocumentChunkMetadata{
GeneratedQuestions: generatedQuestions, GeneratedQuestionsRevision: chunk.ContentRevision,
}
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
if err := chunk.SetDocumentMetadata(meta); err != nil {
logger.Warnf(ctx, "Failed to set document metadata for chunk %s: %v", chunk.ID, err)
continue
}
if err := s.chunkRepo.UpdateChunk(ctx, chunk); err != nil {
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
logger.Warnf(ctx, "Failed to update chunk %s: %v", chunk.ID, err)
continue
}
for _, gq := range generatedQuestions {
indexInfoList = append(indexInfoList, &types.IndexInfo{
Content: buildKnowledgeIndexContent(knowledge, gq.Question),
SourceID: types.GeneratedQuestionSourceID(chunk.ID, gq.ID),
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
SourceType: types.ChunkSourceType,
ChunkID: chunk.ID,
KnowledgeID: knowledge.ID,
KnowledgeBaseID: knowledge.KnowledgeBaseID,
IsEnabled: true,
})
}
}
indexEntriesPrepared = len(indexInfoList)
if len(indexInfoList) > 0 {
if err := retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfoList); err != nil {
exitStatus = "index_questions_failed"
qErr = err
logger.Errorf(ctx, "Failed to index generated questions for batch %d: %v", payload.BatchIndex, err)
return fmt.Errorf("failed to index questions: %w", err)
}
indexBatchSucceeded = true
logger.Infof(ctx, "Indexed %d generated questions for knowledge=%s batch=%d",
len(indexInfoList), payload.KnowledgeID, payload.BatchIndex)
}
return nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// generateQuestionsWithContext generates questions for a chunk with surrounding context
func (s *knowledgeService) generateQuestionsWithContext(ctx context.Context,
chatModel chat.Chat, content, prevContent, nextContent, docName string, questionCount int,
customInstructions string,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
) ([]string, error) {
if content == "" || questionCount <= 0 {
return nil, nil
}
prompt := strings.TrimSpace(s.config.Conversation.GenerateQuestionsPrompt)
if prompt == "" {
return nil, fmt.Errorf("generate questions prompt not configured")
}
// Build context section
var contextSection string
if prevContent != "" || nextContent != "" {
contextSection = "<surrounding_context>\n"
if prevContent != "" {
contextSection += fmt.Sprintf("<preceding_content>\n%s\n\n</preceding_content>\n\n", prevContent)
}
if nextContent != "" {
contextSection += fmt.Sprintf("<following_content>\n%s\n\n</following_content>\n\n", nextContent)
}
contextSection += "</surrounding_context>\n\n"
}
langName := types.LanguageNameFromContext(ctx)
prompt = types.RenderPromptPlaceholders(prompt, types.PlaceholderValues{
"question_count": fmt.Sprintf("%d", questionCount),
"content": content,
"context": contextSection,
"doc_name": docName,
"language": langName,
})
prompt = types.AppendCustomPromptInstructions(prompt, customInstructions, "question_generation")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
thinking := false
modelCtx := types.WithLLMCallMetadata(ctx, "question_generation", "")
response, err := chatModel.Chat(modelCtx, []chat.Message{
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
{
Role: "user",
Content: prompt,
},
}, &chat.ChatOptions{
Temperature: 0.7,
MaxTokens: 512,
Thinking: &thinking,
})
if err != nil {
return nil, fmt.Errorf("failed to generate questions: %w", err)
}
// Parse response
lines := strings.Split(response.Content, "\n")
questions := make([]string, 0, questionCount)
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
line = strings.TrimLeft(line, "0123456789.-*) ")
line = strings.TrimSpace(line)
if line != "" && len(line) > 5 {
questions = append(questions, line)
if len(questions) >= questionCount {
break
}
}
}
return questions, nil
}
// RegenerateChunkQuestions synchronously refreshes Doc2Query-style auxiliary
// questions for the current chunk revision and atomically replaces their
// retrieval entries through updateChunkVector.
func (s *knowledgeService) RegenerateChunkQuestions(
ctx context.Context, chunkID string,
) ([]types.GeneratedQuestion, error) {
tenantID := types.MustTenantIDFromContext(ctx)
chunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, chunkID)
if err != nil {
return nil, err
}
if chunk.ChunkType != types.ChunkTypeText {
return nil, fmt.Errorf("questions can only be generated for text chunks")
}
generationRevision := chunk.ContentRevision
knowledge, kb, err := loadKnowledgeWrite(ctx, s.repo, s.kbService, chunk.KnowledgeID)
if err != nil {
return nil, err
}
if knowledge.KnowledgeBaseID != chunk.KnowledgeBaseID || chunk.TenantID != knowledge.TenantID {
return nil, werrors.NewForbiddenError("chunk does not belong to its knowledge document")
}
if kb.SummaryModelID == "" {
return nil, fmt.Errorf("summary model is required for question generation")
}
chatModel, err := s.modelService.GetChatModel(ctx, kb.SummaryModelID)
if err != nil {
return nil, err
}
resolveNeighbor := func(id string) string {
if id == "" {
return ""
}
neighbor, getErr := s.chunkRepo.GetChunkByID(ctx, tenantID, id)
if getErr != nil || !sameChunkDocument(chunk, neighbor) {
return ""
}
return neighbor.Content
}
overrides, _ := knowledge.ProcessOverrides()
config := ResolveProcessConfig(kb, overrides).QuestionGenerationConfig
count := config.QuestionCount
if count <= 0 {
count = 3
}
if count > 10 {
count = 10
}
questions, err := s.generateQuestionsWithContext(
ctx, chatModel, chunk.Content, resolveNeighbor(chunk.PreChunkID),
resolveNeighbor(chunk.NextChunkID), knowledge.Title, count, config.CustomInstructions,
)
if err != nil {
return nil, err
}
latestChunk, err := s.chunkRepo.GetChunkByID(ctx, tenantID, chunkID)
if err != nil {
return nil, err
}
if latestChunk.ContentRevision != generationRevision {
return nil, ErrChunkRevisionConflict
}
chunk = latestChunk
generated := make([]types.GeneratedQuestion, 0, len(questions))
questionRevision := chunk.ContentRevision
for _, question := range questions {
generated = append(generated, types.GeneratedQuestion{
ID: uuid.NewString(), Question: question, ContentRevision: &questionRevision,
})
}
meta := &types.DocumentChunkMetadata{
GeneratedQuestions: generated, GeneratedQuestionsRevision: chunk.ContentRevision,
}
if err := chunk.SetDocumentMetadata(meta); err != nil {
return nil, err
}
if err := s.chunkRepo.UpdateChunk(ctx, chunk); err != nil {
return nil, err
}
if err := s.updateChunkVector(ctx, chunk.KnowledgeBaseID, []*types.Chunk{chunk}); err != nil {
return nil, err
}
return generated, nil
}
// RegenerateKnowledgeSummary refreshes both the knowledge description and the
// summary chunk(s), then reindexes only those summary chunks. It is
// intentionally idempotent.
func (s *knowledgeService) RegenerateKnowledgeSummary(
ctx context.Context, knowledgeID string,
) (*types.Knowledge, error) {
tenantID := types.MustTenantIDFromContext(ctx)
knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
if err != nil {
return nil, err
}
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, knowledge.KnowledgeBaseID)
if err != nil {
return nil, err
}
if kb.SummaryModelID == "" {
return nil, fmt.Errorf("summary model is not configured")
}
allChunks, err := s.chunkRepo.ListChunksByKnowledgeID(ctx, tenantID, knowledgeID)
if err != nil {
return nil, err
}
textChunks := make([]*types.Chunk, 0)
for _, chunk := range allChunks {
if chunk.ChunkType == types.ChunkTypeText && chunk.IsEnabled {
textChunks = append(textChunks, chunk)
}
}
if len(textChunks) == 0 {
knowledge.Description = ""
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
knowledge.Profile = nil
knowledge.SummaryStatus = types.SummaryStatusFailed
knowledge.UpdatedAt = time.Now()
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
return knowledge, updateErr
}
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
_ = requestKnowledgeBaseProfileRefresh(ctx, s.task, kb, false)
return knowledge, errInsufficientSummaryContent
}
sort.Slice(textChunks, func(i, j int) bool {
return textChunks[i].ChunkIndex < textChunks[j].ChunkIndex
})
metadataVersion := string(knowledge.CustomMetadata)
knowledge.SummaryStatus = types.SummaryStatusProcessing
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if err := s.saveSummaryState(ctx, knowledge); err != nil {
return nil, err
}
handleGenerationFailure := func(generationErr error) (*types.Knowledge, error) {
if errors.Is(generationErr, errInsufficientSummaryContent) {
knowledge.Description = ""
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
knowledge.Profile = nil
knowledge.SummaryStatus = types.SummaryStatusFailed
knowledge.UpdatedAt = time.Now()
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
return knowledge, updateErr
}
return knowledge, generationErr
}
if summaryTaskWillRetry(ctx) {
applyRetryableSummaryFailureState(knowledge, textChunks, true)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
logger.Warnf(ctx, "Failed to mark summary refresh pending for retry: %v", updateErr)
}
return knowledge, generationErr
}
stale, staleErr := summarySourceChanged(
ctx, s.repo, s.chunkRepo, tenantID, knowledgeID, metadataVersion, textChunks,
)
if staleErr != nil {
knowledge.SummaryStatus = types.SummaryStatusFailed
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
_ = s.saveSummaryState(ctx, knowledge)
return knowledge, fmt.Errorf("verify summary fallback freshness: %w", staleErr)
}
if stale {
return knowledge, ErrSummaryRefreshStale
}
applyRetryableSummaryFailureState(knowledge, textChunks, false)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if updateErr := s.saveSummaryState(ctx, knowledge); updateErr != nil {
return knowledge, updateErr
}
return knowledge, generationErr
}
chatModel, err := s.modelService.GetChatModel(ctx, kb.SummaryModelID)
if err != nil {
return handleGenerationFailure(fmt.Errorf("get chat model: %w", err))
}
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
summaryResult, err := s.getSummary(ctx, chatModel, knowledge, textChunks)
if err != nil {
return handleGenerationFailure(err)
}
stale, err := summarySourceChanged(
ctx, s.repo, s.chunkRepo, tenantID, knowledgeID, metadataVersion, textChunks,
)
if err != nil {
return nil, fmt.Errorf("verify summary freshness: %w", err)
}
if stale {
logger.Infof(ctx, "Discarding stale summary refresh for knowledge %s", knowledgeID)
return nil, ErrSummaryRefreshStale
}
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
summary := summaryResult.Summary
knowledge.Description = summary
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
knowledge.Profile = summaryResult.Profile
knowledge.SummaryStatus = types.SummaryStatusCompleted
knowledge.UpdatedAt = time.Now()
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if err := s.saveSummaryState(ctx, knowledge); err != nil {
return nil, err
}
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
summaryChunkContent := buildSummaryChunkContent(summary, summaryResult.Profile)
defer func() { _ = requestKnowledgeBaseProfileRefresh(ctx, s.task, kb, false) }()
if kb.NeedsEmbeddingModel() {
maxIndex := 0
for _, chunk := range allChunks {
if chunk.ChunkIndex > maxIndex {
maxIndex = chunk.ChunkIndex
}
fix(retrieval): 分段中删除的图片不再被检索到 从分段里删掉一张图片后,这张图仍会回到检索结果和模型上下文里。 三个问题串在一起: 1. 删图时 syncEditedChunkImages 会把 image_ocr / image_caption 子块置为 禁用,但 CollectImageInfoByChunkIDs 查子块时不看 is_enabled,又把它们的 image_info 挂回了父块。knowledge_search 工具随后把每条 image_info 无条件 渲染成 markdown 图片写进 LLM 上下文,图片就这样回来了。这里按 is_enabled 过滤,两级遍历都跳过禁用子块。过滤放在 collector 而不是工具输出层:纯图片 分块的正文本身就是 OCR 文本、没有 markdown 图片语法,按正文过滤会误杀。 chat_pipeline 里既有的 fake 仓储 fixture 同步补上 IsEnabled: true:它们不 走 DB 默认值,零值 false 会被新的过滤当成已禁用子块。 2. UpdateImageInfo 补建 image_ocr / image_caption 子块时没有设置 IsEnabled。 CreateChunks 用 Select("*") 插入,gorm 的 default:true 不生效,零值 false 直接落库,这些子块一出生就是禁用的。补上 IsEnabled: true —— 否则第 1 点 的过滤会把它们永久丢弃。其余 CreateChunks 调用方均已显式设置该字段。 3. 摘要刷新每次都新建一条 summary 分块,旧的留着且仍然启用。原因是它复用了 ListChunksByKnowledgeID 的结果,而那个查询硬编码 chunk_type = 'text', "查找已有 summary 分块"的分支永远匹配不上。残留的旧摘要描述的是编辑前的 文档,会让用户已经删掉的内容继续被检索到。新增按 chunk_type 过滤的仓储 方法,刷新时原地更新已有 summary 分块。
2026-08-17 10:53:22 +00:00
}
// allChunks holds text chunks only, so it can never carry the existing
// summary chunk. Scanning it for one always came up empty, which left
// every refresh appending a new summary chunk beside the stale one --
// and a stale summary stays enabled and indexed, so content the user
// edited out of the document kept being retrievable through it.
existingSummaries, err := s.chunkRepo.ListChunksByKnowledgeIDAndTypes(
ctx, tenantID, knowledgeID, []types.ChunkType{types.ChunkTypeSummary},
)
if err != nil {
return nil, err
}
summaryChunks := make([]*types.Chunk, 0, len(existingSummaries))
for _, chunk := range existingSummaries {
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
chunk.Content = summaryChunkContent
fix(retrieval): 分段中删除的图片不再被检索到 从分段里删掉一张图片后,这张图仍会回到检索结果和模型上下文里。 三个问题串在一起: 1. 删图时 syncEditedChunkImages 会把 image_ocr / image_caption 子块置为 禁用,但 CollectImageInfoByChunkIDs 查子块时不看 is_enabled,又把它们的 image_info 挂回了父块。knowledge_search 工具随后把每条 image_info 无条件 渲染成 markdown 图片写进 LLM 上下文,图片就这样回来了。这里按 is_enabled 过滤,两级遍历都跳过禁用子块。过滤放在 collector 而不是工具输出层:纯图片 分块的正文本身就是 OCR 文本、没有 markdown 图片语法,按正文过滤会误杀。 chat_pipeline 里既有的 fake 仓储 fixture 同步补上 IsEnabled: true:它们不 走 DB 默认值,零值 false 会被新的过滤当成已禁用子块。 2. UpdateImageInfo 补建 image_ocr / image_caption 子块时没有设置 IsEnabled。 CreateChunks 用 Select("*") 插入,gorm 的 default:true 不生效,零值 false 直接落库,这些子块一出生就是禁用的。补上 IsEnabled: true —— 否则第 1 点 的过滤会把它们永久丢弃。其余 CreateChunks 调用方均已显式设置该字段。 3. 摘要刷新每次都新建一条 summary 分块,旧的留着且仍然启用。原因是它复用了 ListChunksByKnowledgeID 的结果,而那个查询硬编码 chunk_type = 'text', "查找已有 summary 分块"的分支永远匹配不上。残留的旧摘要描述的是编辑前的 文档,会让用户已经删掉的内容继续被检索到。新增按 chunk_type 过滤的仓储 方法,刷新时原地更新已有 summary 分块。
2026-08-17 10:53:22 +00:00
chunk.SourceContent = chunk.Content
chunk.IsEnabled = true
chunk.UpdatedAt = time.Now()
if err := s.chunkRepo.UpdateChunk(ctx, chunk); err != nil {
return nil, err
}
fix(retrieval): 分段中删除的图片不再被检索到 从分段里删掉一张图片后,这张图仍会回到检索结果和模型上下文里。 三个问题串在一起: 1. 删图时 syncEditedChunkImages 会把 image_ocr / image_caption 子块置为 禁用,但 CollectImageInfoByChunkIDs 查子块时不看 is_enabled,又把它们的 image_info 挂回了父块。knowledge_search 工具随后把每条 image_info 无条件 渲染成 markdown 图片写进 LLM 上下文,图片就这样回来了。这里按 is_enabled 过滤,两级遍历都跳过禁用子块。过滤放在 collector 而不是工具输出层:纯图片 分块的正文本身就是 OCR 文本、没有 markdown 图片语法,按正文过滤会误杀。 chat_pipeline 里既有的 fake 仓储 fixture 同步补上 IsEnabled: true:它们不 走 DB 默认值,零值 false 会被新的过滤当成已禁用子块。 2. UpdateImageInfo 补建 image_ocr / image_caption 子块时没有设置 IsEnabled。 CreateChunks 用 Select("*") 插入,gorm 的 default:true 不生效,零值 false 直接落库,这些子块一出生就是禁用的。补上 IsEnabled: true —— 否则第 1 点 的过滤会把它们永久丢弃。其余 CreateChunks 调用方均已显式设置该字段。 3. 摘要刷新每次都新建一条 summary 分块,旧的留着且仍然启用。原因是它复用了 ListChunksByKnowledgeID 的结果,而那个查询硬编码 chunk_type = 'text', "查找已有 summary 分块"的分支永远匹配不上。残留的旧摘要描述的是编辑前的 文档,会让用户已经删掉的内容继续被检索到。新增按 chunk_type 过滤的仓储 方法,刷新时原地更新已有 summary 分块。
2026-08-17 10:53:22 +00:00
summaryChunks = append(summaryChunks, chunk)
}
fix(retrieval): 分段中删除的图片不再被检索到 从分段里删掉一张图片后,这张图仍会回到检索结果和模型上下文里。 三个问题串在一起: 1. 删图时 syncEditedChunkImages 会把 image_ocr / image_caption 子块置为 禁用,但 CollectImageInfoByChunkIDs 查子块时不看 is_enabled,又把它们的 image_info 挂回了父块。knowledge_search 工具随后把每条 image_info 无条件 渲染成 markdown 图片写进 LLM 上下文,图片就这样回来了。这里按 is_enabled 过滤,两级遍历都跳过禁用子块。过滤放在 collector 而不是工具输出层:纯图片 分块的正文本身就是 OCR 文本、没有 markdown 图片语法,按正文过滤会误杀。 chat_pipeline 里既有的 fake 仓储 fixture 同步补上 IsEnabled: true:它们不 走 DB 默认值,零值 false 会被新的过滤当成已禁用子块。 2. UpdateImageInfo 补建 image_ocr / image_caption 子块时没有设置 IsEnabled。 CreateChunks 用 Select("*") 插入,gorm 的 default:true 不生效,零值 false 直接落库,这些子块一出生就是禁用的。补上 IsEnabled: true —— 否则第 1 点 的过滤会把它们永久丢弃。其余 CreateChunks 调用方均已显式设置该字段。 3. 摘要刷新每次都新建一条 summary 分块,旧的留着且仍然启用。原因是它复用了 ListChunksByKnowledgeID 的结果,而那个查询硬编码 chunk_type = 'text', "查找已有 summary 分块"的分支永远匹配不上。残留的旧摘要描述的是编辑前的 文档,会让用户已经删掉的内容继续被检索到。新增按 chunk_type 过滤的仓储 方法,刷新时原地更新已有 summary 分块。
2026-08-17 10:53:22 +00:00
if len(summaryChunks) == 0 {
summaryChunk := &types.Chunk{
ID: uuid.NewString(), TenantID: tenantID, KnowledgeID: knowledge.ID,
feat(knowledge): derive knowledge base descriptions from document profiles (#3370) * feat(knowledge): derive knowledge base descriptions from document profiles Knowledge bases only had a hand-written description, which most users leave empty, so agents bound to several knowledge bases had nothing to route on and searched all of them. This adds a generated description that is derived from per-document data instead of maintained by a model. Document profile: the summary call now returns JSON with a 2-3 sentence summary plus a gist, 3-5 topic keywords, a document type and one typical question (knowledges.profile). Input is capped at 8k chars and output at 1024 tokens; plain-text replies from custom templates still work and simply carry no profile. The summary chunk embeds the gist and short summary. Knowledge base aggregate: a database-only fold over those rows (counts per file type, tag, normalized topic and doc type; stratified samples of titles and questions; a hash of the inputs). Deleting, moving or re-parsing a document changes nothing but the rows, so the next rebuild is exact without any model judgement. Description text: one small model call over the aggregate yields a gist, merged topics and typical questions (knowledge_bases. generated_profile). The call is skipped when the aggregate hash is unchanged; failures keep the previous text and record the error; an empty knowledge base clears it. The manual description is never touched, and the agent runtime context renders both so the model can pass knowledge_base_ids instead of fanning out. Refreshes are requested from summary task exit, post-process completion, deletion, cross-KB moves and enabling the option, debounced per knowledge base in 30 s windows via kb:profile on the summary queue. POST /knowledge-bases/:id/profile/generate regenerates synchronously. profile_config (enabled, model_id, custom_instructions) opts a document knowledge base in; the settings dialog shows the generated card with regenerate and adopt-as-description actions in five locales. Search results now log hits per chunk type so the value of indexing summary chunks can be measured. Migrations 000101 (PostgreSQL) and 000021 (SQLite) add the columns; the SQLite schema test expects the new version and columns. * fix(knowledge): keep generated descriptions out of duplicates and refresh clones DuplicateKnowledgeBase copies the source row through JSON, which carried generated_profile onto a knowledge base that has no documents yet, so an empty duplicate advertised the source's topics. The duplicate now starts without a generated description and keeps profile_config so it derives its own once documents arrive. CopyKnowledgeBase builds the target field by field and skipped profile_config, and the clone task never asked for a description after copying the documents, so a clone stayed undescribed until its next upload. The target now carries a copy of profile_config and both clone paths request a refresh on completion. * fix(knowledge): refresh the loaded clone target and carry document profiles ProcessKBClone requested the description refresh with the reservation stub it builds before CopyKnowledgeBase runs. For the main create path that stub has neither a type nor profile_config, so the refresh helper rejected it and nothing was enqueued. The refresh now uses the loaded target returned by CopyKnowledgeBase. cloneKnowledge copied the summary text but not the structured profile, so even a scheduled refresh would have aggregated titles without topics until every clone was re-summarized. Cloned documents now carry an independent copy of the profile.
2026-09-17 14:21:55 +00:00
KnowledgeBaseID: knowledge.KnowledgeBaseID, Content: summaryChunkContent,
ChunkIndex: maxIndex + 1, IsEnabled: true, ChunkType: types.ChunkTypeSummary,
ParentChunkID: textChunks[0].ID, CreatedAt: time.Now(), UpdatedAt: time.Now(),
}
if err := s.chunkRepo.CreateChunks(ctx, []*types.Chunk{summaryChunk}); err != nil {
return nil, err
}
summaryChunks = append(summaryChunks, summaryChunk)
}
if err := s.updateChunkVector(ctx, knowledge.KnowledgeBaseID, summaryChunks); err != nil {
return nil, err
}
}
return knowledge, nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// ReparseKnowledge deletes existing document content and re-parses the knowledge asynchronously.
// This method reuses the logic from UpdateManualKnowledge for resource cleanup and async parsing.
func (s *knowledgeService) ReparseKnowledge(
ctx context.Context,
knowledgeID string,
processOverrides *types.KnowledgeProcessOverrides,
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
) (*types.Knowledge, error) {
return s.reparseKnowledge(ctx, knowledgeID, processOverrides, false)
}
// reparseKnowledge implements ReparseKnowledge. tasksDequeued tells it the
// caller already dropped the knowledge's queued tasks (ReplaceKnowledgeFile
// does, before pointing the row at the new file), which saves a second scan
// of every queue.
func (s *knowledgeService) reparseKnowledge(
ctx context.Context,
knowledgeID string,
processOverrides *types.KnowledgeProcessOverrides,
tasksDequeued bool,
) (*types.Knowledge, error) {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Info(ctx, "Start re-parsing knowledge")
existing, kb, err := loadKnowledgeWrite(ctx, s.repo, s.kbService, knowledgeID)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
logger.Errorf(ctx, "Failed to load knowledge: %v", err)
return nil, err
}
tenantID := existing.TenantID
// When the caller supplies new overrides (e.g. via the reparse confirm
// dialog), validate them against this knowledge's file type, then persist
// to metadata so both this call's enqueue and the worker re-read the same
// config. nil keeps whatever was stored at upload time.
if processOverrides != nil {
if err := ValidateProcessOverrides(ctx, kb, processOverrides, reparseFileTypes(existing)); err != nil {
return nil, err
}
if err := existing.SetProcessOverrides(processOverrides); err != nil {
logger.Errorf(ctx, "Failed to set process overrides on reparse: %v", err)
return nil, err
}
if err := s.repo.UpdateKnowledgeColumn(ctx, existing.ID, "metadata", existing.Metadata); err != nil {
logger.Errorf(ctx, "Failed to persist process overrides on reparse: %v", err)
return nil, err
}
}
processOverrides, _ = existing.ProcessOverrides()
reparseEff := ResolveProcessConfig(kb, processOverrides)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
var manualContent string
if existing.IsManual() {
meta, metaErr := existing.ManualMetadata()
if metaErr != nil || meta == nil {
logger.Errorf(ctx, "Failed to get manual metadata for reparse: %v", metaErr)
return nil, werrors.NewBadRequestError("无法获取手工知识内容")
}
manualContent = meta.Content
} else {
// Cleanup synchronously; manual knowledge is cleaned up by its worker.
logger.Infof(ctx, "Cleaning up existing resources for knowledge: %s", knowledgeID)
if err := s.cleanupKnowledgeResources(ctx, existing); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_id": knowledgeID,
})
return nil, err
}
}
// Everything that can reject the reparse has run. From here on the
// previous run is superseded, so stop it before announcing the new one.
//
// A reparse may land while the previous run is still in flight (batch
// reparse and the API do not gate on status). Its queued tasks would
// otherwise run against the new attempt: an old ProcessDocument wipes the
// new chunks and writes "processing" back, an old post-process seeds the
// counter for subtasks that all drop themselves as superseded.
if !tasksDequeued && isInFlightParseStatus(existing.ParseStatus) {
s.dequeueKnowledgeTasks(ctx, existing.ID)
}
// Allocate the new span tree attempt only now. Opening it earlier and
// then rejecting the reparse left the previous run's subtasks seeing a
// newer attempt: they skipped their drain as superseded and stranded the
// row in "finalizing". Opening it before the enqueue still means the UI
// shows the fresh attempt immediately and the worker does not allocate a
// second one.
reparseAttempt := 0
if root, n, err := s.tracker().OpenAttempt(ctx, existing.ID, ""); err == nil && root != nil {
reparseAttempt = n
} else if err != nil {
logger.Warnf(ctx, "[Reparse] OpenAttempt failed for %s: %v (will fall back in worker)", existing.ID, err)
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Keep wiki's pending queue consistent across both manual and non-manual
// paths. The destructive work (swapping old wiki contributions for new)
// happens asynchronously inside mapOneDocument — see its oldPageSlugs
// handling — once post-process re-enqueues wiki ingest. All we need to
// do here is stop any stale pending ingest op from firing against the
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
// pre-reparse chunk set. The op's finalizing slot is not released: the
// reset below zeroes the counter. Scrub even when wiki is off now: an op
// left by an earlier wiki-enabled run would otherwise drain a slot of
// the new attempt.
s.prepareWikiForReparse(ctx, existing)
recordReparseStarted := func() {
recordKBActivity(ctx, s.audit, tenantID, existing.KnowledgeBaseID, types.AuditActionKnowledgeReparseStarted,
"knowledge", existing.ID, types.AuditOutcomeAccepted,
map[string]any{"title": existing.Title, "type": existing.Type, "attempt": reparseAttempt})
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// For manual knowledge, use async manual processing (cleanup + re-indexing in worker)
if existing.IsManual() {
resetKnowledgeForReparse(existing, kb)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err := s.repo.UpdateKnowledge(ctx, existing); err != nil {
logger.Errorf(ctx, "Failed to update knowledge status before reparse: %v", err)
return nil, err
}
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
if err := s.repo.UpdateKnowledgeColumn(ctx, existing.ID, "pending_subtasks_count", 0); err != nil {
logger.Errorf(ctx, "Failed to reset pending_subtasks_count before reparse: %v", err)
return nil, err
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if _, err := s.enqueueManualProcessing(ctx, existing, manualContent, true); err != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Errorf(ctx, "Failed to enqueue manual reparse task: %v", err)
s.markKnowledgeEnqueueFailed(ctx, existing)
return existing, werrors.NewInternalServerError("Failed to submit processing task")
} else {
recordReparseStarted()
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
return existing, nil
}
// Step 2: Update knowledge status and metadata
resetKnowledgeForReparse(existing, kb)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err := s.repo.UpdateKnowledge(ctx, existing); err != nil {
logger.Errorf(ctx, "Failed to update knowledge status before reparse: %v", err)
return nil, err
}
fix(knowledge): make finalizing subtask counter reliable + async question fan-out The finalizing subtask counter (pending_subtasks_count) could get stuck at a non-zero value, leaving knowledge permanently in "finalizing" and never promoted to "completed". Root cause and related hardening: - UpdateKnowledge does a full-row Save; pending_subtasks_count was NOT in the omit list, so any concurrent enrichment subtask that loaded the row, did slow work (LLM call), then saved an unrelated field wrote back the STALE counter, clobbering decrements other subtasks performed in between. Add PendingSubtasksCount to omitFieldsOnUpdate so only the atomic helpers (SetFinalizing / FinalizeSubtask / explicit column writes) ever touch it. - FinalizeSubtask no longer gates the finalizing->completed promote on a separate re-read of the counter. Every caller unconditionally runs the guarded promote UPDATE (WHERE pending_subtasks_count = 0), the single authoritative atomic check, so a racy/stale read can't strand the row. - Decrements run on a context detached from the caller's cancellation (context.WithoutCancel + timeout) so graceful shutdown / preemption can't silently skip a decrement. - Reconcile seeded vs actually-enqueued subtask slots (summary/question/graph) and release any shortfall so un-enqueued planned slots (e.g. graph with NEO4J off) don't strand the row. - Reparse paths reset pending_subtasks_count via an explicit column write since full-row Save now omits it. Question generation is also moved off the synchronous single-task path onto a batched async fan-out (windows of text chunks), each batch independently queued / retried / traced, grouped under a postprocess.question span.
2026-05-29 16:09:46 +00:00
if err := s.repo.UpdateKnowledgeColumn(ctx, existing.ID, "pending_subtasks_count", 0); err != nil {
logger.Errorf(ctx, "Failed to reset pending_subtasks_count before reparse: %v", err)
return nil, err
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Step 3: Trigger async re-parsing based on knowledge type
logger.Infof(ctx, "Knowledge status updated, scheduling async reparse, ID: %s, Type: %s", existing.ID, existing.Type)
// For file-based knowledge, enqueue document processing task
if existing.FilePath != "" {
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
enableMultimodel := reparseEff.EnableMultimodel
enableQuestionGeneration := reparseEff.QuestionGenerationConfig.Enabled
questionCount := reparseEff.QuestionGenerationConfig.QuestionCount
if questionCount <= 0 {
questionCount = 3
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
lang := types.LanguageFromContextOrDefault(ctx)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
taskPayload := types.DocumentProcessPayload{
TenantID: tenantID,
KnowledgeID: existing.ID,
KnowledgeBaseID: existing.KnowledgeBaseID,
FilePath: existing.FilePath,
FileName: existing.FileName,
FileType: getFileType(existing.FileName),
EnableMultimodel: enableMultimodel,
EnableQuestionGeneration: enableQuestionGeneration,
QuestionCount: questionCount,
Language: lang,
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
Attempt: reparseAttempt,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
langfuse.InjectTracing(ctx, &taskPayload)
payloadBytes, err := json.Marshal(taskPayload)
if err != nil {
logger.Errorf(ctx, "Failed to marshal reparse task payload: %v", err)
s.markKnowledgeEnqueueFailed(ctx, existing)
return existing, werrors.NewInternalServerError("Failed to submit processing task")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
2026-05-28 08:31:43 +00:00
task := asynq.NewTask(
types.TypeDocumentProcess,
payloadBytes,
documentProcessTaskOptions(s.config, asynq.MaxRetry(3))...,
)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
info, err := s.task.Enqueue(task)
if err != nil {
logger.Errorf(ctx, "Failed to enqueue reparse task: %v", err)
s.markKnowledgeEnqueueFailed(ctx, existing)
return existing, werrors.NewInternalServerError("Failed to submit processing task")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
logger.Infof(ctx, "Enqueued reparse task: id=%s queue=%s knowledge_id=%s", info.ID, info.Queue, existing.ID)
recordReparseStarted()
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// For data tables (csv, xlsx, xls), also enqueue summary task
enqueueDataTableSummaryIfNeeded(ctx, s.task, tenantID, existing.ID, existing.FileName, existing.FileType, kb.SummaryModelID, kb.EmbeddingModelID)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return existing, nil
}
// For file-URL-based knowledge, enqueue document processing task with FileURL field
if existing.Type == "file_url" && existing.Source != "" {
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
enableMultimodel := reparseEff.EnableMultimodel
enableQuestionGeneration := reparseEff.QuestionGenerationConfig.Enabled
questionCount := reparseEff.QuestionGenerationConfig.QuestionCount
if questionCount <= 0 {
questionCount = 3
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
lang := types.LanguageFromContextOrDefault(ctx)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
taskPayload := types.DocumentProcessPayload{
TenantID: tenantID,
KnowledgeID: existing.ID,
KnowledgeBaseID: existing.KnowledgeBaseID,
FileURL: existing.Source,
FileName: existing.FileName,
FileType: existing.FileType,
EnableMultimodel: enableMultimodel,
EnableQuestionGeneration: enableQuestionGeneration,
QuestionCount: questionCount,
Language: lang,
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
Attempt: reparseAttempt,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
langfuse.InjectTracing(ctx, &taskPayload)
payloadBytes, err := json.Marshal(taskPayload)
if err != nil {
logger.Errorf(ctx, "Failed to marshal file URL reparse task payload: %v", err)
s.markKnowledgeEnqueueFailed(ctx, existing)
return existing, werrors.NewInternalServerError("Failed to submit processing task")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
2026-05-28 08:31:43 +00:00
task := asynq.NewTask(
types.TypeDocumentProcess,
payloadBytes,
documentProcessTaskOptions(s.config)...,
)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
info, err := s.task.Enqueue(task)
if err != nil {
logger.Errorf(ctx, "Failed to enqueue file URL reparse task: %v", err)
s.markKnowledgeEnqueueFailed(ctx, existing)
return existing, werrors.NewInternalServerError("Failed to submit processing task")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
logger.Infof(ctx, "Enqueued file URL reparse task: id=%s queue=%s knowledge_id=%s", info.ID, info.Queue, existing.ID)
recordReparseStarted()
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
enqueueDataTableSummaryIfNeeded(ctx, s.task, tenantID, existing.ID, existing.FileName, existing.FileType, kb.SummaryModelID, kb.EmbeddingModelID)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return existing, nil
}
// For URL-based knowledge, enqueue URL processing task
if existing.Type == "url" && existing.Source != "" {
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
enableMultimodel := reparseEff.EnableMultimodel
enableQuestionGeneration := reparseEff.QuestionGenerationConfig.Enabled
questionCount := reparseEff.QuestionGenerationConfig.QuestionCount
if questionCount <= 0 {
questionCount = 3
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
lang := types.LanguageFromContextOrDefault(ctx)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
taskPayload := types.DocumentProcessPayload{
TenantID: tenantID,
KnowledgeID: existing.ID,
KnowledgeBaseID: existing.KnowledgeBaseID,
URL: existing.Source,
EnableMultimodel: enableMultimodel,
EnableQuestionGeneration: enableQuestionGeneration,
QuestionCount: questionCount,
Language: lang,
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
Attempt: reparseAttempt,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
langfuse.InjectTracing(ctx, &taskPayload)
payloadBytes, err := json.Marshal(taskPayload)
if err != nil {
logger.Errorf(ctx, "Failed to marshal URL reparse task payload: %v", err)
s.markKnowledgeEnqueueFailed(ctx, existing)
return existing, werrors.NewInternalServerError("Failed to submit processing task")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
2026-05-28 08:31:43 +00:00
task := asynq.NewTask(
types.TypeDocumentProcess,
payloadBytes,
documentProcessTaskOptions(s.config, asynq.MaxRetry(3))...,
)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
info, err := s.task.Enqueue(task)
if err != nil {
logger.Errorf(ctx, "Failed to enqueue URL reparse task: %v", err)
s.markKnowledgeEnqueueFailed(ctx, existing)
return existing, werrors.NewInternalServerError("Failed to submit processing task")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
logger.Infof(ctx, "Enqueued URL reparse task: id=%s queue=%s knowledge_id=%s", info.ID, info.Queue, existing.ID)
recordReparseStarted()
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return existing, nil
}
logger.Warnf(ctx, "Knowledge %s has no parseable content (no file, URL, or manual content)", knowledgeID)
existing.ParseStatus = types.ParseStatusFailed
existing.ErrorMessage = "Knowledge has no parseable content"
if err := s.repo.UpdateKnowledge(ctx, existing); err != nil {
logger.Errorf(ctx, "Failed to persist unparseable knowledge state for %s: %v",
secutils.SanitizeForLog(knowledgeID), err)
}
return existing, werrors.NewBadRequestError("Knowledge has no parseable content")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// resetKnowledgeForReparse makes the top-level knowledge state describe the
// new processing attempt rather than retaining terminal state from the
// previous one.
func resetKnowledgeForReparse(knowledge *types.Knowledge, kb *types.KnowledgeBase) {
knowledge.ParseStatus = types.ParseStatusPending
knowledge.EnableStatus = "disabled"
knowledge.Description = ""
knowledge.ProcessedAt = nil
knowledge.ErrorMessage = ""
knowledge.EmbeddingModelID = kb.EmbeddingModelID
// UpdateKnowledge deliberately omits pending_subtasks_count, so callers
// must still persist this reset through an explicit column update.
knowledge.PendingSubtasksCount = 0
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// CancelKnowledgeParse marks an in-progress parse as cancelled by the user.
//
// Semantics (kept aligned with the existing deleting path, but partial work
// is preserved instead of cleaned up):
// - parse_status is set to "cancelled"; partial chunks/index already written
// to the database remain on disk. The user can re-trigger parsing via the
// existing ReparseKnowledge API, which overwrites status back to pending.
// - Any in-flight worker reads the new status at its next checkpoint and
// bails (see processChunks / ProcessDocument / downstream handlers).
// - The asynq inspector (if available) dequeues pending / scheduled / retry
// tasks for this knowledge_id across all queues used by the pipeline
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// and signals active workers to stop. Lite mode (no Redis) skips the
// dequeue step — the checkpoint-based abort is the only stop signal there.
// - Idempotent: re-calling on an already-cancelled row is a no-op.
//
// Errors:
// - ParseStatusCompleted / ParseStatusFailed: the parse has already finished.
// - ParseStatusDeleting: a delete is in progress; cancel cannot supersede it.
func (s *knowledgeService) CancelKnowledgeParse(
ctx context.Context, knowledgeID string,
) (*types.Knowledge, error) {
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
existing, err := s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
if err != nil {
logger.Errorf(ctx, "CancelKnowledgeParse: failed to load knowledge: %v", err)
return nil, err
}
if existing == nil {
return nil, werrors.NewNotFoundError("knowledge not found")
}
switch existing.ParseStatus {
case types.ParseStatusCancelled:
// Idempotent — still attempt the dequeue in case earlier calls
// raced an enqueue, but skip the row update / span close path.
s.dequeueKnowledgeTasks(ctx, knowledgeID)
return existing, nil
case types.ParseStatusCompleted, types.ParseStatusFailed:
return nil, werrors.NewBadRequestError("解析已结束,无法取消")
case types.ParseStatusDeleting:
return nil, werrors.NewBadRequestError("知识正在删除中,无法取消解析")
case types.ParseStatusPending, types.ParseStatusProcessing, types.ParseStatusFinalizing:
// Cancellable. `finalizing` is the post-process fan-out window
// where graph-extract / summary / question subtasks are still
// running; cancel here stops the LLM cost they would burn.
default:
// Unknown status — let it through but log. Should never happen
// outside test fixtures or hand-edited rows.
logger.Warnf(ctx, "CancelKnowledgeParse: unexpected status %q for %s, proceeding",
existing.ParseStatus, knowledgeID)
}
// Flip the row to cancelled and zero the enrichment counter in one
// update so a late subtask FinalizeSubtask call can't race-promote
// the row back to completed. Persisted partial data is left in
// place — the user can reuse it on the next reparse attempt.
now := time.Now()
if err := s.repo.UpdateKnowledgeColumns(ctx, existing.ID, map[string]interface{}{
"parse_status": types.ParseStatusCancelled,
"error_message": "用户已取消解析",
"pending_subtasks_count": 0,
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
// The summary task is dequeued (or will bail) with the rest.
"summary_status": summaryStatusClosedExpr(types.SummaryStatusNone),
"updated_at": now,
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
}); err != nil {
logger.Errorf(ctx, "CancelKnowledgeParse: failed to mark knowledge cancelled: %v", err)
return nil, err
}
existing.ParseStatus = types.ParseStatusCancelled
existing.ErrorMessage = "用户已取消解析"
existing.PendingSubtasksCount = 0
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if existing.SummaryStatus == types.SummaryStatusPending || existing.SummaryStatus == types.SummaryStatusProcessing {
existing.SummaryStatus = types.SummaryStatusNone
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
existing.UpdatedAt = now
logger.Infof(ctx, "Knowledge %s marked as cancelled by user", knowledgeID)
// Close the active attempt span tree so the UI stops showing "进行中"
// for the cancelled run. AbortAttempt cascade-cancels every still-
// running descendant (multimodal per-image, postprocess subtasks,
// graph chunks) BEFORE closing the root, otherwise the trace
// viewer would leave those striped/running bars hanging forever
// because workers exit via their abort-guard without ever calling
// FailSpan on their own subspan. Best-effort: nil tracker / missing
// attempt no-ops.
if attempt := s.tracker().LatestAttempt(ctx, knowledgeID); attempt > 0 {
s.tracker().AbortAttempt(ctx, knowledgeID, attempt,
"USER_CANCELLED", "用户已取消解析", "用户已取消解析")
}
// Best-effort dequeue. Failures here don't block the cancel — the
// downstream tasks will still self-abort at their entry guards.
s.dequeueKnowledgeTasks(ctx, knowledgeID)
// Wiki ingest lives in its own per-KB pending queue (task_pending_ops)
// rather than asynq, so dequeueKnowledgeTasks above can't see it.
// Mirror the deletion path's scrub so a cancelled knowledge doesn't
// get picked up by the next 30s batch and burn a wiki LLM call on a
// doc the user already abandoned. The in-flight worker would skip it
// at isWikiKnowledgeAborted anyway, but scrubbing avoids waking the
// batch in the first place.
s.scrubWikiPendingIngest(ctx, existing.KnowledgeBaseID, knowledgeID, "cancel")
recordKBActivity(ctx, s.audit, tenantID, existing.KnowledgeBaseID, types.AuditActionKnowledgeParseCanceled,
"knowledge", existing.ID, types.AuditOutcomeCanceled,
map[string]any{"title": existing.Title, "type": existing.Type})
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
return existing, nil
}
// dequeueKnowledgeTasks asks the task inspector to remove any queued
// tasks for this knowledge and signal active workers to stop. Safe to
// call when the inspector is a no-op (Lite mode).
func (s *knowledgeService) dequeueKnowledgeTasks(ctx context.Context, knowledgeID string) {
if s.taskInspector == nil {
return
}
if _, _, err := s.taskInspector.CancelTasksForKnowledge(ctx, knowledgeID); err != nil {
logger.Warnf(ctx, "CancelKnowledgeParse: dequeue best-effort failed for %s: %v", knowledgeID, err)
}
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
func (s *knowledgeService) updateChunkVector(ctx context.Context, kbID string, chunks []*types.Chunk) error {
// Get embedding model from knowledge base
sourceKB, err := s.kbService.GetKnowledgeBaseByID(ctx, kbID)
if err != nil {
return err
}
if !sourceKB.NeedsEmbeddingModel() {
return nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
embeddingModel, err := s.modelService.GetEmbeddingModel(ctx, sourceKB.EmbeddingModelID)
if err != nil {
return err
}
// Initialize composite retrieve engine from tenant configuration
indexInfo := make([]*types.IndexInfo, 0, len(chunks))
ids := make([]string, 0, len(chunks))
knowledgeCache := make(map[string]*types.Knowledge)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
for _, chunk := range chunks {
if chunk.KnowledgeBaseID != kbID {
logger.Warnf(ctx, "Knowledge base ID mismatch: %s != %s", chunk.KnowledgeBaseID, kbID)
continue
}
ids = append(ids, chunk.ID)
if !chunk.IsEnabled || chunk.ChunkType == types.ChunkTypeParentText {
continue
}
knowledge := knowledgeCache[chunk.KnowledgeID]
if knowledge == nil {
knowledge, err = s.repo.GetKnowledgeByID(ctx, chunk.TenantID, chunk.KnowledgeID)
if err != nil {
return err
}
knowledgeCache[chunk.KnowledgeID] = knowledge
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
indexInfo = append(indexInfo, &types.IndexInfo{
Content: buildKnowledgeIndexContent(knowledge, chunk.EmbeddingContent()),
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
SourceID: chunk.ID,
SourceType: types.ChunkSourceType,
ChunkID: chunk.ID,
KnowledgeID: chunk.KnowledgeID,
KnowledgeBaseID: chunk.KnowledgeBaseID,
KnowledgeType: sourceKB.Type,
IsEnabled: chunk.IsEnabled,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
})
meta, metaErr := chunk.DocumentMetadata()
if metaErr != nil {
return metaErr
}
if meta != nil {
for _, q := range meta.GeneratedQuestions {
if strings.TrimSpace(q.Question) != "" {
indexInfo = append(indexInfo, &types.IndexInfo{
Content: buildKnowledgeIndexContent(knowledge, q.Question), SourceID: types.GeneratedQuestionSourceID(chunk.ID, q.ID),
SourceType: types.ChunkSourceType, ChunkID: chunk.ID,
KnowledgeID: chunk.KnowledgeID, KnowledgeBaseID: chunk.KnowledgeBaseID,
KnowledgeType: sourceKB.Type, IsEnabled: true,
})
}
}
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
refactor(retriever): introduce factory for KB-scoped retrieve engine resolution Extracts the 25 repeated NewCompositeRetrieveEngine call sites across seven services into two factory functions with tenant-ownership verification: CreateRetrieveEngineForKB (synchronous) and CreateRetrieveEngineFromPayload (async task handlers). Promotes GetByStoreID from concrete-only to interfaces.RetrieveEngineRegistry. Extends KBDeletePayload / IndexDeletePayload with an omitempty VectorStoreID snapshot. Design highlights - Factory verifies tenant ownership of the resolved store (defense-in-depth) so a gap in PR3 validation or a tampered Asynq payload cannot cross tenants. Cross-tenant attempts return ErrVectorStoreForbidden with a structured log entry. - Sentinel errors (ErrTenantInfoMissing, ErrVectorStoreNotFound, ErrVectorStoreForbidden) let async handlers classify non-retryable failures as asynq.SkipRetry. - nil and empty-string pointers for vectorStoreID normalize to "unbound" so callers never send an empty UUID to GetByStoreID. - resolveBoundEngine constructs engineInfos directly (with slices.Clone of Support()) instead of going through NewCompositeRetrieveEngine. The latter only reads from the byEngineType map and cannot reach DB stores in byStoreID -- multiple stores can share the same engine type. Unbound fallbacks still reuse NewCompositeRetrieveEngine so the tenant effective-engines path is byte-for-byte unchanged. - DeleteKnowledgeBase now reads the KB before soft-delete so the enqueued KBDeletePayload carries a VectorStoreID snapshot; once the row is soft-deleted GORM's default scope hides it. Cost: +1 SELECT per KB-delete request (a rare admin operation). - enqueueIndexDeleteTask gains a vectorStoreID *string parameter that the single caller (tag.go) populates from the owning KB. The worker (ProcessIndexDelete) validates ownership via the factory. - cleanupKnowledgeResources loads the KB so bound-store cleanup routes correctly. If the load fails it warns and falls back to tenant effective engines; orphan vectors become observable in logs instead of disappearing silently. - DeleteKnowledges (batch) stays on the tenant effective-engines path -- batches can span stores and multi-store fan-out is PR4 scope. Noted inline. Merge safety All knowledge bases have VectorStoreID = NULL at merge time (introduced nullable in PR1, Tencent/WeKnora#994). Every factory call falls back to NewCompositeRetrieveEngine(registry, tenantInfo.GetEffectiveEngines()), which is the existing code path for these KBs. Async payloads from before this change decode to VectorStoreID = nil (omitempty) and take the same fallback. Testing - go build ./... - go vet ./... - go test -race -count=1 ./internal/application/service/retriever/... covers unbound (nil/empty), bound, cross-tenant, unregistered store, ownership infra error, legacy payload shapes (missing field/null/ empty string/nil), tampered payload, and parallel invocation. - grep -r NewCompositeRetrieveEngine internal/application/service returns zero results outside factory.go/composite.go. Refs: Part of Tencent/WeKnora#993. Depends on Tencent/WeKnora#994.
2026-05-13 08:24:17 +00:00
retrieveEngine, err := retriever.CreateRetrieveEngineForKB(
ctx, s.retrieveEngine, s.ownership, types.MustTenantIDFromContext(ctx), sourceKB.VectorStoreID)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
return err
}
// Delete old vector representation of the chunk
err = retrieveEngine.DeleteByChunkIDList(ctx, ids, embeddingModel.GetDimensions(), sourceKB.Type)
if err != nil {
return err
}
// Index updated chunk content with new vector representation
err = retrieveEngine.BatchIndex(ctx, embeddingModel, indexInfo)
if err != nil {
return err
}
return nil
}
func (s *knowledgeService) UpdateImageInfo(
ctx context.Context,
knowledgeID string,
chunkID string,
imageInfo string,
) error {
knowledge, _, err := loadKnowledgeWrite(ctx, s.repo, s.kbService, knowledgeID)
if err != nil {
return err
}
imageInfo = common.CleanInvalidUTF8(imageInfo)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
var images []*types.ImageInfo
if err := json.Unmarshal([]byte(imageInfo), &images); err != nil {
logger.Errorf(ctx, "Failed to unmarshal image info: %v", err)
return err
}
if len(images) != 1 {
logger.Warnf(ctx, "Expected exactly one image info, got %d", len(images))
return nil
}
image := images[0]
// Retrieve all chunks with the given parent chunk ID
chunk, err := s.chunkService.GetChunkByID(ctx, chunkID)
if err != nil {
logger.Errorf(ctx, "Failed to get chunk: %v", err)
return err
}
if chunk == nil || chunk.ID != chunkID || chunk.KnowledgeID != knowledge.ID ||
chunk.TenantID != knowledge.TenantID ||
chunk.KnowledgeBaseID != knowledge.KnowledgeBaseID {
return werrors.NewForbiddenError("chunk does not belong to its knowledge document")
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
chunk.ImageInfo = imageInfo
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
chunkChildren, err := s.chunkService.ListChunkByParentID(ctx, tenantID, chunkID)
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"parent_chunk_id": chunkID,
"tenant_id": tenantID,
})
return err
}
for _, child := range chunkChildren {
if !sameChunkDocument(chunk, child) {
return werrors.NewForbiddenError("image child does not belong to its document")
}
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Infof(ctx, "Found %d chunks with parent chunk ID: %s", len(chunkChildren), chunkID)
// Iterate through each chunk and update its content based on the image information
updateChunk := []*types.Chunk{chunk}
var addChunk []*types.Chunk
// Track whether we've found OCR and caption child chunks for this image
hasOCRChunk := false
hasCaptionChunk := false
for i, child := range chunkChildren {
// Skip chunks that are not image types
var cImageInfo []*types.ImageInfo
err = json.Unmarshal([]byte(child.ImageInfo), &cImageInfo)
if err != nil {
logger.Warnf(ctx, "Failed to unmarshal image %s info: %v", child.ID, err)
continue
}
if len(cImageInfo) == 0 {
continue
}
if cImageInfo[0].OriginalURL != image.OriginalURL {
logger.Warnf(ctx, "Skipping chunk ID: %s, image URL mismatch: %s != %s",
child.ID, cImageInfo[0].OriginalURL, image.OriginalURL)
continue
}
// Mark that we've found chunks for this image
switch child.ChunkType {
case types.ChunkTypeImageCaption:
hasCaptionChunk = true
// Update caption if it has changed
if image.Caption != cImageInfo[0].Caption {
child.Content = image.Caption
child.ImageInfo = imageInfo
updateChunk = append(updateChunk, chunkChildren[i])
}
case types.ChunkTypeImageOCR:
hasOCRChunk = true
// Update OCR if it has changed
if image.OCRText != cImageInfo[0].OCRText {
child.Content = image.OCRText
child.ImageInfo = imageInfo
updateChunk = append(updateChunk, chunkChildren[i])
}
}
}
// Create a new caption chunk if it doesn't exist and we have caption data
if !hasCaptionChunk && image.Caption != "" {
captionChunk := &types.Chunk{
ID: uuid.New().String(),
TenantID: tenantID,
KnowledgeID: chunk.KnowledgeID,
KnowledgeBaseID: chunk.KnowledgeBaseID,
Content: image.Caption,
ChunkType: types.ChunkTypeImageCaption,
ParentChunkID: chunk.ID,
ImageInfo: imageInfo,
fix(retrieval): 分段中删除的图片不再被检索到 从分段里删掉一张图片后,这张图仍会回到检索结果和模型上下文里。 三个问题串在一起: 1. 删图时 syncEditedChunkImages 会把 image_ocr / image_caption 子块置为 禁用,但 CollectImageInfoByChunkIDs 查子块时不看 is_enabled,又把它们的 image_info 挂回了父块。knowledge_search 工具随后把每条 image_info 无条件 渲染成 markdown 图片写进 LLM 上下文,图片就这样回来了。这里按 is_enabled 过滤,两级遍历都跳过禁用子块。过滤放在 collector 而不是工具输出层:纯图片 分块的正文本身就是 OCR 文本、没有 markdown 图片语法,按正文过滤会误杀。 chat_pipeline 里既有的 fake 仓储 fixture 同步补上 IsEnabled: true:它们不 走 DB 默认值,零值 false 会被新的过滤当成已禁用子块。 2. UpdateImageInfo 补建 image_ocr / image_caption 子块时没有设置 IsEnabled。 CreateChunks 用 Select("*") 插入,gorm 的 default:true 不生效,零值 false 直接落库,这些子块一出生就是禁用的。补上 IsEnabled: true —— 否则第 1 点 的过滤会把它们永久丢弃。其余 CreateChunks 调用方均已显式设置该字段。 3. 摘要刷新每次都新建一条 summary 分块,旧的留着且仍然启用。原因是它复用了 ListChunksByKnowledgeID 的结果,而那个查询硬编码 chunk_type = 'text', "查找已有 summary 分块"的分支永远匹配不上。残留的旧摘要描述的是编辑前的 文档,会让用户已经删掉的内容继续被检索到。新增按 chunk_type 过滤的仓储 方法,刷新时原地更新已有 summary 分块。
2026-08-17 10:53:22 +00:00
// CreateChunks inserts with Select("*"), so the gorm default:true never
// applies -- an unset IsEnabled lands in the database as false and the
// chunk is silently excluded from retrieval and model context.
IsEnabled: true,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
addChunk = append(addChunk, captionChunk)
logger.Infof(ctx, "Created new caption chunk ID: %s for image URL: %s", captionChunk.ID, image.OriginalURL)
}
// Create a new OCR chunk if it doesn't exist and we have OCR data
if !hasOCRChunk && image.OCRText != "" {
ocrChunk := &types.Chunk{
ID: uuid.New().String(),
TenantID: tenantID,
KnowledgeID: chunk.KnowledgeID,
KnowledgeBaseID: chunk.KnowledgeBaseID,
Content: image.OCRText,
ChunkType: types.ChunkTypeImageOCR,
ParentChunkID: chunk.ID,
ImageInfo: imageInfo,
fix(retrieval): 分段中删除的图片不再被检索到 从分段里删掉一张图片后,这张图仍会回到检索结果和模型上下文里。 三个问题串在一起: 1. 删图时 syncEditedChunkImages 会把 image_ocr / image_caption 子块置为 禁用,但 CollectImageInfoByChunkIDs 查子块时不看 is_enabled,又把它们的 image_info 挂回了父块。knowledge_search 工具随后把每条 image_info 无条件 渲染成 markdown 图片写进 LLM 上下文,图片就这样回来了。这里按 is_enabled 过滤,两级遍历都跳过禁用子块。过滤放在 collector 而不是工具输出层:纯图片 分块的正文本身就是 OCR 文本、没有 markdown 图片语法,按正文过滤会误杀。 chat_pipeline 里既有的 fake 仓储 fixture 同步补上 IsEnabled: true:它们不 走 DB 默认值,零值 false 会被新的过滤当成已禁用子块。 2. UpdateImageInfo 补建 image_ocr / image_caption 子块时没有设置 IsEnabled。 CreateChunks 用 Select("*") 插入,gorm 的 default:true 不生效,零值 false 直接落库,这些子块一出生就是禁用的。补上 IsEnabled: true —— 否则第 1 点 的过滤会把它们永久丢弃。其余 CreateChunks 调用方均已显式设置该字段。 3. 摘要刷新每次都新建一条 summary 分块,旧的留着且仍然启用。原因是它复用了 ListChunksByKnowledgeID 的结果,而那个查询硬编码 chunk_type = 'text', "查找已有 summary 分块"的分支永远匹配不上。残留的旧摘要描述的是编辑前的 文档,会让用户已经删掉的内容继续被检索到。新增按 chunk_type 过滤的仓储 方法,刷新时原地更新已有 summary 分块。
2026-08-17 10:53:22 +00:00
IsEnabled: true,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
addChunk = append(addChunk, ocrChunk)
logger.Infof(ctx, "Created new OCR chunk ID: %s for image URL: %s", ocrChunk.ID, image.OriginalURL)
}
logger.Infof(ctx, "Updated %d chunks out of %d total chunks", len(updateChunk), len(chunkChildren)+1)
if len(addChunk) > 0 {
err := s.chunkRepo.CreateChunks(ctx, addChunk)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"add_chunk_size": len(addChunk),
})
return err
}
}
// Update the chunks
for _, c := range updateChunk {
err := s.chunkRepo.UpdateChunk(ctx, c)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"chunk_id": c.ID,
"knowledge_id": c.KnowledgeID,
})
return err
}
}
// Update the chunk vector
err = s.updateChunkVector(ctx, chunk.KnowledgeBaseID, append(updateChunk, addChunk...))
if err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"chunk_id": chunk.ID,
"knowledge_id": chunk.KnowledgeID,
})
return err
}
// Update the knowledge file hash
knowledge, err = s.repo.GetKnowledgeByID(ctx, tenantID, knowledgeID)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
logger.Errorf(ctx, "Failed to get knowledge: %v", err)
return err
}
fileHash := calculateStr(knowledgeID, knowledge.FileHash, imageInfo)
knowledge.FileHash = fileHash
err = s.repo.UpdateKnowledge(ctx, knowledge)
if err != nil {
logger.Warnf(ctx, "Failed to update knowledge file hash: %v", err)
}
logger.Infof(ctx, "Updated chunk successfully, chunk ID: %s, knowledge ID: %s", chunk.ID, chunk.KnowledgeID)
return nil
}
// ProcessManualUpdate handles Asynq manual knowledge update tasks.
// It performs cleanup of old indexes/chunks (when NeedCleanup is true) and re-indexes the content.
func (s *knowledgeService) ProcessManualUpdate(ctx context.Context, t *asynq.Task) error {
var payload types.ManualProcessPayload
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
logger.Errorf(ctx, "failed to unmarshal manual process task payload: %v", err)
return nil
}
ctx = logger.WithRequestID(ctx, payload.RequestId)
ctx = logger.WithField(ctx, "manual_process", payload.KnowledgeID)
ctx = types.WithExecutionTenant(ctx, payload.TenantID)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
if err != nil {
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
// Retry: acking leaves the row pending with no task behind it.
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Errorf(ctx, "ProcessManualUpdate: failed to get tenant: %v", err)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return fmt.Errorf("get tenant %d: %w", payload.TenantID, err)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenantInfo)
knowledge, err := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if errors.Is(err, repository.ErrKnowledgeNotFound) {
logger.Warnf(ctx, "ProcessManualUpdate: knowledge not found: %s", payload.KnowledgeID)
return nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
logger.Errorf(ctx, "ProcessManualUpdate: failed to get knowledge: %v", err)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return fmt.Errorf("get knowledge %s: %w", payload.KnowledgeID, err)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
if knowledge == nil {
logger.Warnf(ctx, "ProcessManualUpdate: knowledge not found: %s", payload.KnowledgeID)
return nil
}
if err := validateProcessingKnowledge(knowledge,
payload.TenantID,
payload.KnowledgeBaseID,
payload.KnowledgeID); err != nil {
return err
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Skip if already completed or being deleted
if knowledge.ParseStatus == types.ParseStatusCompleted {
logger.Infof(ctx, "ProcessManualUpdate: already completed, skipping: %s", payload.KnowledgeID)
return nil
}
if knowledge.ParseStatus == types.ParseStatusDeleting {
logger.Infof(ctx, "ProcessManualUpdate: being deleted, skipping: %s", payload.KnowledgeID)
return nil
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
if knowledge.ParseStatus == types.ParseStatusCancelled {
logger.Infof(ctx, "ProcessManualUpdate: cancelled by user, skipping: %s", payload.KnowledgeID)
return nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, payload.KnowledgeBaseID)
if err != nil {
logger.Errorf(ctx, "ProcessManualUpdate: failed to get knowledge base: %v", err)
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = fmt.Sprintf("failed to get knowledge base: %v", err)
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
if kb == nil || kb.ID != payload.KnowledgeBaseID || kb.TenantID != payload.TenantID {
return fmt.Errorf("processing task KB owner changed: %w", asynq.SkipRetry)
}
ctx, err = access.WithKBTaskWrite(ctx, kb, payload.TenantID)
if err != nil {
return fmt.Errorf("invalid processing scope: %v: %w", err, asynq.SkipRetry)
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// Re-check abort status right before marking processing — see the same
// note in ProcessDocument for the cancel race this guards.
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
logger.Infof(ctx, "ProcessManualUpdate: knowledge aborted (%s), skipping: %s", status, knowledge.ID)
return abortRetryErr(ctx, knowledge.ID, status)
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Update status to processing
markKnowledgeProcessing(knowledge, time.Now())
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
logger.Errorf(ctx, "ProcessManualUpdate: failed to update status to processing: %v", err)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return fmt.Errorf("mark knowledge %s processing: %w", knowledge.ID, err)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// Allocate a fresh span-tracking attempt for this manual (re)index.
// Without it attemptFromCtx stays 0, so processChunks drops all stage
// spans and KnowledgePostProcess falls back to LatestAttempt — piling
// this run's summary/wiki subspans onto the previous attempt's trace.
attempt := 0
if root, n, err := s.tracker().OpenAttempt(ctx, knowledge.ID, payload.LangfuseTraceID); err == nil && root != nil {
attempt = n
} else if err != nil {
logger.Warnf(ctx, "ProcessManualUpdate: OpenAttempt failed for %s: %v", knowledge.ID, err)
}
ctx = withAttempt(ctx, attempt)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Cleanup old resources (indexes, chunks, graph) for update operations
if payload.NeedCleanup {
if err := s.cleanupKnowledgeResources(ctx, knowledge); err != nil {
logger.ErrorWithFields(ctx, err, map[string]interface{}{
"knowledge_id": payload.KnowledgeID,
})
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = fmt.Sprintf("failed to cleanup old resources: %v", err)
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
}
// Run manual processing (image resolution + chunking + embedding) synchronously within the worker
return s.triggerManualProcessing(ctx, kb, knowledge, payload.Content, true)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// ProcessDocument handles Asynq document processing tasks
func (s *knowledgeService) ProcessDocument(ctx context.Context, t *asynq.Task) error {
var payload types.DocumentProcessPayload
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
logger.Errorf(ctx, "failed to unmarshal document process task payload: %v", err)
return nil
}
ctx = logger.WithRequestID(ctx, payload.RequestId)
ctx = logger.WithField(ctx, "document_process", payload.KnowledgeID)
ctx = types.WithExecutionTenant(ctx, payload.TenantID)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if payload.Language != "" {
ctx = context.WithValue(ctx, types.LanguageContextKey, payload.Language)
}
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
// 获取任务重试信息,用于判断是否是最后一次重试。Lite 模式的执行器不提供
// asynq 的重试计数,改用它注入的 TaskRetryMetadata;否则每次都算最后一次。
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
retryCount, _ := asynq.GetRetryCount(ctx)
maxRetry, _ := asynq.GetMaxRetry(ctx)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if retried, limit, ok := types.TaskRetryMetadataFromContext(ctx); ok {
retryCount, maxRetry = retried, limit
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
isLastRetry := retryCount >= maxRetry
tenantInfo, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
if err != nil {
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
// Retry: acking leaves the row pending with no task behind it.
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Errorf(ctx, "failed to get tenant: %v", err)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return fmt.Errorf("get tenant %d: %w", payload.TenantID, err)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenantInfo)
logger.Infof(ctx, "Processing document task: knowledge_id=%s, file_path=%s, retry=%d/%d",
payload.KnowledgeID, payload.FilePath, retryCount, maxRetry)
// 幂等性检查:获取knowledge记录
knowledge, err := s.repo.GetKnowledgeByID(ctx, payload.TenantID, payload.KnowledgeID)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if errors.Is(err, repository.ErrKnowledgeNotFound) {
return nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
logger.Errorf(ctx, "failed to get knowledge: %v", err)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return fmt.Errorf("get knowledge %s: %w", payload.KnowledgeID, err)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
if knowledge == nil {
return nil
}
if err := validateProcessingKnowledge(knowledge,
payload.TenantID,
payload.KnowledgeBaseID,
payload.KnowledgeID); err != nil {
return err
}
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
// A reparse opened a newer attempt after this task was queued (or while
// an earlier delivery of it was running). Its row, chunks and counter
// belong to the new run; this task must not touch them.
if attemptSuperseded(ctx, s.tracker(), payload.KnowledgeID, payload.Attempt) {
logger.Infof(ctx, "Parse attempt %d superseded, skipping stale process task: %s",
payload.Attempt, payload.KnowledgeID)
return nil
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// 检查是否正在删除 / 已被用户取消 - 如果是则直接退出
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if knowledge.ParseStatus == types.ParseStatusDeleting {
logger.Infof(ctx, "Knowledge is being deleted, aborting processing: %s", payload.KnowledgeID)
return nil
}
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
if knowledge.ParseStatus == types.ParseStatusCancelled {
logger.Infof(ctx, "Knowledge cancelled by user, aborting processing: %s", payload.KnowledgeID)
return nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// 检查任务状态 - 幂等性处理
if knowledge.ParseStatus == types.ParseStatusCompleted {
logger.Infof(ctx, "Document already completed, skipping: %s", payload.KnowledgeID)
return nil // 幂等:已完成的任务直接返回
}
if knowledge.ParseStatus == types.ParseStatusFailed {
// 检查是否可恢复(例如:超时、临时错误等)
// 对于不可恢复的错误,直接返回
logger.Warnf(
ctx,
"Document processing previously failed: %s, error: %s",
payload.KnowledgeID,
knowledge.ErrorMessage,
)
// 这里可以根据错误类型判断是否可恢复,暂时允许重试
}
// 检查是否有部分处理(有chunks但状态不是completed)
if knowledge.ParseStatus != "completed" && knowledge.ParseStatus != "pending" &&
knowledge.ParseStatus != "processing" {
// 状态异常,记录日志但继续处理
logger.Warnf(ctx, "Unexpected parse status: %s for knowledge: %s", knowledge.ParseStatus, payload.KnowledgeID)
}
// 获取知识库信息
kb, err := s.kbService.GetKnowledgeBaseByID(ctx, payload.KnowledgeBaseID)
if err != nil {
logger.Errorf(ctx, "failed to get knowledge base: %v", err)
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = fmt.Sprintf("failed to get knowledge base: %v", err)
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
if kb == nil || kb.ID != payload.KnowledgeBaseID || kb.TenantID != payload.TenantID {
return fmt.Errorf("processing task KB owner changed: %w", asynq.SkipRetry)
}
ctx, err = access.WithKBTaskWrite(ctx, kb, payload.TenantID)
if err != nil {
return fmt.Errorf("invalid processing scope: %v: %w", err, asynq.SkipRetry)
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
processOverrides, _ := knowledge.ProcessOverrides()
eff := ResolveProcessConfig(kb, processOverrides)
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
// Re-check abort status right before flipping to "processing" — closes
// the race where the user cancels between the entry guard above and
// this write (otherwise the worker would overwrite cancelled→processing
// and downstream checkpoints would treat the run as live).
if aborted, status := s.isKnowledgeAborted(ctx, knowledge.TenantID, knowledge.ID); aborted {
logger.Infof(ctx, "Knowledge aborted (%s) before marking processing: %s", status, knowledge.ID)
return abortRetryErr(ctx, knowledge.ID, status)
feat: add knowledge parse cancellation with finalizing post-process state Lets users stop an in-flight document parse to free up LLM / worker resources without losing the chunks and index already written. The core insight is that the previous parse_status=completed flipped as soon as primary chunks landed, while the most expensive subtasks (graph extract = N LLM calls per chunk, plus summary, question generation) were still running in the background — so "completed" wasn't actually terminal from a resource standpoint. State machine pending -> processing -> finalizing -> completed | +-> cancelled (any of the three in-flight states) +-> failed +-> deleting `finalizing` is the new post-process fan-out window. parse_status only promotes to `completed` once pending_subtasks_count (a new column tracking summary + question + per-chunk graph extract) drains to zero via atomic FinalizeSubtask. Wiki ingest is intentionally excluded from the counter — it's a KB-scoped debounced batch and would otherwise pin parse_status in `finalizing` for the wiki batch window. Backend - New ParseStatusFinalizing + pending_subtasks_count column with migration 000056. - knowledgeRepository.SetFinalizing transitions processing -> finalizing conditionally so a racing cancel cannot be clobbered. - knowledgeRepository.FinalizeSubtask atomically decrements the counter and self-promotes the row to completed when it hits zero. - KnowledgePostProcess restructured to compute expected subtask count up front, flip to finalizing (or completed when no enrichment is enabled), and only then fan out subtasks. Subtask handlers (summary, question, graph extract) defer-decrement on terminal exit using the existing isFinalAsynqAttempt convention. - New POST /api/v1/knowledge/{id}/cancel-parse handler accepting pending / processing / finalizing. Marks the row cancelled, zeroes the counter, best-effort dequeues asynq tasks via a new TaskInspector abstraction (asynq-mode walks pending/scheduled/ retry queues; Lite-mode noop), and scrubs wiki ingest pending op. - SpanTracker.AbortAttempt flat-sweeps every still-running span for the attempt via a new repo.CancelAllOpenSpans helper so the trace viewer's striped bars all flip to cancelled, even leaf generations whose parent stage already EndSpan'd (multimodal fan-out pattern). knowledge_post_process closes its postSpan via SkipSpan on the cancel/deleting entry guard so a worker that opens a span AFTER the cancel sweep doesn't leak it. - Housekeeping and resetPendingTasks sweep finalizing rows identically to processing so a crash/restart can't strand them. - DeleteKnowledge/DeleteKnowledgeList proactively dequeue downstream tasks via the same TaskInspector path. - ChunkExtractService gets a cancel entry guard so the most expensive enrichment (graph extract) bails immediately when the parent knowledge is aborted. Frontend - New cancelKnowledgeParse API client + "Stop parsing" entry in both list view and card view more menus, gated on pending/processing/finalizing. - Polling predicate refactored to a shared isParseInFlight helper that recognises `finalizing` (previously the doc list silently stopped polling once parse_status flipped from processing). - Knowledge processing timeline: isPolling includes finalizing, new isHardTerminal short-circuits LIVE for cancelled/failed/ completed so stranded child spans cannot pin LIVE on. - DocumentListView.computeStatus distinguishes finalizing ("增强中") from completed and shows the previous "生成摘要中" copy when summary_status is still pending under finalizing. Added cancelled badge as well. - i18n: statusFinalizing / statusCancelled / cancelParse* keys across zh-CN, en-US, ko-KR, ru-RU. Docs / SDK - docs/api/knowledge.md: documents the new finalizing state, cancel-parse semantics, and which statuses accept cancel. - client (Go SDK): CancelKnowledgeParse with docstring listing the cancellable statuses.
2026-05-28 10:26:56 +00:00
}
if payload.FilePath != "" && knowledge.FilePath != "" && payload.FilePath != knowledge.FilePath {
logger.Infof(ctx, "Document source replaced, skipping stale process task: %s", payload.KnowledgeID)
return nil
}
if s.isKnowledgeSourceReplaced(ctx, knowledge) {
logger.Infof(ctx, "Document source replaced, skipping stale process task: %s", payload.KnowledgeID)
return nil
}
markKnowledgeProcessing(knowledge, time.Now())
if err := s.updateKnowledgeUnlessSourceReplaced(ctx, knowledge); err != nil {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Errorf(ctx, "failed to update knowledge status to processing: %v", err)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return fmt.Errorf("mark knowledge %s processing: %w", knowledge.ID, err)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
if s.isKnowledgeSourceReplaced(ctx, knowledge) {
logger.Infof(ctx, "Document source replaced, aborting after status update: %s", payload.KnowledgeID)
return nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
// Resolve the attempt for span tracking. The enqueue site sets
// payload.Attempt to a fresh number for the initial parse and to
// max+1 for each user-initiated reparse. Asynq retries within a
// single user action keep the same payload (so retries record
// onto the same attempt). For payloads predating this code we
// fall back to OpenAttempt.
attempt := payload.Attempt
if attempt <= 0 {
if root, n, err := s.tracker().OpenAttempt(ctx, knowledge.ID, payload.LangfuseTraceID); err == nil && root != nil {
attempt = n
}
}
ctx = withAttempt(ctx, attempt)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// 检查多模态配置(仅对文件导入)
if payload.FilePath != "" && !payload.EnableMultimodel && IsImageType(payload.FileType) {
logger.GetLogger(ctx).WithField("knowledge_id", knowledge.ID).
WithField("error", ErrImageNotParse).Errorf("processDocument image without enable multimodel")
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = ErrImageNotParse.Error()
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
// 检查音频ASR配置(仅对文件导入)
if payload.FilePath != "" && IsAudioType(payload.FileType) && !eff.ASRConfig.IsASREnabled() {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.GetLogger(ctx).WithField("knowledge_id", knowledge.ID).
Errorf("processDocument audio without ASR model configured")
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = "上传音频文件需要设置ASR语音识别模型"
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
// 视频文件不再支持入库解析
if payload.FilePath != "" && IsVideoType(payload.FileType) {
logger.GetLogger(ctx).WithField("knowledge_id", knowledge.ID).
Errorf("processDocument video not supported")
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = "暂不支持视频文件"
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
// New pipeline: convert -> store images -> chunk -> vectorize -> multimodal tasks
var convertResult *types.ReadResult
var chunks []types.ParsedChunk
if payload.FileURL != "" {
// file_url import: SSRF re-check (防 DNS 重绑定), download, persist, then delegate to convert()
if err := secutils.ValidateURLForSSRF(payload.FileURL); err != nil {
logger.Errorf(ctx, "File URL rejected for SSRF protection in ProcessDocument: %s, err: %v", payload.FileURL, err)
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = "File URL is not allowed for security reasons"
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
resolvedFileName := payload.FileName
resolvedFileType := payload.FileType
contentBytes, err := downloadFileFromURL(ctx, payload.FileURL, &resolvedFileName, &resolvedFileType)
if err != nil {
logger.Errorf(ctx, "Failed to download file from URL: %s, error: %v", payload.FileURL, err)
if isLastRetry {
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = err.Error()
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
}
return fmt.Errorf("failed to download file from URL: %w", err)
}
if resolvedFileType != "" && !isSupportedImportExtension(resolvedFileType) {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Errorf(ctx, "Unsupported file type resolved from file URL: %s", resolvedFileType)
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = fmt.Sprintf("unsupported file type: %s", resolvedFileType)
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
if resolvedFileName != "" && knowledge.FileName == "" {
knowledge.FileName = resolvedFileName
}
if resolvedFileType != "" && knowledge.FileType == "" {
knowledge.FileType = resolvedFileType
s.repo.UpdateKnowledge(ctx, knowledge)
}
fileSvc := s.resolveFileService(ctx, kb)
filePath, err := fileSvc.SaveBytes(ctx, contentBytes, payload.TenantID, resolvedFileName, true)
if err != nil {
if isLastRetry {
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = err.Error()
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
}
return fmt.Errorf("failed to save downloaded file: %w", err)
}
payload.FilePath = filePath
payload.FileName = resolvedFileName
payload.FileType = resolvedFileType
convertResult, err = s.convert(ctx, payload, kb, knowledge, eff, isLastRetry)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
return err
}
if convertResult == nil {
return nil
}
} else if payload.URL != "" {
// URL import
convertResult, err = s.convert(ctx, payload, kb, knowledge, eff, isLastRetry)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
return err
}
if convertResult == nil {
return nil
}
// Update knowledge title from extracted page title if not already set
if knowledge.Title == "" || knowledge.Title == payload.URL {
if extractedTitle := convertResult.Metadata["title"]; extractedTitle != "" {
knowledge.Title = extractedTitle
knowledge.UpdatedAt = time.Now()
if err := s.repo.UpdateKnowledge(ctx, knowledge); err != nil {
logger.Warnf(ctx, "Failed to update knowledge title from extracted page title: %v", err)
} else {
logger.Infof(ctx, "Updated knowledge title to extracted page title: %s", extractedTitle)
}
}
}
} else if len(payload.Passages) > 0 {
// Text passage import - direct chunking, no conversion needed
passageChunks := make([]types.ParsedChunk, 0, len(payload.Passages))
start, end := 0, 0
for i, p := range payload.Passages {
if p == "" {
continue
}
end += len([]rune(p))
passageChunks = append(passageChunks, types.ParsedChunk{
Content: p,
Seq: i,
Start: start,
End: end,
})
start = end
}
passageOpts := ProcessChunksOptions{
EnableQuestionGeneration: payload.EnableQuestionGeneration,
QuestionCount: payload.QuestionCount,
}
return s.processChunks(ctx, kb, knowledge, passageChunks, passageOpts)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
} else {
// File import
convertResult, err = s.convert(ctx, payload, kb, knowledge, eff, isLastRetry)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
return err
}
if convertResult == nil {
return nil
}
}
// Step 1.5: ASR transcription for audio files
if convertResult != nil && convertResult.IsAudio && len(convertResult.AudioData) > 0 {
if !eff.ASRConfig.IsASREnabled() {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
logger.Error(ctx, "Audio file detected but ASR is not configured")
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = "ASR model is not configured for audio transcription"
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
logger.Infof(ctx, "[ASR] Starting audio transcription for knowledge %s, audio size=%d bytes",
knowledge.ID, len(convertResult.AudioData))
asrModel, err := s.modelService.GetASRModel(ctx, eff.ASRConfig.ModelID)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
logger.Errorf(ctx, "[ASR] Failed to get ASR model: %v", err)
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = fmt.Sprintf("failed to get ASR model: %v", err)
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
return nil
}
// The knowledge base's language hint; the vendor declares where it
// goes, or that it takes none.
asrCtx := asr.WithLanguage(ctx, eff.ASRConfig.Language)
transcriptionResult, err := asrModel.Transcribe(asrCtx, convertResult.AudioData, knowledge.FileName)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
logger.Errorf(ctx, "[ASR] Transcription failed: %v", err)
if isLastRetry {
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = fmt.Sprintf("audio transcription failed: %v", err)
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
}
return fmt.Errorf("audio transcription failed: %w", err)
}
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
transcribedText, timeBlocks := transcriptWithSegments(transcriptionResult)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if transcribedText == "" {
logger.Warn(ctx, "[ASR] Transcription returned empty text")
transcribedText = "[No speech detected in audio file]"
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
timeBlocks = nil
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
logger.Infof(ctx, "[ASR] Transcription completed, text length=%d", len(transcribedText))
// Replace the audio placeholder with the transcribed text
convertResult.MarkdownContent = transcribedText
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
convertResult.SourceBlocks = timeBlocks
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
convertResult.IsAudio = false
convertResult.AudioData = nil
}
fix(chunking): 修复内联 HTML 表格与保护模式导致的超长 chunk (#3404) * fix(ocr): normalize inline HTML tables in VLM/OCR sanitizer The VLM/OCR path left raw HTML <table> blocks in the body: looksLikeHTML does not match markdown text with an embedded table, so ocrHTMLToMarkdown (which also lacked the table plugin) never ran. The chunker then split the raw markup mid-row, tripping the 7500-char hard limit and invalidating the heading layer for the whole document. Reuse docparser.NormalizeHTMLTables (already used by PaddleOCR-VL) instead: export it and call it unconditionally from sanitizeOCRText, since it is a safe no-op when no <table> is present. * fix(ocr): keep merged-cell HTML tables chunkable - Narrow span detection to values >1 so rowspan=1/colspan=1 tables still convert to GFM instead of falling back to raw HTML. - On the merged-cell fallback, split each <tr> onto its own line and pad the block with blank lines so the chunker can split by "\n" instead of force-cutting at the absolute max size. * fix(knowledge): normalize inline HTML tables for all parser engines before chunking Previously NormalizeHTMLTables was only wired into the paddleocr-vl converters, so tables emitted by other engines (notably MinerU) reached the chunker as raw single-line <table> blocks and were force-cut at the 7500 char hard limit. Add the normalization at the two central pre-chunk boundaries instead: - knowledge_process.go: after all converter/ASR/image markdown rewrites, before the chunker step (covers every parser engine) - knowledge_create.go: before building the splitter config for manual markdown Converters keep their existing calls (idempotent no-op). * fix(chunker): bound Markdown link/image protected patterns to one line The unbounded [^\]]* / [^)]+ character classes in the Markdown link and image protectedPatterns also matched newlines, so a stray '[' left behind by OCR (e.g. a full-width 【公章】 mis-read as half-width) could pair with a distant '](' and swallow whole paragraphs as one protected atomic span. buildUnitsWithProtection then treated the region as a single unit and mergeUnits could not split it, defeating chunking (observed 1 chunk of 1753 runes where 16 chunks were expected). Exclude newlines and bound the link text (<=200) / destination (<=500), matching CommonMark's rule that neither may span a blank line. Regression: protected_spans_test.go — same input now yields multiple chunks with max 125 runes (chunkSize=128) instead of a single 1753-rune chunk; well-formed single-line links/images stay protected. * fix(ocr): keep non-GFM HTML tables chunkable across all ingest paths Conversion fallbacks for <br>, nested lists, and one-column tables still left single-line HTML, so MinerU output could hit the same oversized-chunk bug. Split those rows, accept one-column GFM, skip fenced examples, and normalize before image resolution so cell images are not escaped. * style: wrap long lines and avoid shadowing max in table-chunk tests Pre-push lll/revive failed on the PR diff versus origin/main. --------- Co-authored-by: neoczr <neoczr@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-18 13:10:17 +00:00
// Normalize inline HTML tables from any parser engine (MinerU, builtin,
// markitdown, paddleocr-vl, ...) into GFM, or row-newline-separated HTML
// for merged / non-GFM tables, so the chunker can split them.
// Runs before image resolution so <img> inside HTML tables becomes
// markdown the resolver can persist, instead of rewriting data-URI
// <img> tags to `![...](...)` and then escaping them in a later
// HTML→GFM pass. Line endings are normalized first so injected row
// breaks are plain LF.
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
// Source blocks were recorded against the parser's markdown; keep it so
// they can be re-aimed after the rewrites below.
var parsedMarkdown string
var sourceBlocks []types.SourceBlock
if convertResult != nil {
parsedMarkdown = convertResult.MarkdownContent
sourceBlocks = convertResult.SourceBlocks
for i := range sourceBlocks {
sourceBlocks[i].Locator.SourceHash = knowledge.FileHash
}
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
}
fix(chunking): 修复内联 HTML 表格与保护模式导致的超长 chunk (#3404) * fix(ocr): normalize inline HTML tables in VLM/OCR sanitizer The VLM/OCR path left raw HTML <table> blocks in the body: looksLikeHTML does not match markdown text with an embedded table, so ocrHTMLToMarkdown (which also lacked the table plugin) never ran. The chunker then split the raw markup mid-row, tripping the 7500-char hard limit and invalidating the heading layer for the whole document. Reuse docparser.NormalizeHTMLTables (already used by PaddleOCR-VL) instead: export it and call it unconditionally from sanitizeOCRText, since it is a safe no-op when no <table> is present. * fix(ocr): keep merged-cell HTML tables chunkable - Narrow span detection to values >1 so rowspan=1/colspan=1 tables still convert to GFM instead of falling back to raw HTML. - On the merged-cell fallback, split each <tr> onto its own line and pad the block with blank lines so the chunker can split by "\n" instead of force-cutting at the absolute max size. * fix(knowledge): normalize inline HTML tables for all parser engines before chunking Previously NormalizeHTMLTables was only wired into the paddleocr-vl converters, so tables emitted by other engines (notably MinerU) reached the chunker as raw single-line <table> blocks and were force-cut at the 7500 char hard limit. Add the normalization at the two central pre-chunk boundaries instead: - knowledge_process.go: after all converter/ASR/image markdown rewrites, before the chunker step (covers every parser engine) - knowledge_create.go: before building the splitter config for manual markdown Converters keep their existing calls (idempotent no-op). * fix(chunker): bound Markdown link/image protected patterns to one line The unbounded [^\]]* / [^)]+ character classes in the Markdown link and image protectedPatterns also matched newlines, so a stray '[' left behind by OCR (e.g. a full-width 【公章】 mis-read as half-width) could pair with a distant '](' and swallow whole paragraphs as one protected atomic span. buildUnitsWithProtection then treated the region as a single unit and mergeUnits could not split it, defeating chunking (observed 1 chunk of 1753 runes where 16 chunks were expected). Exclude newlines and bound the link text (<=200) / destination (<=500), matching CommonMark's rule that neither may span a blank line. Regression: protected_spans_test.go — same input now yields multiple chunks with max 125 runes (chunkSize=128) instead of a single 1753-rune chunk; well-formed single-line links/images stay protected. * fix(ocr): keep non-GFM HTML tables chunkable across all ingest paths Conversion fallbacks for <br>, nested lists, and one-column tables still left single-line HTML, so MinerU output could hit the same oversized-chunk bug. Split those rows, accept one-column GFM, skip fenced examples, and normalize before image resolution so cell images are not escaped. * style: wrap long lines and avoid shadowing max in table-chunk tests Pre-push lll/revive failed on the PR diff versus origin/main. --------- Co-authored-by: neoczr <neoczr@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-18 13:10:17 +00:00
sanitizeReadResult(convertResult)
if convertResult != nil {
convertResult.MarkdownContent = chunker.NormalizeLineEndings(convertResult.MarkdownContent)
if convertResult.MarkdownContent != "" {
convertResult.MarkdownContent = docparser.NormalizeHTMLTables(convertResult.MarkdownContent)
}
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Step 2: Store images and update markdown references
var storedImages []docparser.StoredImage
if s.imageResolver != nil && convertResult != nil {
fileSvc := s.resolveFileService(ctx, kb)
tenantID, _ := ctx.Value(types.TenantIDContextKey).(uint64)
updatedMarkdown, images, resolveErr := s.imageResolver.ResolveAndStore(ctx, convertResult, fileSvc, tenantID)
if resolveErr != nil {
logger.Warnf(ctx, "Image resolution partially failed: %v", resolveErr)
}
if updatedMarkdown != "" {
convertResult.MarkdownContent = updatedMarkdown
}
storedImages = images
// Resolve remote http(s) images (e.g. markdown external URLs) → download + upload to storage.
// ResolveAndStore handles inline bytes and base64; ResolveRemoteImages handles http/https URLs.
updatedContent, remoteImages, remoteErr := s.imageResolver.ResolveRemoteImages(ctx, convertResult.MarkdownContent, fileSvc, tenantID)
if remoteErr != nil {
logger.Warnf(ctx, "Remote image resolution partially failed: %v", remoteErr)
}
if len(remoteImages) > 0 {
logger.Infof(ctx, "Resolved %d remote images for knowledge %s", len(remoteImages), knowledge.ID)
convertResult.MarkdownContent = updatedContent
storedImages = append(storedImages, remoteImages...)
}
logger.Infof(ctx, "Resolved %d total images for knowledge %s", len(storedImages), knowledge.ID)
}
fix(knowledge): bind extracted images to their document and unscope shared-KB parent lookups Org-shared KB viewers got 403 for extracted images on current main even though the retrieving chunk text carried the resource:// handle and the share grant was valid (#3342, second report after #3022/#3069). Root cause is a mismatch between ingestion and authorization: document parses store extracted images through SaveBytes, which registers the resource but never claims it, while both file proxies (ResolveKBFile and the message fallback via resourceAccessibleViaSharedKB) authorize through IsReferencedByKnowledgeBase — which accepts explicit resource_bindings rows only. The binding-only hardening landed without adding the missing bindings, so every extracted image became invisible cross-workspace. Ingestion: bindStoredImages claims each stored image for its knowledge (ResourceRelationExtractedImage), mirroring bindContentResources — best effort, same-workspace resources only. Wired into both the file-parse path (knowledge_process) and manual knowledge (triggerManualProcessing). Merge: resolveParentChunks fetched parents, grandparents, and image_info children with the caller's tenant, so shared-KB hits from the sharing workspace resolved none of them and lost parent context and image_info (the second defect in the #3342 audit). Those lookups now use the existing *Only unscoped variants, matching their shared-KB precedent. Historical documents parsed before this change still carry no bindings; a backfill is tracked as the follow-up slice. Verified end-to-end on a fresh stack: publishing a manual document with an embedded image now records kind=image plus an extracted_image binding alongside the content-derived attachment binding.
2026-09-21 01:57:17 +00:00
// Claim the stored images for this document before chunking proceeds:
// the file proxies authorize images through resource bindings, and an
// unbound extracted image renders broken for org-shared KB viewers (#3342).
s.bindStoredImages(ctx, knowledge, storedImages)
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
var sourceIndex *sourceloc.Index
if convertResult != nil {
sourceIndex = buildSourceIndex(parsedMarkdown, sourceBlocks, convertResult.MarkdownContent, storedImages)
}
fix(chunking): 修复内联 HTML 表格与保护模式导致的超长 chunk (#3404) * fix(ocr): normalize inline HTML tables in VLM/OCR sanitizer The VLM/OCR path left raw HTML <table> blocks in the body: looksLikeHTML does not match markdown text with an embedded table, so ocrHTMLToMarkdown (which also lacked the table plugin) never ran. The chunker then split the raw markup mid-row, tripping the 7500-char hard limit and invalidating the heading layer for the whole document. Reuse docparser.NormalizeHTMLTables (already used by PaddleOCR-VL) instead: export it and call it unconditionally from sanitizeOCRText, since it is a safe no-op when no <table> is present. * fix(ocr): keep merged-cell HTML tables chunkable - Narrow span detection to values >1 so rowspan=1/colspan=1 tables still convert to GFM instead of falling back to raw HTML. - On the merged-cell fallback, split each <tr> onto its own line and pad the block with blank lines so the chunker can split by "\n" instead of force-cutting at the absolute max size. * fix(knowledge): normalize inline HTML tables for all parser engines before chunking Previously NormalizeHTMLTables was only wired into the paddleocr-vl converters, so tables emitted by other engines (notably MinerU) reached the chunker as raw single-line <table> blocks and were force-cut at the 7500 char hard limit. Add the normalization at the two central pre-chunk boundaries instead: - knowledge_process.go: after all converter/ASR/image markdown rewrites, before the chunker step (covers every parser engine) - knowledge_create.go: before building the splitter config for manual markdown Converters keep their existing calls (idempotent no-op). * fix(chunker): bound Markdown link/image protected patterns to one line The unbounded [^\]]* / [^)]+ character classes in the Markdown link and image protectedPatterns also matched newlines, so a stray '[' left behind by OCR (e.g. a full-width 【公章】 mis-read as half-width) could pair with a distant '](' and swallow whole paragraphs as one protected atomic span. buildUnitsWithProtection then treated the region as a single unit and mergeUnits could not split it, defeating chunking (observed 1 chunk of 1753 runes where 16 chunks were expected). Exclude newlines and bound the link text (<=200) / destination (<=500), matching CommonMark's rule that neither may span a blank line. Regression: protected_spans_test.go — same input now yields multiple chunks with max 125 runes (chunkSize=128) instead of a single 1753-rune chunk; well-formed single-line links/images stay protected. * fix(ocr): keep non-GFM HTML tables chunkable across all ingest paths Conversion fallbacks for <br>, nested lists, and one-column tables still left single-line HTML, so MinerU output could hit the same oversized-chunk bug. Split those rows, accept one-column GFM, skip fenced examples, and normalize before image resolution so cell images are not escaped. * style: wrap long lines and avoid shadowing max in table-chunk tests Pre-push lll/revive failed on the PR diff versus origin/main. --------- Co-authored-by: neoczr <neoczr@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-18 13:10:17 +00:00
// Step 3: Split into chunks using Go chunker. Line endings and inline
// HTML tables were normalized before image resolution above.
chunkCfg := buildSplitterConfigFromChunking(eff.ChunkingConfig)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
processOpts := ProcessChunksOptions{
EnableQuestionGeneration: payload.EnableQuestionGeneration,
QuestionCount: payload.QuestionCount,
EnableMultimodel: payload.EnableMultimodel,
StoredImages: storedImages,
}
if convertResult != nil {
processOpts.Metadata = convertResult.Metadata
}
if eff.ChunkingConfig.EnableParentChild {
parentCfg, childCfg := buildParentChildConfigs(eff.ChunkingConfig, chunkCfg)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
pcResult := chunker.SplitParentChild(convertResult.MarkdownContent, parentCfg, childCfg)
chunks = make([]types.ParsedChunk, len(pcResult.Children))
for i, c := range pcResult.Children {
chunks[i] = types.ParsedChunk{
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
Content: c.Content,
ContextHeader: c.ContextHeader,
Seq: c.Seq,
Start: c.Start,
End: c.End,
ParentIndex: c.ParentIndex,
SourceLocators: sourceIndex.Locators(c.Start, c.End),
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
}
parentChunks := make([]types.ParsedParentChunk, len(pcResult.Parents))
for i, p := range pcResult.Parents {
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
parentChunks[i] = types.ParsedParentChunk{
Content: p.Content, Seq: p.Seq, Start: p.Start, End: p.End,
SourceLocators: sourceIndex.Locators(p.Start, p.End),
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
processOpts.ParentChunks = parentChunks
logger.Infof(ctx, "Split document into %d parent + %d child chunks for knowledge %s",
len(pcResult.Parents), len(pcResult.Children), knowledge.ID)
} else {
splitChunks := chunker.Split(convertResult.MarkdownContent, chunkCfg)
chunks = make([]types.ParsedChunk, len(splitChunks))
for i, c := range splitChunks {
chunks[i] = types.ParsedChunk{
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
Content: c.Content,
ContextHeader: c.ContextHeader,
Seq: c.Seq,
Start: c.Start,
End: c.End,
SourceLocators: sourceIndex.Locators(c.Start, c.End),
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
}
logger.Infof(ctx, "Split document into %d chunks for knowledge %s", len(chunks), knowledge.ID)
}
// Step 4: Process chunks (vectorize + index + enqueue async tasks)
return s.processChunks(ctx, kb, knowledge, chunks, processOpts)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// sanitizeReadResult protects every text field that can cross from a parser
// into the embedding, storage, or tracing layers. A parser may return a Go
// string containing arbitrary bytes even though the string type itself does
// not enforce UTF-8 validity.
func sanitizeReadResult(result *types.ReadResult) {
if result == nil {
return
}
result.MarkdownContent = common.CleanInvalidUTF8(result.MarkdownContent)
result.ImageDirPath = common.CleanInvalidUTF8(result.ImageDirPath)
result.Error = common.CleanInvalidUTF8(result.Error)
for key, value := range result.Metadata {
result.Metadata[key] = common.CleanInvalidUTF8(value)
}
for i := range result.ImageRefs {
result.ImageRefs[i].Filename = common.CleanInvalidUTF8(result.ImageRefs[i].Filename)
result.ImageRefs[i].OriginalRef = common.CleanInvalidUTF8(result.ImageRefs[i].OriginalRef)
result.ImageRefs[i].MimeType = common.CleanInvalidUTF8(result.ImageRefs[i].MimeType)
result.ImageRefs[i].StorageKey = common.CleanInvalidUTF8(result.ImageRefs[i].StorageKey)
}
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// convert handles both file and URL reading using a unified ReadRequest.
func (s *knowledgeService) convert(
ctx context.Context,
payload types.DocumentProcessPayload,
kb *types.KnowledgeBase,
knowledge *types.Knowledge,
eff types.EffectiveProcessConfig,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
isLastRetry bool,
) (*types.ReadResult, error) {
// Stage tracking: docreader. Mark the stage as running here so the
// timeline reflects "DocReader" the moment a worker picks the task
// up — before that, the stage stays "pending" from the initial
// upload. Failure/skip transitions are emitted at the specific
// failure points below; success is emitted at the bottom.
fix(knowledge): close root span on terminal state, enrich stage metadata The root span created by OpenAttempt was never closed: PostProcess only ended the postprocess stage, so the root row stayed at status=running forever even after parse_status flipped to completed/failed. The timeline rendered "进行中" indefinitely on the root, defeating the whole "is the document done" question the timeline is meant to answer. - SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg): closes the root row idempotently. Re-closing a terminal root no-ops so success / cascade-fail / dead-letter paths can fire without coordination. - PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess) on the success path. Async downstream work (summary/question/wiki/ graph) still records its own spans; their completion extends the trace's wall-clock end-time but doesn't reopen the root. - FailSpan auto-closes the root when a MAIN pipeline stage fails (docreader / chunking / embedding / multimodal / postprocess). Cascade-cancelled siblings stay closed-with-the-cascade as before. - Dead-letter callback (router/task.go) accepts the SpanTracker via DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a document-related task exhausts retries. The probe payload now extracts the Attempt field that Document/Manual/PostProcess payloads already thread through. Stage spans were also being recorded with nil input/output, leaving the new detail panel with timestamps only. Each Begin/End site now emits useful work metrics: - DocReader input: file_name, file_type, is_url, url output: text_length, images_found, is_audio, pages - Chunking input: chunks_planned output: chunks_written, total_text_chars - Embedding input: chunks_to_embed, model_id, dim output: vectors_written, storage_bytes - Multimodal input: image_count, enable_ocr, enable_caption - PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph i18n: add knowledgeStages.root ("Knowledge processing") so the UI can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
docInput := types.JSONMap{
"file_name": payload.FileName,
"file_type": payload.FileType,
"is_url": payload.URL != "",
}
if payload.URL != "" {
docInput["url"] = payload.URL
}
s.beginStage(ctx, knowledge.ID, types.StageDocReader, docInput)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
isURL := payload.URL != ""
fileType := payload.FileType
tenantOverrides := s.getParserEngineOverridesFromContext(ctx)
var uploadOverrides map[string]string
if processOverrides, err := knowledge.ProcessOverrides(); err == nil && processOverrides != nil {
uploadOverrides = processOverrides.ParserEngineOverrides
}
mergedOverrides := MergeParserEngineOverrides(tenantOverrides, uploadOverrides)
applyParserRuleOverrides(mergedOverrides, eff.ChunkingConfig, fileType)
if err := validateParserEngineOverrideURLs(mergedOverrides); err != nil {
logger.Errorf(ctx, "Parser endpoint rejected for SSRF protection: %v", err)
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = "Parser endpoint is not allowed for security reasons"
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
s.failStage(ctx, knowledge.ID, types.StageDocReader,
werrors.ErrCodeDocReaderParseFailed, knowledge.ErrorMessage, err)
return nil, nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if isURL {
if err := secutils.ValidateURLForSSRF(payload.URL); err != nil {
logger.Errorf(ctx, "URL rejected for SSRF protection: %s, err: %v", payload.URL, err)
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = "URL is not allowed for security reasons"
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
s.failStage(ctx, knowledge.ID, types.StageDocReader,
werrors.ErrCodeDocReaderParseFailed, "URL rejected for security reasons", err)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return nil, nil
}
}
parserEngine := eff.ChunkingConfig.ResolveParserEngine(fileType)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if isURL {
parserEngine = eff.ChunkingConfig.ResolveParserEngine("url")
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
logger.Infof(ctx, "[convert] kb=%s fileType=%s isURL=%v engine=%q rules=%+v",
kb.ID, fileType, isURL, parserEngine, eff.ChunkingConfig.ParserEngineRules)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
var reader interfaces.DocReader = s.resolveDocReader(ctx, parserEngine, fileType, isURL, mergedOverrides)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if reader == nil {
logger.Errorf(ctx, "[convert] no doc reader for kb=%s knowledge=%s fileType=%s engine=%q isURL=%v",
kb.ID, knowledge.ID, fileType, parserEngine, isURL)
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = "Document parsing service is not configured. Please use text/paragraph import or set DOCREADER_ADDR."
knowledge.UpdatedAt = time.Now()
s.repo.UpdateKnowledge(ctx, knowledge)
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
s.failStage(ctx, knowledge.ID, types.StageDocReader,
werrors.ErrCodeDocReaderUnavailable, knowledge.ErrorMessage, nil)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return nil, nil
}
req := &types.ReadRequest{
URL: payload.URL,
Title: knowledge.Title,
ParserEngine: parserEngine,
RequestID: payload.RequestId,
ParserEngineOverrides: mergedOverrides,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
if !isURL {
fileReader, err := s.resolveFileServiceForPath(ctx, kb, payload.FilePath).GetFile(ctx, payload.FilePath)
if err != nil {
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
s.failStage(ctx, knowledge.ID, types.StageDocReader,
werrors.ErrCodeDocReaderParseFailed, "failed to get file", err)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return s.failKnowledge(ctx, knowledge, isLastRetry, "failed to get file: %v", err)
}
defer fileReader.Close()
contentBytes, err := io.ReadAll(fileReader)
if err != nil {
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
s.failStage(ctx, knowledge.ID, types.StageDocReader,
werrors.ErrCodeDocReaderParseFailed, "failed to read file", err)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return s.failKnowledge(ctx, knowledge, isLastRetry, "failed to read file: %v", err)
}
req.FileContent = contentBytes
req.FileName = payload.FileName
req.FileType = fileType
}
fix(knowledge): prevent documents from getting stuck in "processing" Several failure modes left Knowledge.parse_status pinned at "processing" forever, with no signal to users beyond a permanent spinner. This commit addresses the root causes and adds a safety net. - Asynq worker pool: explicit Concurrency (default 16, env-tunable via WEKNORA_ASYNQ_CONCURRENCY) so batch uploads don't queue behind a CPU-count-sized worker pool. Redis op timeouts raised to 500ms/1000ms (WEKNORA_REDIS_OP_TIMEOUT_MS) to absorb bursty multimodal counter ops. - DocReader RPC: cap each call with WEKNORA_DOCREADER_CALL_TIMEOUT (default 30m). Without this, a hung docreader pinned a worker for the full DocumentProcessTimeout window. - ImageMultimodal: finalize-on-last-attempt semantics. A permanently failing single image no longer strands the parent — the asynq retry is allowed to run, but on the final attempt we count the image regardless of outcome. Redis DECR errors fall back to enqueuing the post-process task instead of returning silently. - Dead-letter callback: when DocumentProcess / KnowledgePostProcess / ManualProcess exhausts retries, immediately mark the corresponding Knowledge as failed with the last error. This surfaces the failure in the UI without waiting for the housekeeping sweep. - HousekeepingService: 5-minute cron that flips knowledge rows stuck in "processing" past DocumentProcessTimeout + 10m to failed, plus summary rows stuck > 1h. Catches anything the other safety nets miss (worker SIGKILL mid-handler, etc.). Disable with WEKNORA_HOUSEKEEPING_ENABLED=false. - Distributed startup recovery: previously the post-restart sweep was skipped whenever REDIS_ADDR was set, even though Asynq does not reschedule the task that was actively running on the dead instance. Now the sweep runs in distributed mode too, but only against rows older than 30 minutes to avoid racing peer instances.
2026-05-27 05:17:08 +00:00
result, err := s.callDocReaderWithTimeout(ctx, reader, req)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if err != nil {
code, message := docReaderFailure(err)
logger.Errorf(ctx, "[convert] DocReader failed knowledge=%s code=%s: %v", knowledge.ID, code, err)
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
s.failStage(ctx, knowledge.ID, types.StageDocReader,
code, message, err)
return s.failKnowledge(ctx, knowledge, isLastRetry, "%s", message)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
sanitizeReadResult(result)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if result.Error != "" {
logger.Errorf(ctx, "[convert] parser returned error kb=%s knowledge=%s file=%q type=%s engine=%q: %s",
kb.ID, knowledge.ID, req.FileName, fileType, parserEngine, result.Error)
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = result.Error
knowledge.UpdatedAt = time.Now()
if err := s.updateKnowledgeUnlessSourceReplaced(ctx, knowledge); err != nil {
logger.Errorf(ctx, "failed to persist parser error for %s: %v", knowledge.ID, err)
}
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
s.failStage(ctx, knowledge.ID, types.StageDocReader,
werrors.ErrCodeDocReaderParseFailed, result.Error, nil)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return nil, nil
}
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
if !isURL {
attachStructureBlocks(ctx, fileType, req.FileContent, result)
}
fix(knowledge): close root span on terminal state, enrich stage metadata The root span created by OpenAttempt was never closed: PostProcess only ended the postprocess stage, so the root row stayed at status=running forever even after parse_status flipped to completed/failed. The timeline rendered "进行中" indefinitely on the root, defeating the whole "is the document done" question the timeline is meant to answer. - SpanTracker.FinalizeAttempt(kid, attempt, status, output, code, msg): closes the root row idempotently. Re-closing a terminal root no-ops so success / cascade-fail / dead-letter paths can fire without coordination. - PostProcess.Handle calls FinalizeAttempt(done) after EndSpan(postprocess) on the success path. Async downstream work (summary/question/wiki/ graph) still records its own spans; their completion extends the trace's wall-clock end-time but doesn't reopen the root. - FailSpan auto-closes the root when a MAIN pipeline stage fails (docreader / chunking / embedding / multimodal / postprocess). Cascade-cancelled siblings stay closed-with-the-cascade as before. - Dead-letter callback (router/task.go) accepts the SpanTracker via DI and calls FinalizeAttempt(failed, TASK_TIMEOUT) when a document-related task exhausts retries. The probe payload now extracts the Attempt field that Document/Manual/PostProcess payloads already thread through. Stage spans were also being recorded with nil input/output, leaving the new detail panel with timestamps only. Each Begin/End site now emits useful work metrics: - DocReader input: file_name, file_type, is_url, url output: text_length, images_found, is_audio, pages - Chunking input: chunks_planned output: chunks_written, total_text_chars - Embedding input: chunks_to_embed, model_id, dim output: vectors_written, storage_bytes - Multimodal input: image_count, enable_ocr, enable_caption - PostProcess output: chunks_total, enqueued_summary, _question, _wiki, _graph i18n: add knowledgeStages.root ("Knowledge processing") so the UI can render a localized name instead of the raw span identifier.
2026-05-27 08:54:09 +00:00
docOutput := types.JSONMap{
"text_length": len(result.MarkdownContent),
"images_found": len(result.ImageRefs),
"is_audio": result.IsAudio,
}
if pages := result.Metadata["pages"]; pages != "" {
docOutput["pages"] = pages
}
s.endStage(ctx, knowledge.ID, types.StageDocReader, docOutput)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
return result, nil
}
fix(knowledge): prevent documents from getting stuck in "processing" Several failure modes left Knowledge.parse_status pinned at "processing" forever, with no signal to users beyond a permanent spinner. This commit addresses the root causes and adds a safety net. - Asynq worker pool: explicit Concurrency (default 16, env-tunable via WEKNORA_ASYNQ_CONCURRENCY) so batch uploads don't queue behind a CPU-count-sized worker pool. Redis op timeouts raised to 500ms/1000ms (WEKNORA_REDIS_OP_TIMEOUT_MS) to absorb bursty multimodal counter ops. - DocReader RPC: cap each call with WEKNORA_DOCREADER_CALL_TIMEOUT (default 30m). Without this, a hung docreader pinned a worker for the full DocumentProcessTimeout window. - ImageMultimodal: finalize-on-last-attempt semantics. A permanently failing single image no longer strands the parent — the asynq retry is allowed to run, but on the final attempt we count the image regardless of outcome. Redis DECR errors fall back to enqueuing the post-process task instead of returning silently. - Dead-letter callback: when DocumentProcess / KnowledgePostProcess / ManualProcess exhausts retries, immediately mark the corresponding Knowledge as failed with the last error. This surfaces the failure in the UI without waiting for the housekeeping sweep. - HousekeepingService: 5-minute cron that flips knowledge rows stuck in "processing" past DocumentProcessTimeout + 10m to failed, plus summary rows stuck > 1h. Catches anything the other safety nets miss (worker SIGKILL mid-handler, etc.). Disable with WEKNORA_HOUSEKEEPING_ENABLED=false. - Distributed startup recovery: previously the post-restart sweep was skipped whenever REDIS_ADDR was set, even though Asynq does not reschedule the task that was actively running on the dead instance. Now the sweep runs in distributed mode too, but only against rows older than 30 minutes to avoid racing peer instances.
2026-05-27 05:17:08 +00:00
// callDocReaderWithTimeout wraps the DocReader RPC in a child context whose
// deadline is min(parent_deadline, DocReaderCallTimeout). Without this cap,
// a hung docreader (network partition, GC pause, OCR runaway) silently
// burns the whole DocumentProcessTimeout budget and pins a worker for hours
// — the #1 cause of "knowledge stuck in processing" reports.
//
// On timeout we annotate the error so retries / dead-letter consumers can
// distinguish "docreader was slow" from "docreader returned an error".
func (s *knowledgeService) callDocReaderWithTimeout(
ctx context.Context, reader interfaces.DocReader, req *types.ReadRequest,
) (*types.ReadResult, error) {
timeout := 30 * time.Minute
if s.config != nil && s.config.KnowledgeBase != nil && s.config.KnowledgeBase.DocReaderCallTimeout > 0 {
timeout = s.config.KnowledgeBase.DocReaderCallTimeout
}
callCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
start := time.Now()
result, err := reader.Read(callCtx, req)
elapsed := time.Since(start)
if err != nil {
// Promote DeadlineExceeded into a clearer message; retain underlying
// error via %w so errors.Is(callCtx.Err(), context.DeadlineExceeded)
// still works for upstream classification.
if errors.Is(callCtx.Err(), context.DeadlineExceeded) && !errors.Is(ctx.Err(), context.DeadlineExceeded) {
logger.Errorf(ctx, "[convert] docreader call timed out after %s (limit %s) for %q",
elapsed, timeout, req.FileName)
return nil, fmt.Errorf("docreader call timeout after %s: %w", timeout, err)
}
return nil, err
}
logger.Infof(ctx, "[convert] docreader call ok in %s for %q", elapsed, req.FileName)
return result, nil
}
// isLikelyRateLimitError performs a fuzzy classification of an error as a
// rate-limit / quota / backpressure failure. We only need a hint — the
// caller maps to one of two error_codes so the UI can offer "retry later"
// vs. "fix configuration" advice. False positives are harmless (the
// detail is preserved in error_detail anyway).
func isLikelyRateLimitError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
for _, needle := range []string{"rate limit", "ratelimit", "429", "too many requests", "quota"} {
if strings.Contains(msg, needle) {
return true
}
}
return false
}
// resolveDocReader picks the reader for one parse request. The engine catalog
// itself lives in the docparser registry; this only supplies the dependencies
// the service owns. Returns nil when the chosen engine cannot run — an
// unconfigured cloud engine, a disconnected docreader — after logging why.
func (s *knowledgeService) resolveDocReader(
ctx context.Context, engine, fileType string, isURL bool, overrides map[string]string,
) interfaces.DocReader {
reader, err := docparser.NewReader(ctx, engine, fileType, isURL, docparser.ReaderDeps{
Overrides: overrides,
Remote: s.documentReader,
WeKnoraCloudCredentials: s.tenantService.GetWeKnoraCloudCredentials,
})
if err != nil {
logger.Warnf(ctx, "[resolveDocReader] engine=%q fileType=%q unusable: %v", engine, fileType, err)
return nil
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
return reader
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// failKnowledge marks knowledge as failed (only on last retry) and returns an error.
func (s *knowledgeService) failKnowledge(
ctx context.Context,
knowledge *types.Knowledge,
isLastRetry bool,
format string,
args ...interface{},
) (*types.ReadResult, error) {
errMsg := fmt.Sprintf(format, args...)
if s.isKnowledgeSourceReplaced(ctx, knowledge) {
logger.Infof(ctx, "Skip failing knowledge %s: source file was replaced", knowledge.ID)
return nil, nil
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if isLastRetry {
knowledge.ParseStatus = "failed"
knowledge.ErrorMessage = errMsg
knowledge.UpdatedAt = time.Now()
if err := s.updateKnowledgeUnlessSourceReplaced(ctx, knowledge); err != nil {
logger.Errorf(ctx, "failed to persist knowledge failure for %s: %v", knowledge.ID, err)
}
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
return nil, fmt.Errorf(format, args...)
}
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
// enqueueImageMultimodalTasks enqueues asynq tasks for multimodal image
// processing. It returns an error only when no path is left to move the
// knowledge out of "processing" (see releaseUnownedMultimodalSlots).
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
func (s *knowledgeService) enqueueImageMultimodalTasks(
ctx context.Context,
knowledge *types.Knowledge,
kb *types.KnowledgeBase,
images []docparser.StoredImage,
chunks []types.ParsedChunk,
metadata map[string]string,
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
) error {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if s.task == nil || len(images) == 0 {
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return nil
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
attempt := attemptFromCtx(ctx)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
lang := types.LanguageFromContextOrDefault(ctx)
redisKey := multimodalPendingKey(knowledge.ID)
// The counter has to be seeded BEFORE the first task is enqueued: an image
// task that finishes early would otherwise decrement a key we are about to
// overwrite, and its slot would be counted twice. The cost of seeding
// first is that a slot whose task never reaches the queue has no owner to
// drain it — releaseUnownedMultimodalSlots settles that after the fan-out.
counterSeeded := false
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if s.redisClient != nil {
if err := s.redisClient.Set(ctx, redisKey, len(images), 24*time.Hour).Err(); err != nil {
logger.Warnf(ctx, "Failed to set multimodal pending count for %s: %v", knowledge.ID, err)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
} else {
counterSeeded = true
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
} else {
liteMultimodalSet(redisKey, int64(len(images)))
counterSeeded = true
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
feat(gallery): add an image gallery tab with schema-driven filters (#3694) * feat(image): observe image attributes and let the policy decide OCR Describe each image with the VLM as before, but ask it to also observe two attributes about the image in the same round — how much body text it carries (contain.text) and whether it presents data visually (contain.data_visual) — then let a small pure function decide whether that image is worth a second, separate OCR round. Per-class OCR was the first shape of this idea; a class (chart / photo / logo) is only an indirect proxy for 'is there text worth reading here', and the class table has to grow whenever a new kind of image shows up. The decision actually needs the observed attributes, so it reads them directly, and the attribute set is a backend registry row rather than a new class. The observation and the caption share one VLM call; OCR stays a separate call (prompt isolation, see #3291). An attribute the model does not answer for is left absent rather than filled with a conservative default, so the trace never claims an observation that did not happen, and an incomplete observation falls back to the on_unobserved policy (OCR still runs). The registry also carries the panel's display text, so a new attribute needs no frontend change. Off by default: image_attrs_enabled=false keeps today's behaviour (one caption and one OCR per image). KB config: image_processing_config.image_attrs_enabled / image_actions; per-upload override via process_config. Registry: GET /api/v1/image-attrs/schema. * feat(gallery): add image gallery tab with schema-driven filters Adds a 4th knowledge-base tab parallel to Documents/Wiki/Graph that browses every image asset in a KB. Backend: - GET /api/v1/knowledge-bases/:id/images lists image assets projected from chunks.image_info, with keyword (caption/OCR), multi-value attribute (attr_<name>=<value>), is_enabled and sort filters applied in memory, plus pagination. - Resolves the source knowledge item title (SourceName) via a batched GetKnowledgeBatch so the viewer can show a human-readable source. Frontend: - ImageGallery.vue: thumbnail grid + search/sort + schema-driven filter panel (from GET /image-attrs/schema) + single-image viewer with prev/next, attributes/caption/OCR/source. - Wired as the gallery tab in KnowledgeBase.vue; i18n keys in all 5 locales. * feat(gallery): drive filters/search/sort from a configurable attribute contract The gallery UI is no longer hardcoded: it renders from a self-describing contract served by GET /knowledge-bases/:id/gallery-config (live attribute sources, every attribute's definition with usage flags merged across the config tiers, and the caller's search activation state). - Attribute sources form an open registry (types.RegisterGalleryAttrSource); a builtin source models caption/ocr_text/timestamps/enabled so the gallery has zero special cases. - Usage resolution: user > KB > system > source, field by field; the system tier lives in system_settings (gallery.policy, JSON, no rebuild), the KB tier slot is wired in the engine but not stored yet. - Search activation is the user's own record: mode (all|custom) plus per-field on/off in users.preferences.gallery; source declarations never set defaults (unrecorded = off in custom mode). - image_info is read through a gallery-local struct, removing the compile dependency on the attribute-pipeline types; the gallery builds and runs with or without that feature deployed. - ListImages validates search_in / sort_by / attr_filters against the contract; ineligible fields are dropped, not served. * fix(frontend): inline the shared graph-drawer stylesheet (@import instead of <style src>) plugin-vue 6.0.6 keys unscoped src-style descriptors by the imported file path, so AgentStreamDisplay.vue and WikiBrowser.vue — both importing components/css/wiki-graph-drawer.less — overwrite each other during the build and the second one crashes with "reading 'scoped'". Adding the gallery changed the module order enough to make the collision hit every time. Inlining the same stylesheet keeps the emitted CSS identical and removes the shared descriptor key. * feat(gallery): render attributes from short labels with descriptions in tooltips A source could only say one thing about a value, so the filter panel had to put a full sentence inside a checkbox. Attributes and their values now carry two pieces of text: a short label for the space-constrained controls (checkbox, search field, sort option) and a description for wherever there is room (tooltip, detail panel). The contract's value list becomes an array of {value, label, description}, and the display helpers resolve each field separately: the gallery stamps the short name on a control and moves the sentence into a tooltip. Translation overlays are looked up per field, so a source that ships no gallery-specific text still picks up the attribute pipeline's own wording. * fix(gallery): let locale text win over the contract's wording The filter panel read the backend's own label before asking the locale, so a translated value never got a chance: the contract ships its own default-language wording, and it shadowed the overlay for every locale. Built keys were also off by a segment — imageAttr.<name> has to be imageAttr.<name>.label, and the gallery's own keys live under knowledgeEditor.wikiBrowser.gallery.attr — so builtin and system attributes fell through to English on a Chinese UI. * feat(gallery): top bar layout, pinned panels and per-value verdicts The toolbar moves onto its own row above the grid, so the controls no longer eat into the space the images are there for: search box, the two scope switches, sort field and direction, and the result count all sit in one flex row. The settings behind them are no longer inline either — each opens as a popover under its control and can be pinned to a right-hand rail, where the two panels take turns as tabs instead of both claiming width at once. Filtering gains a third state per attribute value. Where a value could only be picked or not picked, it can now be "off" (hide those images), "on" (show them whatever else says) or neutral (leave them alone), which is what lets one attribute's rules talk about an image another attribute tried to hide without the pair of them cancelling each other out: a forced display outranks a forced hide, and anything no rule speaks about stays visible. The switch that used to only exist inside the panel now has a toolbar home as well. "筛选:全显示" genuinely drops the attribute constraint instead of imposing it against a panel the user cannot see. Filtering used to empty the list the moment it was switched on. Any image whose attribute was never observed — every image ingested before the attribute pipeline existed — read as a mismatch for every filter, which is not narrowing a list but losing it. Absence now stays silence: an attribute no image carries places no constraint on it, until the pipeline catches up and fills the value in. Co-authored-by: WorkBuddy * feat(gallery): expose the image attribute pipeline as a gallery source The gallery's contract resolved to a single source, so the filter panel could only offer "Enabled" while the attributes the observe-and-describe pipeline fills in — contain.text, contain.data_visual — never reached the UI. The registry is a gallery attribute source like any other: every attribute it declares is offered to the gallery, filterable by default, with the config tiers able to override the usage flags at runtime. The registration lives in the attribute pipeline's own commit; this branch carried an earlier, squapshot of that work which predated the split of an attribute value into a short label and a description, so the registry's value shape and this file have been brought in line with it. Both PRs now hold byte-identical copies of the source hook, which is what lets either one land first and the other merge cleanly afterwards. Co-authored-by: WorkBuddy * fix(gallery): viewer race, pin icon, panel anchoring and scope wording Opening the viewer rendered the img element with the previous or empty source while the proxy fetch was still producing a blob, and the error that empty source fired locked the viewer in its failure state even after the real image arrived. The resolved source now lands before the flag is consulted, and a token keeps a slow fetch of one image from overwriting a faster one that navigated past it. The pin button drew nothing: TDesign has no "pushpin" glyph, so the button rendered as an empty shell. It now uses pin / pin-filled, keeps its place beside the tab bar, and a pinned rail assigns its columns explicitly — the panel precedes the main section in the DOM, so leaving the grid to source order handed the wide column to the panel and squeezed the images into the rail. The floating panel no longer appears at a hardcoded offset: it anchors just below the arrow that summoned it, the arrow flips up while its panel is out, a second press retracts, and any click elsewhere in the toolbar closes it. When a rail is pinned the arrows turn to the requested tab instead of spawning a second surface. The scope words (全部 / 全显示 / 自定义) become plain status text rather than a second dropdown — they name the current mode, and only the arrow beside them opens the panel that changes it. Co-authored-by: WorkBuddy * fix(web): align the OCR-on-unobserved switch with the other setting rows The switch sat bare inside its setting-row while every other switch on the page is wrapped in setting-control, which is what reserves the right column and centers the control vertically. With the row laid out from the top, the bare switch hugged the row's upper edge and crowded the description text — visibly out of place next to its neighbors. Wrapping it in setting-control gives it the same right-aligned, centered slot as the rest. Co-authored-by: WorkBuddy * fix(web): move the OCR-on-unobserved row out of the vertical schema row The row lived inside setting-row-vertical, whose descendant rule stretches every setting-info and setting-control beneath it to 100% width. Two full-width flex children side by side cannot fit, so the control overflowed the container and the switch landed past the right edge — visibly further out than the switch on the row above. The row and its note now sit beside the vertical block instead of inside it, under their own condition, so the switch shares the ordinary row layout and its right edge lines up with the "image attribute observation" switch above. Co-authored-by: WorkBuddy * fix(gallery): applying a verdict now activates the filter scope Setting an off/on verdict while the panel's master switch was off silently ignored it: buildParams only attaches attr_rules in custom scope, and setVerdict never flipped the scope. A verdict the user just expressed now switches the scope to custom; clearing the last meaningful verdict returns to all, since custom with no rules constrains nothing. * fix(gallery): search checkboxes stay visible and idle panels read as dimmed The search panel hid its field checkboxes while the master switch was on, so the only way to reach them was to flip the switch first. They now sit next to the switch like the filter panel's verdicts do: dimmed in all-field mode (where they carry no weight) yet clickable, and touching one drops the mode to custom. The filter panel's verdict rows dim the same way while the filter switch is off. * fix(gallery): bulk verdict row, neutral default mark, panel polish The clear-filters button never matched what the panel is for, so it is now a bulk verdict row: one set of -/off/on buttons that applies the chosen position to every value of every value-typed attribute, with the default mark turned into a language-neutral dash. The panel head drops its second divider (the tab bar already draws one) and the tabs follow the toolbar's order: search left, filter right. * fix(gallery): drop the all-fields caption and center the order arrow The caption above the search checkboxes showed and hid with the master switch, shoving the checkboxes down on every flip; it said nothing the dimmed state doesn't, so it is gone. The order button's arrow is an inline svg, which sits on the text baseline and reads as riding high; it now centers against the label. * fix(gallery): center the order arrow for real vertical-align never applied: the icon is a flex item inside the button's inline-flex text wrapper, and the wrapper's default stretch pins the explicitly-sized 16px icon to the top of the 22px line box. align-items: center on the wrapper is what actually centers it. * fix(gallery): shorten panel tab labels in en and ru The two-word labels overflowed the 300px panel and forced the tab bar into scroll arrows; single-word labels fit in every locale that was affected. * docs: drop the image pipeline rewrite from this branch The rewritten 'Go 侧接手后' paragraph belongs to the image attribute observation work (#3635), which this branch carries as a prerequisite and which already documents the caption_ocr / observation_driven split. Keeping a competing rewrite of the same paragraph on the gallery branch makes it collide with upstream, which extended that paragraph with the custom_instructions and inline HTML table notes. Restoring the shared wording keeps the gallery branch free of this file so upstream's edits merge cleanly. * style: gofmt the gallery attribute types Struct field tags in the resolved gallery config were one column narrow, so gofmt rebroke the alignment block. Whitespace only. * style(gallery): use design tokens in the gallery styles The style guard ratchet fails on any new violation. ImageGallery.vue shipped with 47 TDesign token fallbacks, 21 literal font sizes, 4 literal radii and a 0.15s transition; all of them now read the --app-* / --td-* tokens, which is what the guard asks for and what dark mode depends on. * lint(gallery): fix the golangci-lint findings in the gallery code lll: the three over-long swagger @Param lines and one registry row were shortened. ineffassign: ctx was assigned before the access check and then reassigned, so the first value was dead; it is now declared once, after the check. errcheck: the three unchecked c.Error calls in ListImages. revive: the AttrSpec / AttrValue doc comment block was attached to the wrong type and split into one block each. staticcheck S1016: the gallery registration converts the registry value instead of restating its fields. * lint(gallery): wrap the image query select and check the last c.Error * style: reformat the wrapped image select in chunk.go * fix(gallery): address review findings on ordering, KB switch and blob lifetime - sortImageAssets: swap operands for desc instead of negating, keeping a strict weak ordering so ties page stably - ImageGallery: reload on knowledgeBaseId change, drop stale list responses, fetch thumbnails in parallel with one cached blob per URL, revoke blobs on unmount, default sort to builtin:created_at - KnowledgeBase: non-wiki KBs with a stale wiki/graph tab fall back to documents again - handler: move ListImages godoc out of ListKnowledgeFolders' block and document attr_filters / attr_rules - DecideOCR: a payload with no OCR conditions uses the built-in policy instead of silently skipping OCR * docs(parsing): describe the caption_ocr and observation_driven image pipelines Carried over from #3635, which this PR supersedes. * fix(gallery): load local:// and other storage handles through the KB file proxy The gallery's own scheme check only caught resource://, provider:// and storage://, so local:// (the default storage), minio://, cos:// and s3:// images went straight into <img src> and never rendered. Resolve through isProviderFileURL, the scheme list chat and wiki already use, and lock the routing with a test. * fix(kb-editor): keep API-customised OCR conditions on save and upload The KB editor always wrote the registry default into image_actions.ocr.on, so any unrelated edit replaced a knowledge base's custom OCR conditions with the default table; the upload dialog did the same for the per-document override. Keep a stored custom list and fall back to the registry default only when there is none, and show the conditions actually in effect instead of the default table in both panels. * perf(gallery): de-duplicate, filter, sort and page images in SQL Every gallery request used to read every image-bearing chunk of the KB, OCR text included, decode it in Go and page in memory. A single query now expands the image_info arrays, keeps one row per image URL, applies the keyword / attribute / verdict / enabled filters and the sort, and returns only the page with the filtered total. The expansion carries narrow scalars only; filters and JSON sort keys are evaluated on the winning entry of each image, and the page's JSON is read back for its rows alone. Postgres runs the query with JIT off, since the fixed 100-rows-per-call estimate of jsonb_array_elements otherwise prices it ~100x high and compilation dominates. On 20k images with 2 KB of OCR text each (40k chunks), a page drops from ~750 ms to ~100-200 ms on postgres and ~200 ms on sqlite; keyword search over OCR text stays a full scan (~400-600 ms) until the text is indexed. The filter semantics are pinned against both databases. * perf(gallery): serve the gallery from a trigger-maintained chunk_images table Reading images out of chunks.image_info meant parsing every image chunk of the knowledge base on each request, so a page still cost time in proportion to the KB. chunk_images (versioned/000113, sqlite/000032) keeps one row per image_info entry with caption, OCR text and attributes as columns; triggers on chunks keep it in step with every write path, and the migration backfills existing chunks. Copies of one image stay separate rows and the query lists the copy on the most recently updated chunk through an indexed anti-join, so writes decide nothing and concurrent writers need no locking. On postgres, caption and OCR text get pg_trgm indexes when the extension is available. On 20k images with 2 KB of OCR text each (40k chunks): postgres first page 10 ms, page 500 41 ms, keyword 2 ms, filters 23 ms sqlite first page 3 ms, page 500 39 ms, keyword 147 ms, filters 51 ms down from ~100-600 ms. Writing those 40k image chunks costs 7.0 s instead of 1.3 s on postgres (1.9 s instead of 1.0 s on sqlite), mostly the trigram indexes; status and enable-flag updates patch rows in place. --------- Co-authored-by: tayadwx <tayadwx@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-25 04:33:59 +00:00
// Resolve the image pipeline settings once for the whole fan-out: the image
// action policy and the pipeline switch travel with each task so the worker
// needs no second config lookup, and so a task keeps the policy it was
// enqueued with even if the knowledge base is reconfigured meanwhile.
overrides, _ := knowledge.ProcessOverrides()
eff := ResolveProcessConfig(kb, overrides)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
enqueued := 0
refactor(knowledge): replace flat stage table with langfuse-style span tree Addresses review feedback that the PR② design had four shortcomings: 1. The pipeline is a DAG, not a sequence — Embedding and Multimodal are independent of each other, both downstream of Chunking, both upstream of PostProcess. The flat (knowledge_id, stage) table couldn't represent that, so a Chunking failure left dependents stranded as "pending" forever instead of being marked as impossible-to-run. 2. No history across attempts. A reparse erased the previous run's status before the new run started, leaving operators with no way to investigate "why did this fail twice?". 3. Stages had only status + duration. Operators want to know how big the work was — pages parsed, chunks created, tokens embedded, VLM calls made — to distinguish "slow because the file is huge" from "slow because the docreader is wedged". 4. Multimodal fans out N image tasks; Embedding fans out M batches; PostProcess fans out into Summary/Question/Wiki/Graph. Each unit is interesting on its own (Langfuse already captures this for LLM calls). The flat model couldn't express it. The redesign mirrors Langfuse's trace/span/generation hierarchy: * Migration 000053 supersedes 000052: knowledge_processing_spans table with (knowledge_id, attempt, span_id) primary key, plus parent_span_id, kind ∈ {root, stage, subspan, generation}, status ∈ {pending,running,done,failed,skipped,cancelled}, and JSONB input/output/metadata fields. * SpanTracker (replacing StageTracker) exposes OpenAttempt / BeginStage / BeginSubSpan / EndSpan / FailSpan / SkipSpan / LookupStage. Cross-process workers (image_multimodal) get the parent's attempt + span via payload + LookupStage so subspans attach correctly. * StageDependencies declares the DAG; FailSpan now cascades — descendants of the failed span and dependent stages are flipped to "cancelled" with a UPSTREAM_FAILED code. The UI sees a clear blast radius instead of orphan spinners. * Reparse now calls OpenAttempt up front so the timeline reflects "new attempt, all pending" instead of letting the previous run's status linger until the worker picks up the task. * Image_multimodal records each image as a generation subspan with its own success/failure on the parent attempt's multimodal stage. The finalize-on-last-attempt counter logic is preserved unchanged. * GET /api/v1/knowledge/:id/spans (also kept /stages alias) returns a tree shape with synthesized pending placeholders so the frontend always renders five timeline segments. ?attempt=N enables history navigation.
2026-05-27 06:05:47 +00:00
for idx, img := range images {
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
// Match image to the ParsedChunk whose content contains the image URL.
// ChunkID was populated by processChunks with the real DB UUID.
chunkID := imageChunkOwner(img.ServingURL, chunks)
if chunkID == "" {
logger.Warnf(ctx, "Image has no owning text chunk: knowledge=%s image=%s", knowledge.ID, img.ServingURL)
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
payload := types.ImageMultimodalPayload{
feat(gallery): add an image gallery tab with schema-driven filters (#3694) * feat(image): observe image attributes and let the policy decide OCR Describe each image with the VLM as before, but ask it to also observe two attributes about the image in the same round — how much body text it carries (contain.text) and whether it presents data visually (contain.data_visual) — then let a small pure function decide whether that image is worth a second, separate OCR round. Per-class OCR was the first shape of this idea; a class (chart / photo / logo) is only an indirect proxy for 'is there text worth reading here', and the class table has to grow whenever a new kind of image shows up. The decision actually needs the observed attributes, so it reads them directly, and the attribute set is a backend registry row rather than a new class. The observation and the caption share one VLM call; OCR stays a separate call (prompt isolation, see #3291). An attribute the model does not answer for is left absent rather than filled with a conservative default, so the trace never claims an observation that did not happen, and an incomplete observation falls back to the on_unobserved policy (OCR still runs). The registry also carries the panel's display text, so a new attribute needs no frontend change. Off by default: image_attrs_enabled=false keeps today's behaviour (one caption and one OCR per image). KB config: image_processing_config.image_attrs_enabled / image_actions; per-upload override via process_config. Registry: GET /api/v1/image-attrs/schema. * feat(gallery): add image gallery tab with schema-driven filters Adds a 4th knowledge-base tab parallel to Documents/Wiki/Graph that browses every image asset in a KB. Backend: - GET /api/v1/knowledge-bases/:id/images lists image assets projected from chunks.image_info, with keyword (caption/OCR), multi-value attribute (attr_<name>=<value>), is_enabled and sort filters applied in memory, plus pagination. - Resolves the source knowledge item title (SourceName) via a batched GetKnowledgeBatch so the viewer can show a human-readable source. Frontend: - ImageGallery.vue: thumbnail grid + search/sort + schema-driven filter panel (from GET /image-attrs/schema) + single-image viewer with prev/next, attributes/caption/OCR/source. - Wired as the gallery tab in KnowledgeBase.vue; i18n keys in all 5 locales. * feat(gallery): drive filters/search/sort from a configurable attribute contract The gallery UI is no longer hardcoded: it renders from a self-describing contract served by GET /knowledge-bases/:id/gallery-config (live attribute sources, every attribute's definition with usage flags merged across the config tiers, and the caller's search activation state). - Attribute sources form an open registry (types.RegisterGalleryAttrSource); a builtin source models caption/ocr_text/timestamps/enabled so the gallery has zero special cases. - Usage resolution: user > KB > system > source, field by field; the system tier lives in system_settings (gallery.policy, JSON, no rebuild), the KB tier slot is wired in the engine but not stored yet. - Search activation is the user's own record: mode (all|custom) plus per-field on/off in users.preferences.gallery; source declarations never set defaults (unrecorded = off in custom mode). - image_info is read through a gallery-local struct, removing the compile dependency on the attribute-pipeline types; the gallery builds and runs with or without that feature deployed. - ListImages validates search_in / sort_by / attr_filters against the contract; ineligible fields are dropped, not served. * fix(frontend): inline the shared graph-drawer stylesheet (@import instead of <style src>) plugin-vue 6.0.6 keys unscoped src-style descriptors by the imported file path, so AgentStreamDisplay.vue and WikiBrowser.vue — both importing components/css/wiki-graph-drawer.less — overwrite each other during the build and the second one crashes with "reading 'scoped'". Adding the gallery changed the module order enough to make the collision hit every time. Inlining the same stylesheet keeps the emitted CSS identical and removes the shared descriptor key. * feat(gallery): render attributes from short labels with descriptions in tooltips A source could only say one thing about a value, so the filter panel had to put a full sentence inside a checkbox. Attributes and their values now carry two pieces of text: a short label for the space-constrained controls (checkbox, search field, sort option) and a description for wherever there is room (tooltip, detail panel). The contract's value list becomes an array of {value, label, description}, and the display helpers resolve each field separately: the gallery stamps the short name on a control and moves the sentence into a tooltip. Translation overlays are looked up per field, so a source that ships no gallery-specific text still picks up the attribute pipeline's own wording. * fix(gallery): let locale text win over the contract's wording The filter panel read the backend's own label before asking the locale, so a translated value never got a chance: the contract ships its own default-language wording, and it shadowed the overlay for every locale. Built keys were also off by a segment — imageAttr.<name> has to be imageAttr.<name>.label, and the gallery's own keys live under knowledgeEditor.wikiBrowser.gallery.attr — so builtin and system attributes fell through to English on a Chinese UI. * feat(gallery): top bar layout, pinned panels and per-value verdicts The toolbar moves onto its own row above the grid, so the controls no longer eat into the space the images are there for: search box, the two scope switches, sort field and direction, and the result count all sit in one flex row. The settings behind them are no longer inline either — each opens as a popover under its control and can be pinned to a right-hand rail, where the two panels take turns as tabs instead of both claiming width at once. Filtering gains a third state per attribute value. Where a value could only be picked or not picked, it can now be "off" (hide those images), "on" (show them whatever else says) or neutral (leave them alone), which is what lets one attribute's rules talk about an image another attribute tried to hide without the pair of them cancelling each other out: a forced display outranks a forced hide, and anything no rule speaks about stays visible. The switch that used to only exist inside the panel now has a toolbar home as well. "筛选:全显示" genuinely drops the attribute constraint instead of imposing it against a panel the user cannot see. Filtering used to empty the list the moment it was switched on. Any image whose attribute was never observed — every image ingested before the attribute pipeline existed — read as a mismatch for every filter, which is not narrowing a list but losing it. Absence now stays silence: an attribute no image carries places no constraint on it, until the pipeline catches up and fills the value in. Co-authored-by: WorkBuddy * feat(gallery): expose the image attribute pipeline as a gallery source The gallery's contract resolved to a single source, so the filter panel could only offer "Enabled" while the attributes the observe-and-describe pipeline fills in — contain.text, contain.data_visual — never reached the UI. The registry is a gallery attribute source like any other: every attribute it declares is offered to the gallery, filterable by default, with the config tiers able to override the usage flags at runtime. The registration lives in the attribute pipeline's own commit; this branch carried an earlier, squapshot of that work which predated the split of an attribute value into a short label and a description, so the registry's value shape and this file have been brought in line with it. Both PRs now hold byte-identical copies of the source hook, which is what lets either one land first and the other merge cleanly afterwards. Co-authored-by: WorkBuddy * fix(gallery): viewer race, pin icon, panel anchoring and scope wording Opening the viewer rendered the img element with the previous or empty source while the proxy fetch was still producing a blob, and the error that empty source fired locked the viewer in its failure state even after the real image arrived. The resolved source now lands before the flag is consulted, and a token keeps a slow fetch of one image from overwriting a faster one that navigated past it. The pin button drew nothing: TDesign has no "pushpin" glyph, so the button rendered as an empty shell. It now uses pin / pin-filled, keeps its place beside the tab bar, and a pinned rail assigns its columns explicitly — the panel precedes the main section in the DOM, so leaving the grid to source order handed the wide column to the panel and squeezed the images into the rail. The floating panel no longer appears at a hardcoded offset: it anchors just below the arrow that summoned it, the arrow flips up while its panel is out, a second press retracts, and any click elsewhere in the toolbar closes it. When a rail is pinned the arrows turn to the requested tab instead of spawning a second surface. The scope words (全部 / 全显示 / 自定义) become plain status text rather than a second dropdown — they name the current mode, and only the arrow beside them opens the panel that changes it. Co-authored-by: WorkBuddy * fix(web): align the OCR-on-unobserved switch with the other setting rows The switch sat bare inside its setting-row while every other switch on the page is wrapped in setting-control, which is what reserves the right column and centers the control vertically. With the row laid out from the top, the bare switch hugged the row's upper edge and crowded the description text — visibly out of place next to its neighbors. Wrapping it in setting-control gives it the same right-aligned, centered slot as the rest. Co-authored-by: WorkBuddy * fix(web): move the OCR-on-unobserved row out of the vertical schema row The row lived inside setting-row-vertical, whose descendant rule stretches every setting-info and setting-control beneath it to 100% width. Two full-width flex children side by side cannot fit, so the control overflowed the container and the switch landed past the right edge — visibly further out than the switch on the row above. The row and its note now sit beside the vertical block instead of inside it, under their own condition, so the switch shares the ordinary row layout and its right edge lines up with the "image attribute observation" switch above. Co-authored-by: WorkBuddy * fix(gallery): applying a verdict now activates the filter scope Setting an off/on verdict while the panel's master switch was off silently ignored it: buildParams only attaches attr_rules in custom scope, and setVerdict never flipped the scope. A verdict the user just expressed now switches the scope to custom; clearing the last meaningful verdict returns to all, since custom with no rules constrains nothing. * fix(gallery): search checkboxes stay visible and idle panels read as dimmed The search panel hid its field checkboxes while the master switch was on, so the only way to reach them was to flip the switch first. They now sit next to the switch like the filter panel's verdicts do: dimmed in all-field mode (where they carry no weight) yet clickable, and touching one drops the mode to custom. The filter panel's verdict rows dim the same way while the filter switch is off. * fix(gallery): bulk verdict row, neutral default mark, panel polish The clear-filters button never matched what the panel is for, so it is now a bulk verdict row: one set of -/off/on buttons that applies the chosen position to every value of every value-typed attribute, with the default mark turned into a language-neutral dash. The panel head drops its second divider (the tab bar already draws one) and the tabs follow the toolbar's order: search left, filter right. * fix(gallery): drop the all-fields caption and center the order arrow The caption above the search checkboxes showed and hid with the master switch, shoving the checkboxes down on every flip; it said nothing the dimmed state doesn't, so it is gone. The order button's arrow is an inline svg, which sits on the text baseline and reads as riding high; it now centers against the label. * fix(gallery): center the order arrow for real vertical-align never applied: the icon is a flex item inside the button's inline-flex text wrapper, and the wrapper's default stretch pins the explicitly-sized 16px icon to the top of the 22px line box. align-items: center on the wrapper is what actually centers it. * fix(gallery): shorten panel tab labels in en and ru The two-word labels overflowed the 300px panel and forced the tab bar into scroll arrows; single-word labels fit in every locale that was affected. * docs: drop the image pipeline rewrite from this branch The rewritten 'Go 侧接手后' paragraph belongs to the image attribute observation work (#3635), which this branch carries as a prerequisite and which already documents the caption_ocr / observation_driven split. Keeping a competing rewrite of the same paragraph on the gallery branch makes it collide with upstream, which extended that paragraph with the custom_instructions and inline HTML table notes. Restoring the shared wording keeps the gallery branch free of this file so upstream's edits merge cleanly. * style: gofmt the gallery attribute types Struct field tags in the resolved gallery config were one column narrow, so gofmt rebroke the alignment block. Whitespace only. * style(gallery): use design tokens in the gallery styles The style guard ratchet fails on any new violation. ImageGallery.vue shipped with 47 TDesign token fallbacks, 21 literal font sizes, 4 literal radii and a 0.15s transition; all of them now read the --app-* / --td-* tokens, which is what the guard asks for and what dark mode depends on. * lint(gallery): fix the golangci-lint findings in the gallery code lll: the three over-long swagger @Param lines and one registry row were shortened. ineffassign: ctx was assigned before the access check and then reassigned, so the first value was dead; it is now declared once, after the check. errcheck: the three unchecked c.Error calls in ListImages. revive: the AttrSpec / AttrValue doc comment block was attached to the wrong type and split into one block each. staticcheck S1016: the gallery registration converts the registry value instead of restating its fields. * lint(gallery): wrap the image query select and check the last c.Error * style: reformat the wrapped image select in chunk.go * fix(gallery): address review findings on ordering, KB switch and blob lifetime - sortImageAssets: swap operands for desc instead of negating, keeping a strict weak ordering so ties page stably - ImageGallery: reload on knowledgeBaseId change, drop stale list responses, fetch thumbnails in parallel with one cached blob per URL, revoke blobs on unmount, default sort to builtin:created_at - KnowledgeBase: non-wiki KBs with a stale wiki/graph tab fall back to documents again - handler: move ListImages godoc out of ListKnowledgeFolders' block and document attr_filters / attr_rules - DecideOCR: a payload with no OCR conditions uses the built-in policy instead of silently skipping OCR * docs(parsing): describe the caption_ocr and observation_driven image pipelines Carried over from #3635, which this PR supersedes. * fix(gallery): load local:// and other storage handles through the KB file proxy The gallery's own scheme check only caught resource://, provider:// and storage://, so local:// (the default storage), minio://, cos:// and s3:// images went straight into <img src> and never rendered. Resolve through isProviderFileURL, the scheme list chat and wiki already use, and lock the routing with a test. * fix(kb-editor): keep API-customised OCR conditions on save and upload The KB editor always wrote the registry default into image_actions.ocr.on, so any unrelated edit replaced a knowledge base's custom OCR conditions with the default table; the upload dialog did the same for the per-document override. Keep a stored custom list and fall back to the registry default only when there is none, and show the conditions actually in effect instead of the default table in both panels. * perf(gallery): de-duplicate, filter, sort and page images in SQL Every gallery request used to read every image-bearing chunk of the KB, OCR text included, decode it in Go and page in memory. A single query now expands the image_info arrays, keeps one row per image URL, applies the keyword / attribute / verdict / enabled filters and the sort, and returns only the page with the filtered total. The expansion carries narrow scalars only; filters and JSON sort keys are evaluated on the winning entry of each image, and the page's JSON is read back for its rows alone. Postgres runs the query with JIT off, since the fixed 100-rows-per-call estimate of jsonb_array_elements otherwise prices it ~100x high and compilation dominates. On 20k images with 2 KB of OCR text each (40k chunks), a page drops from ~750 ms to ~100-200 ms on postgres and ~200 ms on sqlite; keyword search over OCR text stays a full scan (~400-600 ms) until the text is indexed. The filter semantics are pinned against both databases. * perf(gallery): serve the gallery from a trigger-maintained chunk_images table Reading images out of chunks.image_info meant parsing every image chunk of the knowledge base on each request, so a page still cost time in proportion to the KB. chunk_images (versioned/000113, sqlite/000032) keeps one row per image_info entry with caption, OCR text and attributes as columns; triggers on chunks keep it in step with every write path, and the migration backfills existing chunks. Copies of one image stay separate rows and the query lists the copy on the most recently updated chunk through an indexed anti-join, so writes decide nothing and concurrent writers need no locking. On postgres, caption and OCR text get pg_trgm indexes when the extension is available. On 20k images with 2 KB of OCR text each (40k chunks): postgres first page 10 ms, page 500 41 ms, keyword 2 ms, filters 23 ms sqlite first page 3 ms, page 500 39 ms, keyword 147 ms, filters 51 ms down from ~100-600 ms. Writing those 40k image chunks costs 7.0 s instead of 1.3 s on postgres (1.9 s instead of 1.0 s on sqlite), mostly the trigram indexes; status and enable-flag updates patch rows in place. --------- Co-authored-by: tayadwx <tayadwx@users.noreply.github.com> Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-25 04:33:59 +00:00
TenantID: knowledge.TenantID,
KnowledgeID: knowledge.ID,
KnowledgeBaseID: kb.ID,
ChunkID: chunkID,
ImageURL: img.ServingURL,
EnableOCR: true,
EnableCaption: true,
ImageAttrsEnabled: eff.ImageAttrsEnabled,
ImageActions: eff.ImageActions,
Language: lang,
ImageSourceType: metadata["image_source_type"],
Attempt: attempt,
ImageIndex: idx,
feat(chat): open cited documents at the cited passage (#3700) * feat(chat): open cited documents at the cited passage Clicking a citation used to show only the parsed chunk. It now opens the original file in the references panel, jumps to the cited place and highlights it, narrowed to the sentence the citation supports. Parsing records where each chunk sits in the original file (chunks.source_locators): PDF page and paragraph boxes from the docreader, MinerU and PaddleOCR-VL layouts; Word paragraphs, slides, sheet rows and EPUB chapters aligned in Go against any parser engine's Markdown; text offsets for Markdown/TXT; segment times for audio. Pipeline text rewrites are followed with a line-diff remapper. Scanned PDF pages get their OCR text as quotes at search time so a sentence can pick its page. The frontend renders PDFs with pdf.js and every other previewable type with the existing preview, then highlights with the CSS Custom Highlight API in a highlighter yellow that stays visible against the brand green. * fix(docreader): serialize source blocks outside main so tests import it test_docx_tables stubs docreader.parser in sys.modules, so importing docreader.main from a later test failed in the full unittest discover run. The wire conversion now lives in docreader.source_wire, which needs only the proto. * fix(chat): tighten source locators from review - Remap rewritten-line-for-line stretches by line so scanned PDF pages no longer drift onto the wrong page. - Keep the source preview mounted for citations in the file already open. - Wait for in-flight PDF page renders before looking for the text layer. - Count image rune offsets in one pass; stream xlsx rows up to maxUnits. - Start text locators after a UTF-8 BOM, as viewers decode without it. - Only re-query image children for scanned-page results. - Seek audio citations without autoplay and drop stale seek listeners. - Fix the SQLite migration's cross-reference to versioned/000113. * fix(migrations): renumber chunk source locators after main's chunk_images main took versioned 000113 and sqlite 000032 for chunk_images, so the source_locators column moves to versioned 000114 and sqlite 000033.
2026-09-25 05:26:16 +00:00
SourceLocators: img.SourceLocators,
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
langfuse.InjectTracing(ctx, &payload)
payloadBytes, err := json.Marshal(payload)
if err != nil {
logger.Warnf(ctx, "Failed to marshal image multimodal payload: %v", err)
continue
}
task := asynq.NewTask(types.TypeImageMultimodal, payloadBytes,
asynq.Queue(types.QueueMultimodal), asynq.MaxRetry(3), asynq.Timeout(30*time.Minute))
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
if _, err := s.task.Enqueue(task); err != nil {
logger.Warnf(ctx, "Failed to enqueue image multimodal task for %s: %v", img.ServingURL, err)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
continue
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
enqueued++
logger.Infof(ctx, "Enqueued image:multimodal task for %s", img.ServingURL)
}
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return s.releaseUnownedMultimodalSlots(
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
ctx, knowledge, redisKey, counterSeeded, len(images), enqueued,
)
}
// releaseUnownedMultimodalSlots settles the multimodal fan-in counter against
// what actually reached the queue.
//
// Every enqueued image task drains exactly one slot when it exits terminally,
// and the knowledge only leaves "processing" once the counter reaches zero. A
// slot whose task was never enqueued (payload marshal failure, asynq refusing
// the write) has no owner, so without this release the counter stalls above
// zero, post-process is never triggered, and the row sits in "processing"
// until the housekeeping sweep fails it an hour later — which reaches the user
// as an unexplained parse failure. This mirrors the shortfall release
// KnowledgePostProcess already performs for its own enrichment subtasks.
func (s *knowledgeService) releaseUnownedMultimodalSlots(
ctx context.Context,
knowledge *types.Knowledge,
redisKey string,
counterSeeded bool,
planned, enqueued int,
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
) error {
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
if enqueued == 0 {
// No task exists to finalize this knowledge, whatever the counter
// says. Drive post-process directly so the row completes on the
// chunks that were already indexed instead of waiting to be swept.
logger.Warnf(ctx,
"[ImageMultimodal] No image task enqueued for %s (planned=%d); enqueueing post-process directly",
knowledge.ID, planned)
if counterSeeded {
// Detached like the shortfall path below: a cancelled parent
// context would otherwise leave the seeded key to expire on its
// own 24h TTL.
dctx, cancel := context.WithTimeout(
context.WithoutCancel(ctx), finalizeSubtaskDetachedTimeout)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
s.delMultimodalCounter(dctx, redisKey)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
cancel()
}
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return s.enqueueKnowledgePostProcessTask(ctx, knowledge)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
}
shortfall := planned - enqueued
if shortfall <= 0 {
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return nil
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
}
if !counterSeeded {
// Seeding failed, so the key is absent and the first image to finish
// already drives post-process through the missing-key fallback in
// checkAndFinalizeAllImages. Decrementing here would only create the
// key below zero and finalize before the siblings are done.
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return nil
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
}
logger.Warnf(ctx,
"[ImageMultimodal] Releasing %d un-enqueued image slot(s) for %s (planned=%d enqueued=%d)",
shortfall, knowledge.ID, planned, enqueued)
// Detached ctx, for the same reason KnowledgePostProcess detaches its own
// releases: these slots have no other path to drain, so a parent context
// cancelled mid-fan-out (graceful shutdown) must not skip the release.
rctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), finalizeSubtaskDetachedTimeout)
defer cancel()
pending, err := s.decrMultimodalSlots(rctx, redisKey, int64(shortfall))
if err != nil {
// Giving up here puts the row back in the state this whole fix exists
// to remove: a counter no task can drain, recovered only by the
// housekeeping sweep an hour later. Say so at error level so it is
// greppable, rather than hiding it in a warning.
logger.Errorf(ctx,
"Failed to release %d multimodal slot(s) for %s after %d attempts: %v; "+
"row will be left to the housekeeping sweep",
shortfall, knowledge.ID, multimodalSlotReleaseAttempts, err)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return nil
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
}
if pending <= 0 {
// Every enqueued sibling had already finished, so the release owns the
// finalize. Ordering is safe either way: the slots we just drained have
// no task behind them, so exactly one path reaches zero.
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if err := s.enqueueKnowledgePostProcessTask(ctx, knowledge); err != nil {
return err
}
s.delMultimodalCounter(rctx, redisKey)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
}
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return nil
}
// delMultimodalCounter removes the fan-in counter from Redis, or from the
// in-process stand-in in Lite mode.
func (s *knowledgeService) delMultimodalCounter(ctx context.Context, redisKey string) {
if s.redisClient == nil {
liteMultimodalDel(redisKey)
return
}
s.redisClient.Del(ctx, redisKey)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
}
// multimodalSlotReleaseAttempts bounds the retry on the release decrement.
//
// The release is the only thing that can ever drain an un-owned slot, so a
// single transient Redis error must not be the end of it — that would strand
// the row exactly as it did before this fix. Attempts stay small because they
// share the detached context's budget, and the housekeeping sweep is still the
// backstop when Redis is genuinely down.
//
// DECRBY is not idempotent, so a retry after a lost reply can over-decrement.
// That is the safe direction to fail in: an over-decrement finalizes early
// (post-process may miss some OCR / caption chunks, and repeat deliveries are
// already handled by its non-processing-status branch), whereas not retrying
// strands the document in "processing" for an hour.
const multimodalSlotReleaseAttempts = 3
// multimodalSlotReleaseBackoff is the unit of linear backoff between release
// attempts, small enough that all attempts fit the detached 10s budget.
const multimodalSlotReleaseBackoff = 100 * time.Millisecond
// decrMultimodalSlots decrements the fan-in counter by `by`, retrying transient
// Redis failures, and returns the resulting count.
func (s *knowledgeService) decrMultimodalSlots(
ctx context.Context, redisKey string, by int64,
) (int64, error) {
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if s.redisClient == nil {
return liteMultimodalDecrBy(redisKey, by), nil
}
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
var lastErr error
for attempt := 1; attempt <= multimodalSlotReleaseAttempts; attempt++ {
pending, err := s.redisClient.DecrBy(ctx, redisKey, by).Result()
if err == nil {
return pending, nil
}
lastErr = err
if attempt == multimodalSlotReleaseAttempts {
break
}
logger.Warnf(ctx, "multimodal slot release attempt %d/%d failed for %s: %v",
attempt, multimodalSlotReleaseAttempts, redisKey, err)
select {
case <-time.After(time.Duration(attempt) * multimodalSlotReleaseBackoff):
case <-ctx.Done():
return 0, ctx.Err()
}
}
return 0, lastErr
}
// enqueueKnowledgePostProcessTask hands a knowledge to the post-process
// orchestrator, which owns the enrichment fan-out and the promotion out of
// "processing". Shared by the no-multimodal path and by the multimodal slot
// release, so both build the same payload (attempt, language, tracing).
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
//
// The error must reach the caller's task result: once the chunks are indexed
// this enqueue is the only thing that moves the row out of "processing", so
// swallowing it acked the task with the row stranded until housekeeping.
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
func (s *knowledgeService) enqueueKnowledgePostProcessTask(
ctx context.Context, knowledge *types.Knowledge,
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
) error {
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
if s.task == nil {
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return nil
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
}
payload := types.KnowledgePostProcessPayload{
TenantID: knowledge.TenantID,
KnowledgeID: knowledge.ID,
KnowledgeBaseID: knowledge.KnowledgeBaseID,
Language: types.LanguageFromContextOrDefault(ctx),
Attempt: attemptFromCtx(ctx),
}
langfuse.InjectTracing(ctx, &payload)
payloadBytes, err := json.Marshal(payload)
if err != nil {
logger.Errorf(ctx, "Failed to marshal knowledge post process payload: %v", err)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return fmt.Errorf("marshal post process payload: %w", err)
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
}
task := asynq.NewTask(types.TypeKnowledgePostProcess, payloadBytes,
knowledgePostProcessTaskOptions()...)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
if err := enqueueWithRetry(ctx, s.task, task); err != nil {
logger.Errorf(ctx, "Failed to enqueue knowledge post process task for %s: %v", knowledge.ID, err)
return err
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
fix(knowledge): stop two parse paths from stranding a row in processing (#3445) * fix(knowledge): stop two parse paths from stranding a row in processing Both of these left parse_status on "processing" with nothing left to move it, so the document sat there until the housekeeping sweep failed it an hour later with "task stuck in processing, recovered by housekeeping" — reaching the user as a slow, unexplained parse failure. processChunks returned silently when the embedding model could not be resolved (deleted model, expired credentials, unreachable provider). It reports nothing to its callers, so the attempt ended with the row still marked processing. Persist the failure with the underlying cause and record the embedding stage as failed, matching how the sibling GetASRModel branch already handles a model it cannot resolve. enqueueImageMultimodalTasks seeded the multimodal fan-in counter with len(images) before the fan-out, then only warned when a payload failed to marshal or asynq refused the write. Those slots have no task behind them to drain them, so the counter never reached zero and post-process was never triggered. Release the shortfall after the fan-out, and drive post-process directly when the release itself brings the counter to zero or when nothing reached the queue at all — the same reconciliation KnowledgePostProcess already performs for its enrichment subtasks. Seeding the counter before enqueueing is kept deliberately: an image task that finishes early would otherwise decrement a key the fan-out is about to overwrite. The release is what settles the resulting gap. Also collapse the Redis key into multimodalPendingKey so the fan-out and fan-in cannot drift, and share one enqueueKnowledgePostProcessTask between the no-multimodal path and the slot release. * fix(knowledge): keep the embedding-model guard from clobbering abort state Review follow-up on the two stranded-row fixes. The embedding-model guard wrote parse_status=failed unconditionally, which made two cases worse than the silent return it replaced. Resolving a model reads the database, so the entry guard's verdict is already stale by the time the error comes back: - A user cancel signals asynq CancelProcessing, which cancels the handler context. GetEmbeddingModel then fails with context.Canceled and the guard overwrote "cancelled" with "failed: ... context canceled" — mislabelling an interrupted run as a broken model. Worker preemption and graceful shutdown look the same. - ReplaceKnowledgeFile keeps the knowledge ID and swaps file_path. UpdateKnowledge is a full-row Save and file_path is not among omitFieldsOnUpdate, so the stale row rolled the path back over the replacement and marked the replacement's live attempt failed. So the guard now returns without writing when the context is gone or the error is a context error, re-checks isKnowledgeAborted before writing, and persists through updateKnowledgeUnlessSourceReplaced like the completion path already does. The multimodal slot release gave up on the first Redis error. Since the release is the only thing that can drain a slot with no task behind it, that put the row straight back into the stranded state this fix exists to remove. It now retries a bounded number of times and logs at error level when it still cannot settle the counter. DECRBY is not idempotent, so a retry after a lost reply can over-decrement; that finalizes early rather than stranding, which is the direction to fail in, and post-process already tolerates repeat deliveries. The nothing-enqueued branch's Del also moves onto the detached context, so a cancelled parent no longer leaves the seeded key to expire on its own 24h TTL. Two reporting corrections while here: the span now carries the same message as the document list instead of a fixed generic string, because the timeline renders error_message and withholds error_detail; and the comment no longer claims expired credentials or an unreachable provider surface here — resolving a model only reads the row and constructs a client, so those fail later on the first BatchIndex round-trip. Adds 6 tests for the paths above. Two of them initially passed against the unfixed code because the entry guard caught them before the model call, so the repository fake now serves the cancelled / replaced row only after the guard's own reads, which is the window that actually exists.
2026-09-20 05:02:05 +00:00
logger.Infof(ctx, "Enqueued knowledge post process task for %s", knowledge.ID)
fix(knowledge): stop parses from getting stuck in processing or finalizing (#3696) Reparse: - Open the new attempt only after override validation and cleanup pass. A rejected reparse used to leave the previous run's subtasks treating themselves as superseded, so the row stayed in finalizing for good. - Cancel the previous run's queued tasks when it is still in flight. ProcessDocument, processChunks, post-process, image tasks, wiki ops and the dead-letter callback now skip work that belongs to a superseded attempt. - Summary tasks write only their own columns. A full-row save after the LLM call could put finalizing over the new run's processing row. Errors that were acked with the row still in flight: - A failed post-process enqueue is retried in place and then returned, so the task retries instead of leaving the row in processing. - Transient tenant/knowledge reads and the processing write now retry. - An image whose orphan check fails on its final attempt is still counted. Empty manual content fails the row. Counters: - FinalizeSubtask runs its decrement and promote in one transaction. Slot releases retry, and the post-process shortfall release keeps going past a failed release. Wiki: - A synthesis model that cannot be built releases the KB's pending documents on the final attempt instead of retrying forever. - Panics in map/reduce workers become per-document failures. - Housekeeping protects a row held by a wiki op for at most 48h. Lite mode: - SyncTaskExecutor honours options set on asynq.NewTask (MaxRetry, Timeout, Deadline, ProcessIn/At), stops on SkipRetry, and runs the same final-failure callback as the dead-letter middleware. - The multimodal fan-in counter is kept in process, so post-process waits for every image. Also: - Housekeeping recovers summaries left pending on finished rows. Cancel and stall recovery close unfinished summaries. - Housekeeping sweeps no longer overlap. - Data source URL ingest writes only the metadata column. - The document list drops cards the batch endpoint no longer returns.
2026-09-25 05:26:38 +00:00
return nil
refactor(knowledge): split 9.8k-line service file by responsibility internal/application/service/knowledge.go had grown to 9883 lines / 149 functions spanning CRUD, document processing, summary/question generation, clone/move, FAQ (CRUD+import+index+export), wiki cleanup, multimodal image, and file utilities. Navigating it, or diffing changes in it, was increasingly painful. Purely mechanical split into 8 files in the same package. No signatures, behaviors, or types were modified. knowledgeService struct, NewKnowledgeService, and package-level errors remain in knowledge.go unchanged. Per-file imports were trimmed by goimports. knowledge.go 497 struct + constructor + errs + CRUD reads + Search knowledge_create.go 1144 CreateFrom{File,URL,Passage,Manual} + helpers knowledge_delete.go 686 Delete + wiki cleanup + ProcessKnowledgeListDelete knowledge_process.go 2407 ProcessDocument/Summary/Question + Reparse + UpdateImageInfo knowledge_clone_move.go 1049 Clone* + Move* + progress persistence knowledge_faq.go 1932 FAQ CRUD + Search + Export knowledge_faq_import.go 1939 FAQ import/validate/index + runningFAQImportInfo knowledge_util.go 352 file-type/url/hash + VLM+Storage config + resolveFileService Verification: go build, go vet, gofmt on the 8 files, and golangci-lint all clean (22 issues post-split matches 22 pre-split in knowledge.go — no new issues introduced). The pre-existing unused warnings on getVLMConfig / buildStorageConfig were left as-is rather than removing dead code beyond the scope of this task.
2026-05-06 05:47:23 +00:00
}
// ProcessKnowledgeListReparse handles Asynq knowledge list reparse tasks.
func (s *knowledgeService) ProcessKnowledgeListReparse(ctx context.Context, t *asynq.Task) error {
var payload types.KnowledgeListReparsePayload
if err := json.Unmarshal(t.Payload(), &payload); err != nil {
logger.Errorf(ctx, "Failed to unmarshal knowledge list reparse payload: %v", err)
return err
}
ctx = payload.Initiator.Apply(ctx)
taskID, _ := asynq.GetTaskID(ctx)
ctx = withKBActivityTask(ctx, taskID, kbActivityTrigger(ctx))
logger.Infof(ctx, "Processing knowledge list reparse task for %d knowledge items", len(payload.KnowledgeIDs))
ctx, ids, err := s.reparseTaskScope(ctx, payload)
if err != nil || len(ids) == 0 {
return err
}
tenant, err := s.tenantRepo.GetTenantByID(ctx, payload.TenantID)
if err != nil {
logger.Errorf(ctx, "Failed to get tenant %d: %v", payload.TenantID, err)
return err
}
ctx = context.WithValue(ctx, types.TenantIDContextKey, payload.TenantID)
ctx = context.WithValue(ctx, types.TenantInfoContextKey, tenant)
outcome, err := runKnowledgeListReparseSubmissions(ids, func(id string) error {
_, err := s.ReparseKnowledge(ctx, id, payload.ProcessConfig)
return err
})
logger.Infof(ctx, "Knowledge list reparse task finished: %d submitted, %d failed",
outcome.Submitted, outcome.Failed)
return err
}
type knowledgeListReparseOutcome struct {
Submitted int
Failed int
}
// runKnowledgeListReparseSubmissions attempts every item so one bad document
// cannot block the remainder of the batch. A partial failure is non-retryable:
// retrying the wrapper task would destructively reparse items that were already
// submitted successfully. Failed rows remain selectable for an explicit retry.
func runKnowledgeListReparseSubmissions(
ids []string,
submit func(string) error,
) (knowledgeListReparseOutcome, error) {
var outcome knowledgeListReparseOutcome
failures := make([]error, 0)
for _, id := range ids {
if err := submit(id); err != nil {
failures = append(failures, fmt.Errorf("knowledge %s: %w", secutils.SanitizeForLog(id), err))
outcome.Failed++
continue
}
outcome.Submitted++
}
if len(failures) == 0 {
return outcome, nil
}
return outcome, fmt.Errorf(
"%w: batch reparse submitted %d item(s) and failed %d: %w",
asynq.SkipRetry, outcome.Submitted, outcome.Failed, errors.Join(failures...),
)
}