From 196478114ca18c0a5c4358890a334b79dc70b5d5 Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Tue, 24 Nov 2026 11:10:14 +0800 Subject: [PATCH] =?UTF-8?q?fix(onboarding):=20=E7=A7=9F=E6=88=B7=E5=BA=8F?= =?UTF-8?q?=E5=88=97=E9=81=BF=E8=AE=A9=E4=BF=9D=E7=95=99=20ID=20=E5=B9=B6?= =?UTF-8?q?=E4=B8=BA=E5=AD=98=E9=87=8F=E7=A9=BA=E9=97=B4=E8=A1=A5=E9=BD=90?= =?UTF-8?q?=E5=BC=80=E7=AE=B1=E9=BB=98=E8=AE=A4=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因(26040006 等首用户空间零知识库): - 000000 初始迁移把 tenants_id_seq 起点设为 10000,恰好等于内置模型宿主 保留租户 id(DefaultBuiltinModelTenantID=10000):全新环境的第一个用户 空间必然撞上 SeedTenantDefaults 的「永不 seed」豁免,一个默认库都没有; 后续空间(10001+)正常。内置模型行(tenant_id=10000)被真实空间占住, 还存在归属歧义隐患 - 注册引导是创建时一次性动作,存量空间因引导当时失败(如模型未就绪)或 上述碰撞而缺库时,此后永不补建 修复: - migration 000160:租户序列推到 10001 之后——全新库从 10001 起号(10000 永久保留给内置模型宿主),存量库按 max(id) 连续续号不受影响 - SeedTenantDefaults 拆出 seedStarterKB 供创建时引导与自愈共用;保留租户 豁免注释同步更新 - 新增 EnsureTenantDefaultKnowledgeBases 惰性自愈:挂在知识库列表读路径 (幂等/fail-open/进程内互斥防并发重复建档)——企业培训课件/题库两库恒补 (Source 去重),「新手入门」仅零库空间补建(不复活用户主动删除的入门库) 效果:26040006(租户 10000)等存量用户打开「知识库」页即自动补齐 3 个默认 库;全新环境的首个用户空间不再撞保留 id --- .../application/service/tenant_bootstrap.go | 154 +++++++++++++++--- internal/handler/knowledgebase.go | 13 ++ .../interfaces/tenant_bootstrap_service.go | 8 + ...0_tenant_seq_reserve_builtin_host.down.sql | 10 ++ ...160_tenant_seq_reserve_builtin_host.up.sql | 16 ++ 5 files changed, 177 insertions(+), 24 deletions(-) create mode 100644 migrations/versioned/000160_tenant_seq_reserve_builtin_host.down.sql create mode 100644 migrations/versioned/000160_tenant_seq_reserve_builtin_host.up.sql diff --git a/internal/application/service/tenant_bootstrap.go b/internal/application/service/tenant_bootstrap.go index e4d9c23..0a64784 100644 --- a/internal/application/service/tenant_bootstrap.go +++ b/internal/application/service/tenant_bootstrap.go @@ -7,6 +7,7 @@ import ( "io" "mime/multipart" "strings" + "sync" "academy/internal/logger" "academy/internal/types" @@ -89,6 +90,8 @@ type tenantBootstrapService struct { kbService interfaces.KnowledgeBaseService kgService interfaces.KnowledgeService tenantService interfaces.TenantService + // ensureMu 串行化惰性自愈的补建段(见 EnsureTenantDefaultKnowledgeBases)。 + ensureMu sync.Mutex } // SeedTenantDefaults implements interfaces.TenantBootstrapService. See the @@ -105,7 +108,11 @@ func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant if tenant == nil || tenant.ID == 0 { return } - // 内置模型的宿主租户(tenant 10000)不是用户空间,永不 seed。 + // 内置模型的宿主租户(tenant 10000)不是用户空间,永不 seed。000160 起 + // 租户序列已避开 10000(见 migration 000160_tenant_seq_reserve_builtin_host), + // 新环境不会再有真实空间拿到该 id;存量环境若首空间已占住 10000(引导因此 + // 被跳过,一个默认库都没有),其默认库由 EnsureTenantDefaultKnowledgeBases + // 惰性自愈补齐——该路径不带本豁免。 if tenant.ID == types.DefaultBuiltinModelTenantID { return } @@ -149,32 +156,13 @@ func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant embedID := PickDefaultModelID(models, types.ModelTypeEmbedding) rerankID := PickDefaultModelID(models, types.ModelTypeRerank) - // 1) 默认知识库。模型解析不到就留空——行为与用户手动不选一致。 - kb := &types.KnowledgeBase{ - Name: BootstrapKBName, - Description: "系统自动创建的入门知识库,已绑定默认模型,可直接提问体验知识库问答。", - Type: types.KnowledgeBaseTypeDocument, - SummaryModelID: chatID, - EmbeddingModelID: embedID, - } - createdKB, err := s.kbService.CreateKnowledgeBase(seedCtx, kb) - if err != nil { - logger.Warnf(ctx, "tenant bootstrap: create starter KB failed: tenant=%d err=%v", tenant.ID, err) + // 1) 默认知识库 + 欢迎文档(创建时引导与存量空间自愈共用同一实现)。 + // 模型解析不到就留空——行为与用户手动不选一致。 + if err := s.seedStarterKB(seedCtx, chatID, embedID); err != nil { return } - logger.Infof(ctx, "tenant bootstrap: starter KB created: tenant=%d kb=%s", tenant.ID, createdKB.ID) - // 2) 预置欢迎文档(标准上传管道,切片/向量化由后台任务异步完成)。 - if fh, fhErr := buildInMemoryFileHeader(bootstrapWelcomeFileName, bootstrapWelcomeDocContent); fhErr != nil { - logger.Warnf(ctx, "tenant bootstrap: build welcome file failed: tenant=%d err=%v", tenant.ID, fhErr) - } else if _, upErr := s.kgService.CreateKnowledgeFromFile(seedCtx, createdKB.ID, fh, nil, nil, "", nil, "", nil); upErr != nil { - logger.Warnf(ctx, "tenant bootstrap: upload welcome doc failed: tenant=%d kb=%s err=%v", - tenant.ID, createdKB.ID, upErr) - } else { - logger.Infof(ctx, "tenant bootstrap: welcome doc queued: tenant=%d kb=%s", tenant.ID, createdKB.ID) - } - - // 3) 租户级检索重排模型(RetrievalConfig 其余零值按 GetEffective* 回退默认)。 + // 2) 租户级检索重排模型(RetrievalConfig 其余零值按 GetEffective* 回退默认)。 if rerankID != "" { if tenant.RetrievalConfig == nil { tenant.RetrievalConfig = &types.RetrievalConfig{} @@ -192,6 +180,124 @@ func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant } } +// seedStarterKB 创建「新手入门」知识库并预置欢迎文档(标准上传管道,切片/ +// 向量化由后台任务异步完成)。创建时引导(SeedTenantDefaults)与存量空间 +// 惰性自愈(EnsureTenantDefaultKnowledgeBases)共用同一实现。fail-open: +// 失败仅记日志返回 error,由调用方决定是否中断后续步骤。 +func (s *tenantBootstrapService) seedStarterKB(ctx context.Context, chatID, embedID string) error { + kb := &types.KnowledgeBase{ + Name: BootstrapKBName, + Description: "系统自动创建的入门知识库,已绑定默认模型,可直接提问体验知识库问答。", + Type: types.KnowledgeBaseTypeDocument, + SummaryModelID: chatID, + EmbeddingModelID: embedID, + } + createdKB, err := s.kbService.CreateKnowledgeBase(ctx, kb) + if err != nil { + logger.Warnf(ctx, "tenant bootstrap: create starter KB failed: err=%v", err) + return err + } + logger.Infof(ctx, "tenant bootstrap: starter KB created: kb=%s", createdKB.ID) + + if fh, fhErr := buildInMemoryFileHeader(bootstrapWelcomeFileName, bootstrapWelcomeDocContent); fhErr != nil { + logger.Warnf(ctx, "tenant bootstrap: build welcome file failed: kb=%s err=%v", createdKB.ID, fhErr) + } else if _, upErr := s.kgService.CreateKnowledgeFromFile(ctx, createdKB.ID, fh, nil, nil, "", nil, "", nil); upErr != nil { + logger.Warnf(ctx, "tenant bootstrap: upload welcome doc failed: kb=%s err=%v", createdKB.ID, upErr) + } else { + logger.Infof(ctx, "tenant bootstrap: welcome doc queued: kb=%s", createdKB.ID) + } + return nil +} + +// EnsureTenantDefaultKnowledgeBases implements interfaces.TenantBootstrapService. +// 存量空间默认库惰性自愈:注册/建空间引导是一次性动作,历史空间会因引导 +// 当时的失败(如模型尚未就绪)或保留租户 id 碰撞(migration 000160 前首空间 +// 占住 10000 被豁免)而缺失默认库。知识库列表访问时幂等补齐: +// - 企业培训「课件/题库」两库恒补(Source 标记去重); +// - 「新手入门」仅空间为空时补建——零库说明引导从未成功;用户已在使用的 +// 空间不复活其主动删除的入门库。 +// +// 必须幂等且 fail-open:挂在列表读路径上,任何失败只记日志,不影响正常返回。 +func (s *tenantBootstrapService) EnsureTenantDefaultKnowledgeBases(ctx context.Context) { + defer func() { + if r := recover(); r != nil { + logger.Errorf(ctx, "tenant bootstrap: lazy ensure recovered from panic: %v", r) + } + }() + + tenantID, ok := types.TenantIDFromContext(ctx) + if !ok || tenantID == 0 || s.kbService == nil { + return + } + + // 快路径:三项默认库齐备直接返回(一次只读列表,绝大多数请求止于此)。 + kbs, err := s.kbService.ListKnowledgeBasesByTenantID(ctx, tenantID) + if err != nil { + logger.Warnf(ctx, "tenant bootstrap: lazy ensure list KBs failed: tenant=%d err=%v", tenantID, err) + return + } + if tenantDefaultsComplete(kbs) { + return + } + + // 进程内串行化:并发的列表请求只允许一个进入补建段,防止同名默认库 + // 重复建档(CreateKnowledgeBase 无名称唯一约束)。锁内复查双保险。 + s.ensureMu.Lock() + defer s.ensureMu.Unlock() + kbs, err = s.kbService.ListKnowledgeBasesByTenantID(ctx, tenantID) + if err != nil { + logger.Warnf(ctx, "tenant bootstrap: lazy ensure list KBs failed: tenant=%d err=%v", tenantID, err) + return + } + if tenantDefaultsComplete(kbs) { + return + } + + // 自愈上下文:执行租户落到目标空间;补建人取当前登录用户(与引导同口径, + // 合成 API-key 用户跳过);CreateKnowledgeFromFile 依赖 TenantInfo。 + seedCtx := types.WithExecutionTenant(ctx, tenantID) + if tenant, tErr := s.tenantService.GetTenantByID(ctx, tenantID); tErr == nil && tenant != nil { + seedCtx = context.WithValue(seedCtx, types.TenantInfoContextKey, tenant) + } + if uid, ok := types.UserIDFromContext(ctx); ok && !types.IsSyntheticUserID(uid) { + seedCtx = context.WithValue(seedCtx, types.UserIDContextKey, uid) + } + logger.Infof(seedCtx, "tenant bootstrap: lazy ensure defaults, tenant=%d existing_kbs=%d", tenantID, len(kbs)) + + // 培训两库恒补;「新手入门」仅零库空间补建(见方法注释)。 + s.ensureTrainingKnowledgeBases(seedCtx, tenantID, kbs) + if len(kbs) == 0 { + models, mErr := s.modelService.ListModels(seedCtx) + if mErr != nil { + logger.Warnf(seedCtx, "tenant bootstrap: lazy ensure list models failed: tenant=%d err=%v", tenantID, mErr) + return + } + _ = s.seedStarterKB(seedCtx, + PickDefaultModelID(models, types.ModelTypeKnowledgeQA), + PickDefaultModelID(models, types.ModelTypeEmbedding)) + } +} + +// tenantDefaultsComplete 判断空间的开箱默认库是否齐备:新手入门 + 培训课件 + +// 培训题库三项都在才算完整。 +func tenantDefaultsComplete(kbs []*types.KnowledgeBase) bool { + var hasStarter, hasCourseware, hasBank bool + for _, kb := range kbs { + if kb == nil { + continue + } + switch { + case kb.Name == BootstrapKBName: + hasStarter = true + case kb.Source == types.KnowledgeBaseSourceTrainingCourseware: + hasCourseware = true + case kb.Source == types.KnowledgeBaseSourceTrainingQuestionBank: + hasBank = true + } + } + return hasStarter && hasCourseware && hasBank +} + // ensureTrainingKnowledgeBases 确保「企业培训(课件)/(题库)」两个系统默认库 // 存在(按 Source 标记去重,缺失即建,已存在跳过;模型由 CreateKnowledgeBase // 的默认兜底自动绑定)。与培训域 trainingService.ensureTrainingKnowledgeBases diff --git a/internal/handler/knowledgebase.go b/internal/handler/knowledgebase.go index 920b085..6583063 100644 --- a/internal/handler/knowledgebase.go +++ b/internal/handler/knowledgebase.go @@ -48,6 +48,9 @@ type KnowledgeBaseHandler struct { // default handle mode is available. fileService interfaces.FileService storageResolver interfaces.StorageBackendResolver + // bootstrap 幂等自愈空间开箱默认库(新手入门/企业培训课件/题库),挂在 + // 知识库列表读路径上补齐存量空间缺失的默认库;可为 nil(测试桩)。 + bootstrap interfaces.TenantBootstrapService } // NewKnowledgeBaseHandler creates a new knowledge base handler instance @@ -63,6 +66,7 @@ func NewKnowledgeBaseHandler( fileService interfaces.FileService, storageResolver interfaces.StorageBackendResolver, profileService interfaces.KnowledgeBaseProfileService, + bootstrap interfaces.TenantBootstrapService, ) *KnowledgeBaseHandler { return &KnowledgeBaseHandler{ cfg: cfg, @@ -76,6 +80,7 @@ func NewKnowledgeBaseHandler( userService: userService, fileService: fileService, storageResolver: storageResolver, + bootstrap: bootstrap, } } @@ -639,6 +644,14 @@ func (h *KnowledgeBaseHandler) ListKnowledgeBases(c *gin.Context) { return } + // 开箱默认库惰性自愈(幂等/fail-open):注册引导是一次性动作,存量空间因 + // 引导当时失败或保留租户 id 碰撞(migration 000160 前首空间占住 10000) + // 而缺失默认库时,访问列表即补齐——培训课件/题库两库恒补,新手入门仅 + // 零库空间补建。补建后本次查询即可见。 + if h.bootstrap != nil { + h.bootstrap.EnsureTenantDefaultKnowledgeBases(ctx) + } + // Get all knowledge bases for this tenant kbs, err := h.service.ListKnowledgeBases(ctx) if err != nil { diff --git a/internal/types/interfaces/tenant_bootstrap_service.go b/internal/types/interfaces/tenant_bootstrap_service.go index 0387e47..b2794ec 100644 --- a/internal/types/interfaces/tenant_bootstrap_service.go +++ b/internal/types/interfaces/tenant_bootstrap_service.go @@ -17,4 +17,12 @@ type TenantBootstrapService interface { // bootstrap knowledge base are skipped. ownerUserID (may be empty for // platform-managed tenants) is recorded as the KB creator. SeedTenantDefaults(ctx context.Context, tenant *types.Tenant, ownerUserID string) + + // EnsureTenantDefaultKnowledgeBases lazily self-heals a workspace's + // out-of-the-box defaults on list access: the two enterprise-training KBs + // are always ensured (Source-marker idempotent), and the starter KB is + // re-created only when the workspace has no knowledge bases at all (a + // seed that never succeeded). Idempotent and fail-open — safe to call on + // read paths. The execution tenant is taken from the context. + EnsureTenantDefaultKnowledgeBases(ctx context.Context) } diff --git a/migrations/versioned/000160_tenant_seq_reserve_builtin_host.down.sql b/migrations/versioned/000160_tenant_seq_reserve_builtin_host.down.sql new file mode 100644 index 0000000..08113df --- /dev/null +++ b/migrations/versioned/000160_tenant_seq_reserve_builtin_host.down.sql @@ -0,0 +1,10 @@ +-- Migration: 000160_tenant_seq_reserve_builtin_host (down) +-- 回滚到旧行为:序列回到 10000(与 000000 初始迁移一致)。仅当真实租户 +-- 尚未占用 10000 时执行,否则保留现值(占用的 id 无法安全腾挪)。 + +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM tenants WHERE id = 10000) THEN + PERFORM setval('tenants_id_seq', 10000, false); + END IF; +END $$; diff --git a/migrations/versioned/000160_tenant_seq_reserve_builtin_host.up.sql b/migrations/versioned/000160_tenant_seq_reserve_builtin_host.up.sql new file mode 100644 index 0000000..07fc74c --- /dev/null +++ b/migrations/versioned/000160_tenant_seq_reserve_builtin_host.up.sql @@ -0,0 +1,16 @@ +-- Migration: 000160_tenant_seq_reserve_builtin_host +-- 租户序列与内置模型宿主租户(10000)避让。000000 初始迁移把 tenants_id_seq +-- 起点设为 10000,导致全新环境的第一个用户空间恰好占住保留的内置模型宿主 +-- 租户 id(DefaultBuiltinModelTenantID=10000):SeedTenantDefaults 对该 id +-- 永不 seed(首用户空间没有任何默认库),且内置模型行(tenant_id=10000) +-- 的归属被真实空间占住。本迁移把序列推到 10001 之后: +-- 全新库(无租户行)→ 下一个租户 id 从 10001 开始,10000 永久保留; +-- 存量库 → 按现有 max(id) 连续续号,不受影响。 + +DO $$ BEGIN RAISE NOTICE '[Migration 000160] Realigning tenants_id_seq past reserved builtin-model host id 10000...'; END $$; + +SELECT setval( + 'tenants_id_seq', + GREATEST(COALESCE((SELECT MAX(id) FROM tenants), 0), 10001), + COALESCE((SELECT MAX(id) FROM tenants) IS NOT NULL, false) +);