feat(knowledge): make document summary generation optional
parent
ac4dd59712
commit
105c177b80
|
|
@ -1385,6 +1385,9 @@ const processConfigLines = computed<string[]>(() => {
|
|||
if (o.asr_config?.enabled != null) lines.push(`${t(k('asr'))}: ${onOff(o.asr_config.enabled)}`)
|
||||
|
||||
const qg = o.question_generation_config
|
||||
if (o.summary_enabled != null) {
|
||||
lines.push(`${t('uploadConfirm.documentSummary')}: ${onOff(o.summary_enabled)}`)
|
||||
}
|
||||
if (qg?.enabled != null) {
|
||||
lines.push(`${t(k('question'))}: ${qg.enabled ? t(k('questionOn'), { n: qg.question_count ?? 3 }) : t(k('off'))}`)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -787,6 +787,11 @@ export default {
|
|||
chunkLoadFailed: 'Failed to load chunks'
|
||||
},
|
||||
uploadConfirm: {
|
||||
documentSummary: "Document summary",
|
||||
documentSummaryDescription: "Choose whether to automatically summarize documents in this import.",
|
||||
generateSummary: "Generate document summaries",
|
||||
generateSummaryHint: "Enabled by default. Disable to skip summaries while parsing, indexing, and other configured steps continue.",
|
||||
|
||||
title: 'Confirm Upload',
|
||||
parseConfig: 'Parse settings',
|
||||
configNav: 'Parse settings navigation',
|
||||
|
|
|
|||
|
|
@ -787,6 +787,11 @@ export default {
|
|||
chunkLoadFailed: 'チャンクの読み込みに失敗しました'
|
||||
},
|
||||
uploadConfirm: {
|
||||
documentSummary: "ドキュメントの要約",
|
||||
documentSummaryDescription: "今回インポートするドキュメントの要約を自動生成するか選択します。",
|
||||
generateSummary: "ドキュメントの要約を生成",
|
||||
generateSummaryHint: "既定で有効です。無効にすると要約生成をスキップし、解析、インデックス作成、その他の処理は設定どおり実行されます。",
|
||||
|
||||
title: 'アップロードの確認',
|
||||
parseConfig: '解析設定',
|
||||
configNav: '解析設定のナビゲーション',
|
||||
|
|
|
|||
|
|
@ -6448,6 +6448,11 @@ export default {
|
|||
}
|
||||
},
|
||||
uploadConfirm: {
|
||||
documentSummary: "문서 요약",
|
||||
documentSummaryDescription: "이번에 가져오는 문서의 요약을 자동으로 생성할지 선택합니다.",
|
||||
generateSummary: "문서 요약 생성",
|
||||
generateSummaryHint: "기본적으로 활성화됩니다. 비활성화하면 요약 생성을 건너뛰며 파싱, 인덱싱 및 기타 단계는 설정대로 진행됩니다.",
|
||||
|
||||
title: '문서 업로드 확인',
|
||||
parseConfig: '파싱 설정',
|
||||
configNav: '파싱 설정 탐색',
|
||||
|
|
|
|||
|
|
@ -6448,6 +6448,11 @@ export default {
|
|||
}
|
||||
},
|
||||
uploadConfirm: {
|
||||
documentSummary: "Сводка документа",
|
||||
documentSummaryDescription: "Выберите, создавать ли сводки документов при этом импорте.",
|
||||
generateSummary: "Создавать сводки документов",
|
||||
generateSummaryHint: "Включено по умолчанию. При отключении создание сводок пропускается, а разбор, индексация и другие этапы выполняются согласно настройкам.",
|
||||
|
||||
title: 'Подтверждение загрузки',
|
||||
parseConfig: 'Настройки разбора',
|
||||
configNav: 'Навигация по настройкам разбора',
|
||||
|
|
|
|||
|
|
@ -6450,6 +6450,11 @@ export default {
|
|||
}
|
||||
},
|
||||
uploadConfirm: {
|
||||
documentSummary: "文档摘要",
|
||||
documentSummaryDescription: "为本次导入的文档选择是否自动生成摘要。",
|
||||
generateSummary: "生成文档摘要",
|
||||
generateSummaryHint: "默认开启。关闭后跳过摘要生成,文档解析、索引及其他处理步骤仍按配置执行。",
|
||||
|
||||
title: '上传文档确认',
|
||||
parseConfig: '解析配置',
|
||||
configNav: '解析配置导航',
|
||||
|
|
|
|||
|
|
@ -60,6 +60,7 @@ export interface ExtractConfigOverride {
|
|||
}
|
||||
|
||||
export interface KnowledgeProcessOverrides {
|
||||
summary_enabled?: boolean
|
||||
parser_engine_rules?: ParserEngineRule[]
|
||||
chunking_config?: ChunkingConfigOverride
|
||||
enable_multimodel?: boolean
|
||||
|
|
|
|||
|
|
@ -480,6 +480,26 @@
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<div v-show="activeSection === 'summary'" class="section" data-section="summary">
|
||||
<div class="kb-settings-block">
|
||||
<div class="section-header">
|
||||
<h2 class="section-title">{{ t('uploadConfirm.documentSummary') }}</h2>
|
||||
<p class="section-desc">{{ t('uploadConfirm.documentSummaryDescription') }}</p>
|
||||
</div>
|
||||
<div class="settings-group">
|
||||
<div class="setting-row">
|
||||
<div class="setting-info">
|
||||
<label>{{ t('uploadConfirm.generateSummary') }}</label>
|
||||
<p class="desc">{{ t('uploadConfirm.generateSummaryHint') }}</p>
|
||||
</div>
|
||||
<div class="setting-control">
|
||||
<t-switch v-model="uiState.summaryEnabled" size="medium" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-show="activeSection === 'question'" class="section">
|
||||
<div class="kb-settings-block">
|
||||
<div class="section-header">
|
||||
|
|
@ -576,7 +596,7 @@ import type {
|
|||
const IMAGE_EXTENSIONS = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
|
||||
const AUDIO_EXTENSIONS = ['mp3', 'wav', 'm4a', 'flac', 'ogg']
|
||||
|
||||
type ConfigSectionKey = 'tags' | 'parser' | 'chunking' | 'multimodal' | 'asr' | 'question' | 'graph'
|
||||
type ConfigSectionKey = 'tags' | 'parser' | 'chunking' | 'multimodal' | 'asr' | 'summary' | 'question' | 'graph'
|
||||
type IssueSectionKey = 'multimodal' | 'asr'
|
||||
|
||||
interface ChunkingUIConfig {
|
||||
|
|
@ -598,6 +618,7 @@ interface ChunkingUIConfig {
|
|||
}
|
||||
|
||||
interface UploadUIState {
|
||||
summaryEnabled: boolean
|
||||
chunkingConfig: ChunkingUIConfig
|
||||
multimodalConfig: { enabled: boolean; vllmModelId: string; descriptionLanguage?: string; customInstructions?: string }
|
||||
asrConfig: { enabled: boolean; modelId: string; language: string }
|
||||
|
|
@ -936,6 +957,7 @@ const navItems = computed(() => {
|
|||
t('knowledgeEditor.sidebar.asr'),
|
||||
issueSectionKeys.value.has('asr'),
|
||||
)
|
||||
push('summary', 'file', t('uploadConfirm.documentSummary'))
|
||||
push('question', 'chat', t('knowledgeEditor.advanced.questionGeneration.label'))
|
||||
if (isGraphSectionAvailable.value) {
|
||||
push('graph', 'chart-bubble', t('knowledgeEditor.sidebar.graph'))
|
||||
|
|
@ -997,6 +1019,10 @@ function getSectionNavStatus(
|
|||
statusTone: asr.modelId ? undefined : 'warning',
|
||||
}
|
||||
}
|
||||
case 'summary':
|
||||
return uiState.value.summaryEnabled
|
||||
? { status: t('uploadConfirm.statusOn') }
|
||||
: { status: t('uploadConfirm.statusOff'), statusTone: 'muted' }
|
||||
case 'question': {
|
||||
const question = uiState.value.questionGenerationConfig
|
||||
if (!question.enabled) {
|
||||
|
|
@ -1056,6 +1082,7 @@ function goToSection(key: ConfigSectionKey) {
|
|||
|
||||
function createDefaultUIState(): UploadUIState {
|
||||
return {
|
||||
summaryEnabled: true,
|
||||
chunkingConfig: {
|
||||
chunkSize: 512,
|
||||
chunkOverlap: 80,
|
||||
|
|
@ -1092,6 +1119,7 @@ function initFromKbInfo(kb: any) {
|
|||
}
|
||||
|
||||
uiState.value = {
|
||||
summaryEnabled: true,
|
||||
chunkingConfig: {
|
||||
chunkSize: kb.chunking_config?.chunk_size || 512,
|
||||
chunkOverlap: kb.chunking_config?.chunk_overlap || 80,
|
||||
|
|
@ -1142,6 +1170,7 @@ function buildProcessOverrides(): KnowledgeProcessOverrides {
|
|||
const chunking = state.chunkingConfig
|
||||
|
||||
const overrides: KnowledgeProcessOverrides = {
|
||||
summary_enabled: state.summaryEnabled,
|
||||
parser_engine_rules: chunking.parserEngineRules,
|
||||
chunking_config: {
|
||||
chunk_size: chunking.chunkSize,
|
||||
|
|
@ -1195,6 +1224,7 @@ function buildProcessOverrides(): KnowledgeProcessOverrides {
|
|||
function applyOverridesToState(o?: KnowledgeProcessOverrides | null) {
|
||||
if (!o) return
|
||||
const s = uiState.value
|
||||
if (o.summary_enabled != null) s.summaryEnabled = o.summary_enabled
|
||||
const cc = o.chunking_config
|
||||
if (cc) {
|
||||
if (cc.chunk_size != null) s.chunkingConfig.chunkSize = cc.chunk_size
|
||||
|
|
|
|||
|
|
@ -698,6 +698,24 @@ func (r *knowledgeRepository) SetFinalizing(
|
|||
return res.RowsAffected > 0, nil
|
||||
}
|
||||
|
||||
// CompleteProcessingWithoutSubtasks is the zero-enrichment counterpart of
|
||||
// SetFinalizing. Keep the state check and completion fields in one write so a
|
||||
// concurrent cancel/delete or duplicate delivery cannot be overwritten.
|
||||
func (r *knowledgeRepository) CompleteProcessingWithoutSubtasks(ctx context.Context, id string) (bool, error) {
|
||||
now := time.Now()
|
||||
res := r.db.WithContext(ctx).Model(&types.Knowledge{}).
|
||||
Where("id = ? AND parse_status = ?", id, types.ParseStatusProcessing).
|
||||
Updates(map[string]interface{}{
|
||||
"parse_status": types.ParseStatusCompleted,
|
||||
"summary_status": types.SummaryStatusNone,
|
||||
"pending_subtasks_count": 0,
|
||||
"error_message": "",
|
||||
"processed_at": now,
|
||||
"updated_at": now,
|
||||
})
|
||||
return res.RowsAffected > 0, res.Error
|
||||
}
|
||||
|
||||
// CountKnowledgeByKnowledgeBaseID counts the number of knowledge items in a knowledge base
|
||||
func (r *knowledgeRepository) CountKnowledgeByKnowledgeBaseID(
|
||||
ctx context.Context,
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package repository
|
|||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
|
@ -420,3 +421,46 @@ func TestUpdateActiveDeletingKnowledgeColumns_GuardsStateAndSoftDelete(t *testin
|
|||
status, _ = reloadKnowledgeRow(t, db, deletedDeletingID)
|
||||
assert.Equal(t, types.ParseStatusDeleting, status)
|
||||
}
|
||||
|
||||
func TestCompleteProcessingWithoutSubtasks(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
status string
|
||||
deleted bool
|
||||
want bool
|
||||
}{
|
||||
{types.ParseStatusProcessing, false, true},
|
||||
{types.ParseStatusCancelled, false, false},
|
||||
{types.ParseStatusDeleting, false, false},
|
||||
{types.ParseStatusCompleted, false, false},
|
||||
{types.ParseStatusFinalizing, false, false},
|
||||
{types.ParseStatusProcessing, true, false},
|
||||
} {
|
||||
t.Run(tc.status+"/deleted="+fmt.Sprint(tc.deleted), func(t *testing.T) {
|
||||
db := setupKnowledgeTestDB(t)
|
||||
repo := NewKnowledgeRepository(db)
|
||||
id := insertKnowledgeWithStatus(t, db, tc.status, tc.deleted)
|
||||
require.NoError(t, db.Exec(
|
||||
`UPDATE knowledges SET summary_status = 'pending', error_message = 'old error' WHERE id = ?`, id,
|
||||
).Error)
|
||||
completed, err := repo.CompleteProcessingWithoutSubtasks(context.Background(), id)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.want, completed)
|
||||
status, count := reloadKnowledgeRow(t, db, id)
|
||||
var summary string
|
||||
require.NoError(t, db.Raw(`SELECT summary_status FROM knowledges WHERE id = ?`, id).Scan(&summary).Error)
|
||||
if tc.want {
|
||||
require.Equal(t, types.ParseStatusCompleted, status)
|
||||
require.Zero(t, count)
|
||||
require.Equal(t, types.SummaryStatusNone, summary)
|
||||
require.Empty(t, reloadKnowledgeErrorMessage(t, db, id))
|
||||
completed, err = repo.CompleteProcessingWithoutSubtasks(context.Background(), id)
|
||||
require.NoError(t, err)
|
||||
require.False(t, completed, "duplicate delivery must not complete twice")
|
||||
} else {
|
||||
require.Equal(t, tc.status, status)
|
||||
require.Equal(t, types.SummaryStatusPending, summary)
|
||||
require.Equal(t, "old error", reloadKnowledgeErrorMessage(t, db, id))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -138,3 +138,51 @@ func TestRunKnowledgeListReparseSubmissionsSucceeds(t *testing.T) {
|
|||
require.NoError(t, err)
|
||||
require.Equal(t, knowledgeListReparseOutcome{Submitted: 2}, outcome)
|
||||
}
|
||||
|
||||
func TestReparseKnowledgePreservesOrChangesSummaryChoice(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
overrides *types.KnowledgeProcessOverrides
|
||||
want bool
|
||||
}{
|
||||
{name: "reuse upload choice"},
|
||||
{
|
||||
name: "explicitly keep disabled",
|
||||
overrides: &types.KnowledgeProcessOverrides{SummaryEnabled: processConfigBoolPtr(false)},
|
||||
},
|
||||
{
|
||||
name: "enable on reparse",
|
||||
overrides: &types.KnowledgeProcessOverrides{SummaryEnabled: processConfigBoolPtr(true)},
|
||||
want: true,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
knowledge := &types.Knowledge{
|
||||
ID: "knowledge-1", TenantID: 7, KnowledgeBaseID: "kb-1",
|
||||
Type: types.KnowledgeTypeManual, ParseStatus: types.ParseStatusCompleted,
|
||||
}
|
||||
metadata := types.NewManualKnowledgeMetadata("# content", types.ManualKnowledgeStatusPublish, 1)
|
||||
require.NoError(t, knowledge.SetManualMetadata(metadata))
|
||||
require.NoError(t, knowledge.SetProcessOverrides(&types.KnowledgeProcessOverrides{
|
||||
SummaryEnabled: processConfigBoolPtr(false),
|
||||
}))
|
||||
kb := &types.KnowledgeBase{ID: "kb-1", TenantID: 7}
|
||||
queue := &wikiEnqueueFailureTaskQueue{}
|
||||
svc := &knowledgeService{
|
||||
repo: &reparseFailureKnowledgeRepo{knowledge: knowledge},
|
||||
kbService: &reparseFailureKBService{kb: kb}, task: queue,
|
||||
}
|
||||
ctx := context.WithValue(context.Background(), types.TenantIDContextKey, uint64(7))
|
||||
ctx, err := access.WithKBTaskWrite(ctx, kb, 7)
|
||||
require.NoError(t, err)
|
||||
got, err := svc.ReparseKnowledge(ctx, knowledge.ID, tc.overrides)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []string{types.TypeManualProcess}, queue.taskTypes)
|
||||
overrides, err := got.ProcessOverrides()
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, overrides.SummaryEnabled)
|
||||
require.Equal(t, tc.want, *overrides.SummaryEnabled)
|
||||
require.Equal(t, tc.want, ResolveProcessConfig(kb, overrides).SummaryEnabled)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -282,6 +282,7 @@ func TestCreateKnowledgeFromFile_PersistsProcessOverrides(t *testing.T) {
|
|||
chunkSize := 512
|
||||
overrides := &types.KnowledgeProcessOverrides{
|
||||
ChunkingConfig: &types.ChunkingConfig{ChunkSize: chunkSize},
|
||||
SummaryEnabled: processConfigBoolPtr(false),
|
||||
}
|
||||
|
||||
knowledge, err := svc.CreateKnowledgeFromFile(
|
||||
|
|
@ -304,6 +305,8 @@ func TestCreateKnowledgeFromFile_PersistsProcessOverrides(t *testing.T) {
|
|||
parsed, err := repo.createdKnowledge.ProcessOverrides()
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, parsed)
|
||||
require.NotNil(t, parsed.SummaryEnabled)
|
||||
require.False(t, *parsed.SummaryEnabled)
|
||||
require.NotNil(t, parsed.ChunkingConfig)
|
||||
require.Equal(t, chunkSize, parsed.ChunkingConfig.ChunkSize)
|
||||
|
||||
|
|
|
|||
|
|
@ -205,8 +205,8 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
|||
// until wiki generation actually finishes instead of flipping to
|
||||
// completed while wiki runs minutes later. A wiki op that never
|
||||
// drains is bounded by the housekeeping finalizing sweep.
|
||||
willSpawnSummary := len(textChunks) > 0
|
||||
willSpawnQuestion := willSpawnSummary && kb.NeedsEmbeddingModel() &&
|
||||
willSpawnSummary := eff.SummaryEnabled && len(textChunks) > 0
|
||||
willSpawnQuestion := len(textChunks) > 0 && kb.NeedsEmbeddingModel() &&
|
||||
eff.QuestionGenerationConfig.Enabled
|
||||
willSpawnWiki := kb.IndexingStrategy.WikiEnabled && len(textChunks) > 0
|
||||
willSpawnAutoTag := kb.Type == types.KnowledgeBaseTypeDocument &&
|
||||
|
|
@ -293,21 +293,16 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
|||
}, "", "")
|
||||
return nil
|
||||
case expectedSubtasks == 0:
|
||||
// Nothing to enrich — fast path keeps the previous behavior so
|
||||
// users without summary/question/graph see 'completed' immediately.
|
||||
updates := map[string]interface{}{
|
||||
"parse_status": types.ParseStatusCompleted,
|
||||
"updated_at": time.Now(),
|
||||
completed, err := s.knowledgeRepo.CompleteProcessingWithoutSubtasks(ctx, payload.KnowledgeID)
|
||||
if err != nil {
|
||||
s.tracker().FailSpan(ctx, postSpan, "COMPLETION_FAILED", err.Error(), err)
|
||||
return fmt.Errorf("complete knowledge without enrichment: %w", err)
|
||||
}
|
||||
if len(textChunks) > 0 {
|
||||
updates["summary_status"] = types.SummaryStatusNone
|
||||
}
|
||||
if err := s.knowledgeRepo.UpdateKnowledgeColumns(ctx, payload.KnowledgeID, updates); err != nil {
|
||||
logger.Warnf(ctx, "[KnowledgePostProcess] Failed to mark %s completed (no subtasks): %v",
|
||||
payload.KnowledgeID, err)
|
||||
} else {
|
||||
logger.Infof(ctx, "[KnowledgePostProcess] Knowledge %s marked completed (no enrichment subtasks).",
|
||||
payload.KnowledgeID)
|
||||
if !completed {
|
||||
output := types.JSONMap{"skipped": "knowledge_no_longer_processing"}
|
||||
s.tracker().EndSpan(ctx, postSpan, output)
|
||||
s.tracker().FinalizeAttempt(ctx, payload.KnowledgeID, attempt, types.SpanStatusDone, output, "", "")
|
||||
return nil
|
||||
}
|
||||
default:
|
||||
// Flip processing to finalizing before fan-out so a parallel
|
||||
|
|
@ -374,7 +369,7 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
|||
}
|
||||
|
||||
// Queue best-effort automatic tagging only after the processing row has
|
||||
// successfully handed off to finalizing. This avoids model calls from a
|
||||
// successfully handed off to finalizing or completed. This avoids model calls from a
|
||||
// duplicate post-process delivery that observes an already terminal row.
|
||||
if willSpawnAutoTag {
|
||||
enqueuedAutoTag = s.enqueueAutoTagTask(ctx, payload, attempt)
|
||||
|
|
@ -390,25 +385,27 @@ func (s *KnowledgePostProcessService) Handle(ctx context.Context, task *asynq.Ta
|
|||
ctx, payload.KnowledgeID, "summary_status", types.SummaryStatusFailed,
|
||||
)
|
||||
}
|
||||
if willSpawnQuestion {
|
||||
// Create the postprocess.question grouping span up front so the
|
||||
// per-batch subspans (enqueued just below, run later in their own
|
||||
// workers) have a parent to nest under. It's begun and ended right
|
||||
// here as a structural container — the batches extend past it,
|
||||
// which the timeline renders with the wrapping outline bar.
|
||||
if grp := s.tracker().BeginSubSpan(ctx, postSpan, postprocessQuestionGroupSpanName,
|
||||
types.SpanKindSubSpan, types.JSONMap{
|
||||
"batch_count": questionBatchCount,
|
||||
"chunk_count": len(questionChunks),
|
||||
"batch_size": questionGenChunkBatchSize,
|
||||
}); grp != nil {
|
||||
s.tracker().EndSpan(ctx, grp, types.JSONMap{
|
||||
"batch_count": questionBatchCount,
|
||||
"chunk_count": len(questionChunks),
|
||||
})
|
||||
}
|
||||
enqueuedQuestionCount = s.enqueueQuestionGenerationTasks(ctx, payload, eff.QuestionGenerationConfig, attempt, questionChunks)
|
||||
}
|
||||
if willSpawnQuestion {
|
||||
// Create the postprocess.question grouping span up front so the
|
||||
// per-batch subspans (enqueued just below, run later in their own
|
||||
// workers) have a parent to nest under. It's begun and ended right
|
||||
// here as a structural container — the batches extend past it,
|
||||
// which the timeline renders with the wrapping outline bar.
|
||||
if grp := s.tracker().BeginSubSpan(ctx, postSpan, postprocessQuestionGroupSpanName,
|
||||
types.SpanKindSubSpan, types.JSONMap{
|
||||
"batch_count": questionBatchCount,
|
||||
"chunk_count": len(questionChunks),
|
||||
"batch_size": questionGenChunkBatchSize,
|
||||
}); grp != nil {
|
||||
s.tracker().EndSpan(ctx, grp, types.JSONMap{
|
||||
"batch_count": questionBatchCount,
|
||||
"chunk_count": len(questionChunks),
|
||||
})
|
||||
}
|
||||
enqueuedQuestionCount = s.enqueueQuestionGenerationTasks(
|
||||
ctx, payload, eff.QuestionGenerationConfig, attempt, questionChunks,
|
||||
)
|
||||
}
|
||||
|
||||
// 5. Spawn Graph RAG Tasks — only when graph indexing is enabled in IndexingStrategy
|
||||
|
|
|
|||
|
|
@ -0,0 +1,178 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
"github.com/hibiken/asynq"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type optionalSummaryKnowledgeRepo struct {
|
||||
wikiEnqueueFailureKnowledgeRepo
|
||||
completionErr error
|
||||
completionSkipped bool
|
||||
}
|
||||
|
||||
func (r *optionalSummaryKnowledgeRepo) UpdateKnowledgeColumn(
|
||||
_ context.Context, _ string, column string, value interface{},
|
||||
) error {
|
||||
if column == "summary_status" {
|
||||
r.knowledge.SummaryStatus = value.(string)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *optionalSummaryKnowledgeRepo) CompleteProcessingWithoutSubtasks(context.Context, string) (bool, error) {
|
||||
if r.completionErr != nil {
|
||||
return false, r.completionErr
|
||||
}
|
||||
if r.completionSkipped {
|
||||
return false, nil
|
||||
}
|
||||
r.knowledge.ParseStatus = types.ParseStatusCompleted
|
||||
r.knowledge.SummaryStatus = types.SummaryStatusNone
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func TestKnowledgePostProcessOptionalSummary(t *testing.T) {
|
||||
t.Setenv("NEO4J_ENABLE", "true")
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
summary *bool
|
||||
question bool
|
||||
graph bool
|
||||
wiki bool
|
||||
wantTasks []string
|
||||
}{
|
||||
{name: "legacy defaults generate summary", wantTasks: []string{types.TypeSummaryGeneration}},
|
||||
{
|
||||
name: "explicitly enabled",
|
||||
summary: processConfigBoolPtr(true),
|
||||
wantTasks: []string{types.TypeSummaryGeneration},
|
||||
},
|
||||
{name: "disabled completes without enrichment", summary: processConfigBoolPtr(false)},
|
||||
{
|
||||
name: "disabled preserves question generation",
|
||||
summary: processConfigBoolPtr(false),
|
||||
question: true,
|
||||
wantTasks: []string{types.TypeQuestionGeneration},
|
||||
},
|
||||
{
|
||||
name: "disabled preserves graph extraction",
|
||||
summary: processConfigBoolPtr(false),
|
||||
graph: true,
|
||||
wantTasks: []string{types.TypeChunkExtract},
|
||||
},
|
||||
{
|
||||
name: "disabled preserves wiki generation",
|
||||
summary: processConfigBoolPtr(false),
|
||||
wiki: true,
|
||||
wantTasks: []string{types.TypeWikiIngest},
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
knowledge := &types.Knowledge{
|
||||
ID: "doc", TenantID: 7, KnowledgeBaseID: "kb", ParseStatus: types.ParseStatusProcessing,
|
||||
}
|
||||
require.NoError(t, knowledge.SetProcessOverrides(&types.KnowledgeProcessOverrides{
|
||||
SummaryEnabled: tt.summary,
|
||||
}))
|
||||
repo := &optionalSummaryKnowledgeRepo{
|
||||
wikiEnqueueFailureKnowledgeRepo: wikiEnqueueFailureKnowledgeRepo{knowledge: knowledge},
|
||||
}
|
||||
queue := &wikiEnqueueFailureTaskQueue{}
|
||||
kb := &types.KnowledgeBase{
|
||||
ID: "kb", TenantID: 7,
|
||||
IndexingStrategy: types.IndexingStrategy{
|
||||
VectorEnabled: true, GraphEnabled: tt.graph, WikiEnabled: tt.wiki,
|
||||
},
|
||||
QuestionGenerationConfig: &types.QuestionGenerationConfig{Enabled: tt.question},
|
||||
ExtractConfig: &types.ExtractConfig{Enabled: tt.graph},
|
||||
}
|
||||
service := &KnowledgePostProcessService{
|
||||
knowledgeRepo: repo,
|
||||
kbService: &wikiEnqueueFailureKBService{kb: kb},
|
||||
chunkRepo: &wikiEnqueueFailureChunkRepo{chunks: []*types.Chunk{{
|
||||
ID: "chunk", TenantID: 7, KnowledgeID: "doc", KnowledgeBaseID: "kb",
|
||||
ChunkType: types.ChunkTypeText, Content: "Document content for summary and enrichment.",
|
||||
}}},
|
||||
taskEnqueuer: queue,
|
||||
pendingRepo: &wikiEnqueueFailurePendingRepo{knowledgeRepo: &repo.wikiEnqueueFailureKnowledgeRepo},
|
||||
}
|
||||
payload, err := json.Marshal(types.KnowledgePostProcessPayload{
|
||||
TenantID: 7, KnowledgeID: "doc", KnowledgeBaseID: "kb",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
task := asynq.NewTask(types.TypeKnowledgePostProcess, payload)
|
||||
require.NoError(t, service.Handle(context.Background(), task))
|
||||
require.Equal(t, tt.wantTasks, queue.taskTypes)
|
||||
require.Equal(t, len(tt.wantTasks), repo.expectedSubtasks)
|
||||
if len(tt.wantTasks) == 0 {
|
||||
require.Equal(t, types.ParseStatusCompleted, knowledge.ParseStatus)
|
||||
} else {
|
||||
require.Equal(t, types.ParseStatusFinalizing, knowledge.ParseStatus)
|
||||
}
|
||||
if tt.summary != nil && !*tt.summary {
|
||||
require.Equal(t, types.SummaryStatusNone, knowledge.SummaryStatus)
|
||||
} else {
|
||||
require.Equal(t, types.SummaryStatusPending, knowledge.SummaryStatus)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestKnowledgePostProcessWithoutSummaryCompletionFailure(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
err error
|
||||
skipped bool
|
||||
}{
|
||||
{name: "database failure is retryable", err: errors.New("database unavailable")},
|
||||
{name: "concurrent cancellation skips auto tagging", skipped: true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
knowledge := &types.Knowledge{
|
||||
ID: "doc", TenantID: 7, KnowledgeBaseID: "kb", ParseStatus: types.ParseStatusProcessing,
|
||||
}
|
||||
require.NoError(t, knowledge.SetProcessOverrides(&types.KnowledgeProcessOverrides{
|
||||
SummaryEnabled: processConfigBoolPtr(false),
|
||||
}))
|
||||
repo := &optionalSummaryKnowledgeRepo{
|
||||
wikiEnqueueFailureKnowledgeRepo: wikiEnqueueFailureKnowledgeRepo{knowledge: knowledge},
|
||||
completionErr: tc.err, completionSkipped: tc.skipped,
|
||||
}
|
||||
queue := &wikiEnqueueFailureTaskQueue{}
|
||||
svc := &KnowledgePostProcessService{
|
||||
knowledgeRepo: repo,
|
||||
kbService: &wikiEnqueueFailureKBService{kb: &types.KnowledgeBase{
|
||||
ID: "kb", TenantID: 7, Type: types.KnowledgeBaseTypeDocument,
|
||||
AutoTagConfig: &types.AutoTagConfig{Enabled: true},
|
||||
}},
|
||||
chunkRepo: &wikiEnqueueFailureChunkRepo{chunks: []*types.Chunk{{
|
||||
ID: "chunk", TenantID: 7, KnowledgeID: "doc", KnowledgeBaseID: "kb",
|
||||
ChunkType: types.ChunkTypeText, Content: "Document content.",
|
||||
}}},
|
||||
taskEnqueuer: queue,
|
||||
}
|
||||
payload, err := json.Marshal(types.KnowledgePostProcessPayload{
|
||||
TenantID: 7, KnowledgeID: "doc", KnowledgeBaseID: "kb",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
err = svc.Handle(context.Background(), asynq.NewTask(types.TypeKnowledgePostProcess, payload))
|
||||
require.ErrorIs(t, err, tc.err)
|
||||
require.Empty(t, queue.taskTypes)
|
||||
require.Equal(t, types.ParseStatusProcessing, knowledge.ParseStatus)
|
||||
if tc.err != nil {
|
||||
repo.completionErr = nil
|
||||
task := asynq.NewTask(types.TypeKnowledgePostProcess, payload)
|
||||
require.NoError(t, svc.Handle(context.Background(), task))
|
||||
require.Equal(t, types.ParseStatusCompleted, knowledge.ParseStatus)
|
||||
require.Equal(t, []string{types.TypeKnowledgeAutoTag}, queue.taskTypes)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -39,6 +39,7 @@ func normalizeParserFileType(fileType string) string {
|
|||
// ResolveProcessConfig merges KB defaults with per-upload overrides for the parse pipeline.
|
||||
func ResolveProcessConfig(kb *types.KnowledgeBase, overrides *types.KnowledgeProcessOverrides) types.EffectiveProcessConfig {
|
||||
eff := types.EffectiveProcessConfig{
|
||||
SummaryEnabled: true,
|
||||
ChunkingConfig: kb.ChunkingConfig,
|
||||
EnableMultimodel: kb.IsMultimodalEnabled(),
|
||||
VLMConfig: kb.VLMConfig,
|
||||
|
|
@ -50,6 +51,9 @@ func ResolveProcessConfig(kb *types.KnowledgeBase, overrides *types.KnowledgePro
|
|||
if overrides == nil {
|
||||
return eff
|
||||
}
|
||||
if overrides.SummaryEnabled != nil {
|
||||
eff.SummaryEnabled = *overrides.SummaryEnabled
|
||||
}
|
||||
|
||||
if overrides.ChunkingConfig != nil {
|
||||
eff.ChunkingConfig = mergeChunkingConfig(eff.ChunkingConfig, overrides.ChunkingConfig)
|
||||
|
|
|
|||
|
|
@ -525,3 +525,27 @@ func TestBuildParentChildConfigs_PropagatesStrategy(t *testing.T) {
|
|||
require.Equal(t, base.Separators, parent.Separators)
|
||||
require.Equal(t, base.Separators, child.Separators)
|
||||
}
|
||||
|
||||
func TestResolveProcessConfig_SummaryEnabled(t *testing.T) {
|
||||
kb := &types.KnowledgeBase{}
|
||||
require.True(t, ResolveProcessConfig(kb, nil).SummaryEnabled)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
value *bool
|
||||
want bool
|
||||
}{
|
||||
{"omitted", nil, true},
|
||||
{"enabled", processConfigBoolPtr(true), true},
|
||||
{"disabled", processConfigBoolPtr(false), false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
knowledge := &types.Knowledge{}
|
||||
_, err := ApplyKnowledgeProcessOverrides(context.Background(), kb, knowledge,
|
||||
&types.KnowledgeProcessOverrides{SummaryEnabled: tc.value}, nil, nil)
|
||||
require.NoError(t, err)
|
||||
overrides, err := knowledge.ProcessOverrides()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.want, ResolveProcessConfig(kb, overrides).SummaryEnabled)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -326,6 +326,9 @@ type KnowledgeRepository interface {
|
|||
// whether the transition took place (false when the row's parse_status
|
||||
// was no longer "processing", e.g. user cancelled / deleted in flight).
|
||||
SetFinalizing(ctx context.Context, id string, expectedSubtasks int) (bool, error)
|
||||
// CompleteProcessingWithoutSubtasks atomically completes a still-processing
|
||||
// document that has no enrichment tasks, without overriding cancel/delete.
|
||||
CompleteProcessingWithoutSubtasks(ctx context.Context, id string) (bool, error)
|
||||
// CountKnowledgeByKnowledgeBaseID counts the number of knowledge items in a knowledge base.
|
||||
CountKnowledgeByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) (int64, error)
|
||||
// CountKnowledgeByStatus counts the number of knowledge items with the specified parse status.
|
||||
|
|
|
|||
|
|
@ -2,6 +2,8 @@ package types
|
|||
|
||||
// KnowledgeProcessOverrides stores per-upload parse config overrides in knowledge metadata.
|
||||
type KnowledgeProcessOverrides struct {
|
||||
// SummaryEnabled defaults to true when omitted for backward compatibility.
|
||||
SummaryEnabled *bool `json:"summary_enabled,omitempty"`
|
||||
ParserEngineRules []ParserEngineRule `json:"parser_engine_rules,omitempty"`
|
||||
ChunkingConfig *ChunkingConfig `json:"chunking_config,omitempty"`
|
||||
EnableMultimodel *bool `json:"enable_multimodel,omitempty"`
|
||||
|
|
@ -18,6 +20,7 @@ type KnowledgeProcessOverrides struct {
|
|||
|
||||
// EffectiveProcessConfig is the merged view used by the parse pipeline.
|
||||
type EffectiveProcessConfig struct {
|
||||
SummaryEnabled bool
|
||||
ChunkingConfig ChunkingConfig
|
||||
EnableMultimodel bool
|
||||
VLMConfig VLMConfig
|
||||
|
|
|
|||
Loading…
Reference in New Issue