Skip to content

fix(tenant): 修复已删除租户读取复活、Runtime 不可用错误映射与删除弹窗静默失败 - #4473

Open
charmingchi1 wants to merge 9 commits into
developfrom
dc-fix-tenant-delete-resurrection-1127
Open

charmingchi1 wants to merge 9 commits into
developfrom
dc-fix-tenant-delete-resurrection-1127

Conversation

@charmingchi1

@charmingchi1 charmingchi1 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

fix(tenant): 修复已删除租户读取复活、Runtime 不可用错误映射与删除弹窗静默失败

背景与根因

修复 11-23 e2e 批次(TENANT-CLEANUP-QUOTA-RESOURCE-20261126)登记的三个产品缺陷,以及排查中发现的第四个缺陷(技能级联清理从未真正执行):

  1. 已删除租户"复活"(API-024 FAIL 根因):SU 删除租户返回 200 后,GET /api/tenants/{id} 因读路径自动回填 TENANT_NAME 配置而返回 200 + "Unnamed Tenant",幽灵租户随即回到 SU 列表首位并被配额统计计入;读过之后再 DELETE 返回 200(重跑整条级联);对已删租户 PUT 改名同样返回 200 并写入名称行;对从未存在的 id GET 也返回 200 并落库。
  2. 11-23 批次 DELETE 全量 500 的真实根因(更正):部署版本 f7e6ba52e 的删除端点用 (role or "").upper() 消费元组角色(feat(gateway): run an independent Gateway image and extract service infrastructure #4314 起 get_current_user_context 返回元组)→ AttributeError 落入兜底分支返回 500,且发生在租户存在性判断之前,因此现存与不存在的租户一律 500。该窗口为 11-18 ~ 11-25,已被 feat (memory): Add tenant and versioned Agent controls for automatic memory #4354 换用 has_any_role 顺带关闭。本 PR 处理的是残余的映射错位:Runtime 不可用/超时被服务层包成 ValidationError → 400(应为 503/504)。
  3. 删除确认弹窗静默失败(PW-RESOURCE-01 failure 截图):删除请求失败时仅有一条约 3 秒的 toast,弹窗在 finally 里无条件关闭,失败与成功观感一致;删除成功但列表刷新失败时 refetchTenants() 默认带 isError 正常 resolve,无任何提示。
  4. (新发现)技能级联清理未执行:_delete_skills_for_tenant 为 async def 但调用处漏了 await,删除租户时技能/技能实例/本地技能文件从未被清理。

核心设计:为什么用 TENANT_ID 身份行做存在性判定

  • create_tenant_with_default_group 原子写入 TENANT_ID 身份行
  • v1 / v2.9.0 SQL 迁移已为全部存量真实租户回填身份行(基于 user_tenant_t 成员表的一次性 DO 块,非运行时触发器,复活插入不会带出身份行)
  • 级联删除第 7 步软删全部配置行(含身份行)→ 删除后身份行必然消失
  • 原实现锚定 TENANT_NAME 行 —— 与 _count_real_tenants 等身份语义用键不一致,正是复活链条的病根

Changes

文件 变更
backend/management/db/configuration/tenant.py 新增 tenant_exists / get_existing_tenant_ids:按 TENANT_ID 身份行判定,批量 IN 查询供列表路径一次往返
backend/management/services/permission/identity/tenants.py get_tenant_info 只读化(身份缺失 → NotFoundException,删除 _ensure_tenant_name_config 回填);get_tenants_paginated 以单次批量查询过滤幽灵 id(data 与 total 均排除,页内 verified_exists 跳过重复校验);delete_tenant 存在性改身份行 + 404 分支顺手清除 name-only 幽灵行 + Runtime 异常透传 + 补 await 技能清理(清单失败隔离为 best-effort);update_tenant_info 写前身份前置 → PUT 已删/不存在租户 404
backend/management/api/identity/tenant.py 删除端点新增 503/504 分支(对齐 conversation_run.py 既有约定);删除重复的遗留 import 行
frontend/app/[locale]/resource-manage/components/UserManageComp.tsx 弹窗失败保持打开 + 内联 Alert;404 幂等处理为"已删除";重试清错;confirmLoading 改为请求期防双击;删除/创建/更新收尾刷新均隔离为独立 try(刷新失败只 warning,不再误报为操作失败);页面回调改 refetchTenants({ throwOnError: true }),使刷新失败提示在真实回调契约下可达;静态 message 迁移到 App.useApp();删除按钮加 aria-label
deploy/sql/migrations/v2.9.0_merged_migrations.sql 不再修改(曾追加一次性幽灵行清理段,按存量数据风险考虑已撤销;该文件与 develop 完全一致,不在本 PR diff 中)
test/backend/services/test_tenant_service.py 回归:身份缺失 → 404 且 insert_config 零调用(防复活);PUT 不存在租户写前拒绝;幽灵 id 过滤;name-only 幽灵行 404 分支被清除;Runtime 异常透传;技能清理被 await;放错位置的模块级测试移至文件末尾,恢复 9 个被吞的类方法(收集数 50 → 57)
test/backend/app/test_tenant_app.py 503/504 映射断言扩展进既有异常映射表
test/backend/database/test_tenant_config_db.py tenant_exists / get_existing_tenant_ids DB 层直测
frontend/tests/component/tenantDeleteFeedback.test.tsx 组件回归:失败保持弹窗+内联报错 / 成功关闭+刷新 / 404 幂等 / 刷新失败独立 warning
test-e2e/infra/automation/d3/scenarios/scenario_tenant_northbound_scenarios.py API-024 场景强化:GET 从未存在 id → 404;PUT 已删租户 → 404
test-e2e/cases/PW-RESOURCE-01/{case.yaml,execution.yaml,test.spec.ts} + d4/pages/resource.page.ts 步骤 9 强化:路由拦截一次 500 → 断言弹窗保持打开且内联错误可见 → 放行重试删除成功;补 acceptance obligations 与绑定
test-e2e/changes/bugs/*.yaml 新增 TENANT-DELETE-RESURRECTION-20261130 与 TENANT-DELETE-MODAL-FEEDBACK-20261130 两条 bug 变更记录(含根因更正与 traditional UT 选择器)

API 行为变化

操作 修复前 修复后
GET 已删/不存在的租户(SU) 200 + "Unnamed Tenant" 并写库 404,零写入
读取后再 DELETE 已删租户 200(级联重跑) 404
PUT 已删/不存在的租户 200 并写入名称行(幽灵行) 404,零写入
DELETE 期间 Runtime 不可用/超时 400(内部原因被包进 ValidationError) 503 / 504
SU 租户列表 / 配额统计 幽灵 id 计入 total 与 unmanaged 计数 排除

所有 get_tenant_info 调用方已逐一核对:group API 已有 404 臂、model/groups 服务自带 except Exception 兜底、租户列表循环已有 except NotFoundException。

存量数据说明

本 PR 不包含任何对存量数据的 SQL 修改:曾考虑在 v2.9.0_merged_migrations.sql 末尾追加一次性幽灵行清理段,因在部署期直接改写存量行有风险而撤销,迁移文件与 develop 保持完全一致。历史遗留的 name-only 幽灵行的收敛路径是入口级、显式触发的:SU 对幽灵 id 发起 DELETE /tenants/{id} 时,404 分支会顺手软删该残留行(幂等),不触碰任何其他数据。

评审意见处理

线程 意见 处理
T1 DongJiBao2001 await 后 list_skills() 异常会中止级联,留下部分删除状态 已改为清单失败仅跳过逐技能清理(与级联其余子步骤 best-effort 语义一致),并补 test_delete_skills_for_tenant_listing_failure_isolated
T2/T3 TiTi-iTiT 幽灵过滤 N+1 查询、错误面放大 get_existing_tenant_ids 单次 IN 查询 + 页内 verified_exists 跳过重复校验;失败面收敛为与 get_all_tenant_ids 同级的单查询
T4 TiTi-iTi 刷新失败被误报为删除失败、弹窗不关 两段 try:请求段失败保持弹窗+内联错误;收尾段失败独立 warning;404 幂等处理避免重试死循环
T5 TiTi-iTi name-only 幽灵行不可见且不可清理 404 分支入口级清理:SU 显式 DELETE 幽灵 id 时顺手软删该行(幂等);一次性存量数据迁移按风险考虑不做(本 PR 不改写任何存量数据)
T6 DongJiBao2001 新增测试吞掉 TestDeleteTenant 后续 9 个方法,pytest 不收集 已移至文件末尾,收集数恢复(50 → 57,含 8 个既有级联用例与本 PR 的 Runtime 透传用例)
T7 DongJiBao2001 refetchTenants() 默认不 reject,刷新失败提示不可达 页面回调改 refetchTenants({ throwOnError: true });组件测试以 reject 契约覆盖失败场景;创建/更新的收尾刷新同步隔离,避免刷新失败误报为操作失败

Testing

  • pytest test/backend/services/test_tenant_service.py — 57 passed(合入 T6 修复后恢复 9 个用例)
  • pytest test/backend/app/test_tenant_app.py — 48 passed
  • pytest test/backend/database/test_tenant_config_db.py — 32 passed
  • 前端组件测试 vitest 6/6 passed;tsc --noEmit 零错误;eslint 无新增问题(15 项均为 develop 基线存量)
  • python scripts/check_copyright.py 全部改动文件通过(顺带补齐 PW-RESOURCE-01/test.spec.ts 遗失的版权头)
  • validate_test_assets.py --phase design/implementation --generate --require-ut-change <两个 Change-ID> --require-acceptance-case PW-RESOURCE-01 全绿
  • deploy/images/build.sh --management 以本分支重建镜像成功(打包路径不受影响;撤销迁移后 deploy/sql 与 develop 一致)
  • 修复前复现证据(截图 + API/SQL 日志):证据评论,托管于 release assets(不入 git 历史)
  • 修复后本地栈探针(branch 代码热入 config 容器,gateway 5013,一次性租户,锚点未触碰):
    • create → GET → DELETE → GET:200 / 200 / 200 / 404;再 DELETE → 404;再 GET → 404
    • GET 从未存在 id → 404;PUT 已删租户 / 从未存在 id → 404
    • SU 列表不再出现幽灵租户,total 恰好 -1(被删探针本身);DB 零新增行(system_auto_create 行 0、活动幽灵行 0、never-exist id 0 行)
    • 守卫不变:非 SU 删除 403、匿名 401、DELETE 不存在 404
  • CI 全绿(14/14,含 test 与 codecov/patch;f42deb301 上 10:51 一次通过。附注:此前 7e0cbde 上的 test 失败属全仓库 self-hosted runner 并发互扰事故——同时段多分支套件在同台 workstation 上并发全部失败、失败 job 日志未上传,与代码无关)
  • API-024 / PW-RESOURCE-01 在本分支栈上的 Daily 执行(静态校验与探针不构成 Case 执行证据)

兼容性说明

  • GET / PUT 不存在租户从"200 写库"变为 404 —— GET 部分正是 API-024 断言的契约(断言未放宽,修复合入后 Case 应转 PASS);PUT 部分是本 PR 新增的防幽灵行守卫(原先 PR 描述声明保持旧行为,现已按缺陷登记纳入修复范围)
  • API-025 无需改动,重跑即可;PW-RESOURCE-01 断言强化后与本修复同批验证

遗留(不在本 PR)

  • RuntimeUpstreamError 透传(Runtime 返回 5xx 时仍走 400):可与 conversation_run.py 既有约定对齐后单独提 PR
  • 历史遗留的 name-only 幽灵行不做自动清理:如需收敛,可由 SU 对各幽灵 id 显式发起 DELETE(入口级清理),不引入部署期数据改写
  • 11-23 看板中 500 集群的失败归类为"环境/依赖问题",应按上文更正后的根因(元组 .upper(),已被 feat (memory): Add tenant and versioned Agent controls for automatic memory #4354 修复)重新归类

…ability to 503/504

- get_tenant_info no longer auto-backfills the TENANT_NAME config of a
  deleted tenant; a missing TENANT_ID identity row now answers 404, so a
  successfully deleted tenant can no longer be resurrected on read (API-024)
- delete_tenant validates existence via the identity row instead of the
  TENANT_NAME config, so stale name-only ghost rows are not deletable
- get_tenants_paginated excludes ids whose identity row is gone from both
  data and totals
- delete_tenant passes RuntimeServiceUnavailableError/RuntimeServiceTimeoutError
  through unmapped and the API endpoint answers 503/504 instead of wrapping
  them into a misleading ValidationError
- await the previously un-awaited skill cascade cleanup in delete_tenant
- the delete-confirmation modal stays open with inline error feedback on
  failure and shows loading during the request instead of silently closing
- remove a duplicated legacy import in the tenant API module

Regressions: get_tenant_info missing identity raises NotFoundException without
inserting any config; ghost ids filtered from tenant list; name-only ghost
tenant not deletable; runtime unavailable/timeout passthrough; 503/504 API
mappings; skill cleanup awaited; vitest component specs for dialog feedback.
@codecov

codecov Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Exercise the real tenant_exists query body (identity row present -> True,
absent or soft-deleted -> False) instead of only mocking it at the service
layer; resolves the Codecov patch-coverage gap on
backend/management/db/configuration/tenant.py.
charmingchi1 added a commit that referenced this pull request Nov 28, 2026
…ication evidence

Screenshots and captured API/SQL evidence for the three registered defects
(deleted-tenant resurrection, runtime-unavailable error mapping, silent
delete-modal failure) plus the fixed-frontend comparison frames. See
docs/evidence/pr-4473-tenant-delete/README.md for the frame-by-frame index.
@charmingchi1

charmingchi1 commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor Author

实测复现与验证证据(本地 develop 栈,2026-11-28)

环境与 PR 目标一致:未修复 develop 容器栈(gateway 5013 / 前端 3000),SU 锚点账号登录实操。所有租户均为一次性 repro-*,取证后已清理。证据文件托管于 release assets(不进入 git 历史,PR 评审/合并后可删除该 release)

缺陷①:已删除租户"复活"(API-024 根因)

API 实测序列(一次性租户 repro-resurrect-110834):

步骤 结果
DELETE /api/tenants/{id} 200
GET /api/tenants/{id} 200 + "tenant_name":"Unnamed Tenant" ← 复活
二次 DELETE /api/tenants/{id} 200(幽灵级联空跑仍报成功)

DB 铁证(tenant_config_t,删除 → GET 后查询):

 tenant_config_id |    config_key    |             config_value             | delete_flag |       created_by
------------------+------------------+--------------------------------------+-------------+----------------------
              115 | TENANT_ID        | 5bfaf6af-...                        | Y           | 6b2f815b-...
              116 | TENANT_NAME      | repro-resurrect-110834               | Y           | 6b2f815b-...
              117 | DEFAULT_GROUP_ID | 28                                   | Y           | 6b2f815b-...
              118 | TENANT_NAME      | Unnamed Tenant                       | Y           | system_auto_create
              119 | TENANT_NAME      | Unnamed Tenant                       | N           | system_auto_create  ← 复活行

(每 GET 一次已删租户就多一行 delete_flag=N 的 system_auto_create 回填行,可无限循环。)

帧 说明
A1 删除确认弹窗 A1 删除确认弹窗
A2 删除成功 A2 删除成功:toast「租户已删除」,列表已移除
A3 幽灵重现 A3(决定性) GET 已删租户后刷新,"Unnamed Tenant" 重回列表首位

缺陷②:Runtime 不可用时删除的错误映射

停止 nexent-runtime 容器后删除(未修复 develop 代码):

HTTP 400
{"message":"Failed to delete tenant: Runtime service is unavailable"}

状态码错位(应为 503)且内部原因外泄给用户。修复后(本 PR):503 + 通用文案 Runtime service is unavailable,无内部细节。

缺陷③:删除弹窗静默失败(同一 Runtime 停止条件,UI 实操)

帧 说明
B1 失败后1.5秒 B1 未修复前端:点击确定后 1.5s —— 弹窗已关闭,仅剩 3 秒 toast
B2 6秒后 B2(决定性) 6s 后:页面零失败痕迹,租户实际仍在列表 —— "静默失败"

修复验证(PR 分支前端生产构建,同一未修复后端)

帧 说明
C1 修复版弹窗 C1 修复版删除弹窗(删除图标已带「删除租户」可达名称 —— aria-label 修复生效)
C2 修复后失败反馈 C2(决定性对比 B2) 同样的删除失败:弹窗保持打开 + 内联红色 Alert「删除租户失败」,可重试/取消

旁证:C2 中历史幽灵 d3-delete-9d1f734e 仍在列表 —— 因为修复版前端连接的是未修复后端(列表过滤在 service 层)。这恰好证明前端修复独立生效,而幽灵过滤与 503 映射需本 PR 后端改动部署后生效。

文本证据原文:A3_sql-evidence.txt · B0_runtime-down-delete-response.txt

@charmingchi1
charmingchi1 force-pushed the dc-fix-tenant-delete-resurrection-1127 branch from 91a9a78 to 4424457 Compare November 28, 2026 03:49
@hhhhsc701

Copy link
Copy Markdown
Collaborator

backend/management/services/permission/identity/tenants.py:107

身份校验与名称回填分属不同数据库操作。读取通过校验后,如果并发删除先提交,读取仍可能在查不到名称时写回名称配置,并返回已删除租户的信息。建议移除读取路径的写入副作用,或让回填与删除在同一身份记录上加锁,并在事务内重新校验。

@hhhhsc701

Copy link
Copy Markdown
Collaborator

backend/management/services/permission/identity/tenants.py:224

租户列表在分页前为每个租户单独查询身份记录。即使只请求首页的 20 条数据,租户数为 1,000 时也会额外执行 1,000 次数据库查询。建议在数据库中筛选有效身份记录,并使用同一筛选条件计算总数和分页。

@hhhhsc701

Copy link
Copy Markdown
Collaborator

frontend/app/[locale]/resource-manage/components/UserManageComp.tsx:1006

确认按钮仅在删除请求发出后进入加载状态,失去了加载租户成员期间的提交限制。成员列表尚未显示时,管理员就能确认删除,无法先核对受影响用户。应在加载成员和提交删除两个阶段都禁用确认。


# 5b. Delete all skills, skill instances, and local skill files for the tenant
_delete_skills_for_tenant(tenant_id, deleted_by or "system")
await _delete_skills_for_tenant(tenant_id, deleted_by or "system")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

新增 await 会让 _delete_skills_for_tenant() 中未捕获的 skill_db.list_skills() 异常中止整个级联。此时用户、分组等清理已经执行,MCP、邀请码和租户身份行还没处理,接口会返回 400,但租户已处于部分删除状态。建议将技能清单读取移到任何不可回滚的清理之前,或把技能清理做成能明确记录失败并安全重试的步骤,并补上清单查询失败的用例。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已修复(81385f086):采用您建议的第二种方式——把技能清理做成"明确记录失败并安全继续"的步骤:list_skills() 失败时记录 warning 并跳过逐技能软删,级联继续执行(与级联中分组/知识库/MCP 等子步骤的 best-effort 语义一致),不再出现"部分删除 + 400"的状态。

未采用重排序方案(清单读取前移):属于级联结构性调整,且 fail-fast 语义与其余子步骤的 best-effort 惯例矛盾。已补用例 test_delete_skills_for_tenant_listing_failure_isolated(清单失败 → 不抛异常、逐技能清理跳过、实例清理仍执行)。

total = len(all_tenant_ids)
# Exclude ids whose identity row is gone (e.g. stale rows left behind by
# the earlier deleted-tenant read-backfill bug) from both data and totals.
existing_tenant_ids = [tid for tid in all_tenant_ids if tenant_exists(tid)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ 租户列表为过滤幽灵 id 逐条查库,单条查询失败会让整个列表接口 500

新增的幽灵 id 过滤写成 existing_tenant_ids = [tid for tid in all_tenant_ids if tenant_exists(tid)]:对 get_all_tenant_ids() 返回的每一个租户 id 各调用一次 tenant_exists。而本 PR 新增的 tenant_exists(backend/management/db/configuration/tenant.py)每次都用 with get_db_session() as session 新开一个会话做一次单行查询,因此列表接口由原来的 1 次查询退化为 1+N 次会话/查询;后续分页循环里又要对当前页每个 id 调 get_tenant_info(tid),而 get_tenant_info 开头同样新增了一次 tenant_exists 校验,同一批租户被重复校验,总往返约为 2N+1。更关键的是错误传播面被放大:这个列表推导没有任何异常隔离,只要其中任意一个 id 的 tenant_exists 查询抛异常(连接池耗尽、语句超时、单行锁等待),整个 get_tenants_paginated 直接失败,GET /api/tenants 从「少显示一条记录」变成整体 500,影响面远大于被过滤幽灵行本身。过滤语义是对的,但实现方式把可用性和查询次数都做了负向改动。

上下文代码:

    all_tenant_ids = [
        tid for tid in get_all_tenant_ids()
        if _is_displayable_tenant_id(tid)
    ]
    # Exclude ids whose identity row is gone (e.g. stale rows left behind by
    # the earlier deleted-tenant read-backfill bug) from both data and totals.
    existing_tenant_ids = [tid for tid in all_tenant_ids if tenant_exists(tid)]
    total = len(existing_tenant_ids)

修复方案:

# backend/management/db/configuration/tenant.py
from typing import Iterable, Set

def get_existing_tenant_ids(tenant_ids: Iterable[str]) -> Set[str]:
    """Batch variant: one round-trip for the whole id list."""
    ids = list(tenant_ids)
    if not ids:
        return set()
    with get_db_session() as session:
        rows = (
            session.query(TenantConfig.tenant_id)
            .filter(
                TenantConfig.tenant_id.in_(ids),
                TenantConfig.config_key == TENANT_ID,
                TenantConfig.delete_flag == "N",
            )
            .all()
        )
        return {row[0] for row in rows}

# backend/management/services/permission/identity/tenants.py
    existing_ids = get_existing_tenant_ids(all_tenant_ids)
    existing_tenant_ids = [tid for tid in all_tenant_ids if tid in existing_ids]
    total = len(existing_tenant_ids)

用一次 IN 查询批量取回存活身份行集合,把 1+N 次会话降为 1 次;过滤语义(data 与 total 同时排除幽灵 id)不变,同时把异常点收敛到单个查询,避免某一条记录的查询失败放大成整个列表接口 500。若希望更保守,可对该批量查询加 try/except 后回退为「不过滤」,保证列表接口可用性优先。


🤖 generated by github-code-review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已修复(81385f086):db 层新增 get_existing_tenant_ids(ids),一次 IN + config_key=TENANT_ID + delete_flag='N' 查询替代逐 id 会话;get_tenants_paginated 在分页切片前只调这一批查询,页内循环通过 get_tenant_info(..., verified_exists=True) 跳过重复存在性校验,接口查询量回到 1+1+page_size,连接压力同步消除。

关于可用性:批量化后异常点收敛为单个查询,失败面与改动前列表本就依赖的 get_all_tenant_ids 单查询一致(它失败同样导致 500),因此未加"失败回退为不过滤"——回退会重新把幽灵租户引入列表。回归用例断言:批量函数仅调用 1 次、tenant_exists 零调用、verified_exists=True 透传到页内查询。

total = len(all_tenant_ids)
# Exclude ids whose identity row is gone (e.g. stale rows left behind by
# the earlier deleted-tenant read-backfill bug) from both data and totals.
existing_tenant_ids = [tid for tid in all_tenant_ids if tenant_exists(tid)]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ 租户列表对全部租户 id 逐个调用 tenant_exists,引入 N+1 查询

get_tenants_paginated 在分页切片之前,对全部租户 id 做了一次列表推导逐个调用 tenant_exists(tid)。tenant_exists 每次都会通过 with get_db_session() 新开一次会话并执行一条 SELECT,因此一页数据的数据库往返次数与『租户总数』成正比,而不是与 page_size 成正比;随后循环里的 get_tenant_info 内部又会针对同一个 id 再调用一次 tenant_exists,单页查询量进一步翻倍。租户规模增长后该列表接口的延迟会线性恶化,且大量短连接会话会给连接池带来压力。建议在 db 层提供一次批量查询(IN + config_key=TENANT_ID + delete_flag=N),一次取回存在的租户 id 集合后在内存里做过滤。

上下文代码:

    existing_tenant_ids = [tid for tid in all_tenant_ids if tenant_exists(tid)]
    total = len(existing_tenant_ids)

    # Calculate pagination
    total_pages = (total + page_size - 1) // page_size if total > 0 else 1
    start_idx = (page - 1) * page_size

修复方案:

    # db 层新增批量查询:一次取回拥有有效身份行的租户 id
    existing_id_set = get_existing_tenant_ids(all_tenant_ids)
    existing_tenant_ids = [tid for tid in all_tenant_ids if tid in existing_id_set]
    total = len(existing_tenant_ids)

    # Calculate pagination
    total_pages = (total + page_size - 1) // page_size if total > 0 else 1
    start_idx = (page - 1) * page_size

在 management/db/configuration/tenant.py 增加批量函数,例如 select distinct tenant_id from tenant_config where tenant_id in (:ids) and config_key = TENANT_ID and delete_flag = 'N',用一次查询替代 N 次单行查询;同时可让 get_tenant_info 支持传入已获取的存在性结果,避免同一 id 被重复查询。


🤖 generated by github-code-review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已修复(81385f086):db 层新增 get_existing_tenant_ids(ids) 批量函数(一次 IN 查询,SELECT DISTINCT tenant_id WHERE tenant_id IN (...) AND config_key='TENANT_ID' AND delete_flag='N'),与您给出的修复建议一致;get_tenant_info 新增 verified_exists 参数供列表路径跳过同批 id 的重复校验。回归用例断言单页查询量与批量调用次数。

setDeleteModalVisible(false);
setDeletingTenant(null);
setTenantUsers([]);
} catch (error) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ 删除成功后的列表刷新失败会被当作删除失败,弹窗不关闭并可重复提交删除

handleDeleteConfirm 的 try 块同时包含 deleteTenant 请求与其后的列表刷新、选中态清理,catch 里统一用 tenantResources.tenantDeleteFailed 这段『删除失败』文案兜底任何异常。当删除已经成功、但后续刷新(或选中态清理)抛错时,用户看到的是删除失败的内联报错,而且本次改动把 setDeleteModalVisible(false) 移进了 try,弹窗因此保持在打开状态;用户再次点击确认会重新发起 DELETE,此时租户已被删除,接口按本 PR 的新语义返回 404,于是用户被永久困在同一个错误提示里无法脱身。建议把『删除请求』与『删除后的收尾/刷新』拆成两段 try,删除成功即刻关闭弹窗,刷新失败单独提示。

上下文代码:

      }

      // Only a successful delete closes the modal.
      setDeleteModalVisible(false);
      setDeletingTenant(null);
      setTenantUsers([]);
    } catch (error) {
      // Keep the modal open with inline feedback so the failure is visible
      // and the user can retry or cancel instead of a silent dismiss.
      setDeleteError(
        getTenantResourceLimitMessage(error, t) ||
          t("tenantResources.tenantDeleteFailed")
      );

修复方案:

      await deleteTenant(deletingTenant.tenant_id);
      message.success(t("tenantResources.tenants.deleted"));

      // 删除已成功,立即收敛弹窗状态,避免刷新异常导致重复提交
      setDeleteModalVisible(false);
      setDeletingTenant(null);
      setTenantUsers([]);

      try {
        if (onTenantsRefetch) {
          await onTenantsRefetch();
        }
        if (selected === deletingTenant.tenant_id && onSelect) {
          onSelect("");
        }
      } catch (refreshError) {
        // 租户已删除完成,刷新失败只需提示,不回滚弹窗
        console.error("Failed to refresh tenants after delete", refreshError);
      }
    } catch (error) {
      setDeleteError(
        getTenantResourceLimitMessage(error, t) ||
          t("tenantResources.tenantDeleteFailed")
      );
    } finally {

把『删除请求』和『删除后的刷新/选中态清理』分离到两个 try:删除成功就先关闭弹窗并清空状态,刷新失败单独处理且不再复用『删除失败』文案,从而既保留失败可重试的内联反馈,又避免已成功删除后用户被误导并重复发起请求。


🤖 generated by github-code-review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已修复(81385f086):handleDeleteConfirm 拆为两段 try——

  1. 请求段只包含 deleteTenant:非 404 失败保持弹窗打开 + 内联错误(现有行为);ApiError.code === 404 按幂等已删除处理:关弹窗 + "租户已被删除"提示(新键 tenantResources.tenants.alreadyDeleted)+ 仍触发刷新,用户不会再被困在 404 重试循环里。
  2. 收尾段(onTenantsRefetch + 选中清理)独立隔离:失败单独 message.warning(新键 tenantResources.tenants.refreshFailed),不再与"删除失败"文案混用。

组件用例覆盖:删除成功但刷新失败 → 弹窗已关 + 仅显示刷新失败提示;404 → 关弹窗 + 已删提示 + refetch 被调用。

if not name_config:
# Validate tenant exists via its identity row; a stale name-only config row
# (e.g. left behind by an earlier read-backfill bug) must not make deletion pass.
if not tenant_exists(tenant_id):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ 历史遗留的 name-only 幽灵租户行在删除入口改判后既不可见也不可清理

删除入口的存在性判据由 TENANT_NAME 行改为 TENANT_ID 身份行后,凡是此前因读取回填 bug 残留的 name-only 行(代码注释本身就承认这类行存在)都会一律返回 404;同时 get_tenants_paginated 的新过滤又把这些 id 从列表的 data 与 total 中剔除。结果是这批脏数据在管理界面上完全不可见,也无法再通过 DELETE 接口被级联软删(改动前它们能通过 TENANT_NAME 判据进入级联清理),只能靠人工 SQL 处理,脏行会长期滞留在 tenant_config 表中;而 get_all_tenant_ids() 仍然返回这些 id,其它依赖它的路径(统计、配额、northbound 等)可能继续把幽灵租户计入。本次改动只做了"遮蔽"而没有配套的一次性清理动作。

上下文代码:

    # Validate tenant exists via its identity row; a stale name-only config row
    # (e.g. left behind by an earlier read-backfill bug) must not make deletion pass.
    if not tenant_exists(tenant_id):
        raise NotFoundException(f"Tenant {tenant_id} does not exist")

修复方案:

    if not tenant_exists(tenant_id):
        # 身份行缺失但存在 name-only 残留时,说明这是旧回填 bug 产生的幽灵行:
        # 记录并顺手清理,避免脏行永久滞留且不可见。
        ghost_name_config = get_single_config_info(tenant_id, TENANT_NAME)
        if ghost_name_config:
            logger.warning(
                f"Purging ghost tenant {tenant_id}: TENANT_NAME row without identity row"
            )
            delete_config_by_tenant_config_id(ghost_name_config.get("tenant_config_id"))
        raise NotFoundException(f"Tenant {tenant_id} does not exist")

保持以身份行作为真实租户的唯一判据(不回退到复活语义),但在 404 分支里识别并清理 name-only 残留行,或改为随 PR 附带一次性迁移脚本 UPDATE/软删 tenant_config 中没有 TENANT_ID 身份行的 TENANT_NAME 行,让历史脏数据有明确的收敛路径,同时保证 404 幂等性不变。


🤖 generated by github-code-review

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已修复(81385f086):双重处理,正是您给出的两个方向的组合——

  1. 入口清理:delete_tenant 的 404 分支先识别 name-only 残留行(get_single_config_info),存在则 logger.warning("Purging ghost tenant ...") 并软删该行后再抛 NotFoundException(幂等)。
  2. 一次性迁移:deploy/sql/migrations/v2.10.0_merged_migrations.sql 软删所有无身份行的 TENANT_NAME 行(NOT EXISTS 写法规避 NULL 陷阱、幂等、含 updated_by='system' 审计)。存量脏数据随部署清理后 get_all_tenant_ids 不再返回幽灵 id,统计/配额等依赖路径随之自愈。

迁移谓词已在本地库用插入的幽灵行验证精确命中。回归用例:404 分支断言幽灵行被软删;无幽灵行时不产生任何写。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

跟进说明(f42deb301):按存量数据风险评估,原计划追加在 v2.9.0_merged_migrations.sql 的一次性幽灵行清理迁移已撤销——不在部署期改写任何存量行,该文件与 develop 保持一致。v2.10.0 迁移文件同样不存在。入口级清理保留:SU 对幽灵 id 显式发起 DELETE /tenants/{id} 时,404 分支会顺手软删该 name-only 残留行(幂等,不触碰其他数据)。PR 描述已同步更新。

Backend:
- get_tenants_paginated filters ghost ids via one batched
  get_existing_tenant_ids IN-query instead of per-id tenant_exists
  sessions, and the page loop skips the per-id re-check through
  verified_exists; single-query failure surface matches the
  pre-existing get_all_tenant_ids dependency
- get_tenant_info is now read-only: the TENANT_NAME auto-backfill
  (and _ensure_tenant_name_config) is removed, so a concurrent delete
  can no longer be resurrected by a read; callers updated
- delete_tenant purges leftover name-only ghost rows before raising
  the idempotent 404; one-time migration v2.10.0 soft-deletes
  historical ghost rows the same way
- _delete_skills_for_tenant isolates the skill listing failure so it
  only skips skill cleanup instead of aborting the cascade halfway

Frontend:
- handleDeleteConfirm splits the delete request from the post-delete
  refresh: a refresh failure warns on its own and never masquerades
  as a delete failure, and an idempotent 404 closes the dialog with
  an already-deleted notice instead of trapping the user in a retry
  loop
- the confirm button is disabled while tenant members are still
  loading so admins cannot confirm before seeing affected users

Tests: batched filtering and verified_exists assertions, read-only
name semantics, ghost purge on 404, skill listing isolation, refresh
failure/404/disable component specs; i18n keys for the new messages.
@charmingchi1
charmingchi1 force-pushed the dc-fix-tenant-delete-resurrection-1127 branch from 259a7db to 81385f0 Compare November 28, 2026 08:15
@charmingchi1

Copy link
Copy Markdown
Contributor Author

@hhhhsc701 感谢三条意见,均已在 81385f0 修复,逐条对应:

1. 读取路径写入副作用 / 并发竞态(tenants.py 身份校验处)
采纳您建议的第一种方式:移除读取路径的写入副作用。get_tenant_info 不再回填 TENANT_NAME(_ensure_tenant_name_config 已删除),名称缺失返回空值(前端列表已有 unnamed 兜底)。GET 全链路纯只读,与并发删除的写竞态结构性消失,无需行锁。补充:v1 迁移已为存量租户回填名称行,回填分支实际只服务异常数据;update_tenant_info 写路径重建(PUT)保留。回归用例断言名称缺失时 insert_config 零调用。

2. 租户列表逐租户查询(分页前身份过滤)
按您的建议在数据库层完成筛选:新增 get_existing_tenant_ids(ids) 一次 IN 查询取回有效身份行集合;列表的 data 与 total 基于同一集合计算(保持原排序),页内循环通过 get_tenant_info(..., verified_exists=True) 跳过重复存在性校验。租户规模上千时接口也不再产生与总数成正比的查询。

3. 成员加载期间可确认删除(弹窗确认按钮)
两个阶段都受限:成员加载期禁用(okButtonProps={{ disabled: deleteLoading }},弹窗显示 Spin),请求提交期转 loading(confirmLoading)。组件用例覆盖加载中 disabled、加载完成后恢复。

同时已一并处理 DongJiBao2001 与 TiTi-iTiT 的其余意见(技能清单异常隔离、404 幂等自愈、幽灵行入口清理 + 一次性迁移 v2.10.0),详见各线程回复。CI 已在新 head 重新触发。

@DongJiBao2001 DongJiBao2001 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

检视意见见行内评论。



@pytest.mark.asyncio
async def test_delete_skills_for_tenant_listing_failure_isolated():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

这个新增测试在 TestDeleteTenant 中间退到了模块级,后面 9 个仍缩进四格的测试方法因此变成了该函数的局部函数。pytest 不会收集它们,包括本 PR 的 Runtime 超时/不可用异常透传和既有的组、模型、Agent 等级联测试。请把新增测试移到类末尾之后,或把它作为类方法并加入 self,再确认这些用例能够被收集。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已修复(7e0cbdea7):test_delete_skills_for_tenant_listing_isolated 已整体移至文件末尾(TestCheckTenantNameExists 之后),其后 9 个方法回到 TestDeleteTenant 类级。--collect-only 收集数 50 → 57,包含既有 8 个级联用例(组/模型/Agent/MCP/邀请码等)与本 PR 的 test_delete_tenant_runtime_unavailable_passthrough(2 个参数变体);本地实跑 57 passed。

@DongJiBao2001 DongJiBao2001 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

检视意见见行内评论。

setDeletingTenant(null);
setTenantUsers([]);
console.error("Failed to refresh tenant list after delete:", error);
message.warning(t("tenantResources.tenants.refreshFailed"));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

实际页面传入的 onTenantsRefetch 返回 TanStack Query 的 refetchTenants()。它默认把网络失败放在结果的 isError 中,Promise 仍然 resolve,所以这里的刷新失败提示不会出现,已删除租户可能继续留在旧列表里。现有测试用 mockRejectedValueOnce 覆盖了生产回调默认不会返回的行为。建议传 refetchTenants({ throwOnError: true }) 或显式检查 isError,再用实际的回调契约覆盖失败场景。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

已修复(0365e03c):页面传入的 onTenantsRefetch 改为 refetchTenants({ throwOnError: true }),刷新失败时 reject,refreshFailed 提示在真实回调契约下可达;组件测试中 mockRejectedValueOnce 的 refetch 即为该契约的直接建模。同时把创建/更新的收尾刷新隔离成独立 try(刷新失败仅 warning,不再误报为创建/更新失败),与删除流的两段式语义一致。

charmingchi1 and others added 5 commits November 30, 2026 09:44
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…e ghost purge into the v2.9.0 bundle

- update_tenant_info now requires a live TENANT_ID identity row before any
  write, so PUT /tenants/{id} answers 404 on deleted or never-existing
  tenants instead of inserting a name-only ghost row.
- The one-time ghost-name purge moves from a new v2.10.0 bundle to a section
  appended to v2.9.0_merged_migrations.sql, reusing the packaged migration
  path without a Dockerfile change; VERSION returns to v2.9.0.
- The page-level refetch callback now rejects on refresh failure
  (refetchTenants({ throwOnError: true })), making the dedicated
  refresh-failure feedback reachable with the real callback contract.
- Create/update bookkeeping isolates the post-mutation refresh: a refresh
  failure warns instead of masquerading as a failed create/update, matching
  the delete flow's two-stage confirmation.
…essions and register bug records

- Move test_delete_skills_for_tenant_listing_failure_isolated out of the
  middle of TestDeleteTenant: the nine four-space defs after it were nested
  inside it and never collected (57 tests collected again, including the
  existing cascade tests and the Runtime passthrough regression).
- API-024's D3 scenario now also asserts a 404 read on a never-existing id
  and a 404 rename on the deleted tenant, guarding the resurrection fix.
- PW-RESOURCE-01 step 9 injects one failed DELETE through the page object,
  asserts the modal stays open with the inline error, and completes the
  deletion on retry; acceptance obligations and bindings were added.
- Register TENANT-DELETE-RESURRECTION-20261130 and
  TENANT-DELETE-MODAL-FEEDBACK-20261130 bug change records with traditional
  UT selectors.
The appended section rewrote stored rows at deployment time (soft-deleting
TENANT_NAME rows without a live identity row), which is a legacy-data risk
the maintainers decided not to take. Restore v2.9.0_merged_migrations.sql
to its develop state; the file drops out of the PR diff entirely.

Ghost rows are still cleared through the existing delete 404 entry path
when a super administrator explicitly deletes the ghost id, and the bug
record now states that no migration in this change touches stored data.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants