diff --git a/docs/architecture/12-multi-tenant.md b/docs/architecture/12-multi-tenant.md index b9ec6c5962..97a462bd44 100644 --- a/docs/architecture/12-multi-tenant.md +++ b/docs/architecture/12-multi-tenant.md @@ -402,9 +402,10 @@ SUPPORTED_SHAREABLE_TYPES: set[str] = {'llm_server'} v3.1.0 F005 起,子租户的系统模型设置**不再读时回落 Root**,这个字段对系统模型也没有效果了。它仍被 `source_read_target_repository`、`model_name_resolution_repository` 和 `resource_share_service` 读取,列保留。 -### 另外两条"像共享实则不是"的路径 +### 另外三条"像共享实则不是"的路径 - **系统模型配置是快照**(v3.1.0 F005 起):挂载子租户时,`asnapshot_child_model_defaults` 把 Root 的五个设置复制成子租户自己的行:保留子租户能用的模型,空位从它能用的模型中自动填,仍为空的槽位在挂载响应 `model_settings_pending` 中返回。此后两边不同步。存量子租户由运维脚本 `scripts/snapshot_child_model_defaults.py` 补一次快照 +- **共享模型的价格是副本**(v3.1.0 F005 起):子租户新拿到 Root 的模型时,`initialize_shared_models` 在共享事务内同时补默认可见范围和价格副本(表 `llm_model_tenant_pricing`,只补缺失)。子租户内计费、倍率和价格表经 `tenant_pricing.aread_effective_pricing` 只读自己的副本,不回退 Root;子租户编辑价格写副本。Root 和自有模型的价格仍在 `llm_model.config["pricing"]` - **内置工具是复制不是共享**:`acopy_root_builtin_tools_to_tenant` 给子租户建自己 tenant_id 的副本行 --- diff --git "a/docs/customer-guides/\345\244\232\347\247\237\346\210\267\344\272\247\345\223\201\344\275\277\347\224\250\350\257\264\346\230\216.md" "b/docs/customer-guides/\345\244\232\347\247\237\346\210\267\344\272\247\345\223\201\344\275\277\347\224\250\350\257\264\346\230\216.md" index fe0367068d..9c49b915d8 100644 --- "a/docs/customer-guides/\345\244\232\347\247\237\346\210\267\344\272\247\345\223\201\344\275\277\347\224\250\350\257\264\346\230\216.md" +++ "b/docs/customer-guides/\345\244\232\347\247\237\346\210\267\344\272\247\345\223\201\344\275\277\347\224\250\350\257\264\346\230\216.md" @@ -198,6 +198,8 @@ uv run alembic upgrade head - 它的系统默认模型设置中,使用这个模型服务的项会被清空,不会自动换成其他模型; - 它的应用、工作流、助手和知识空间中使用这些模型的数量和名称。这些配置不会被修改,但调用时会失败,需要该机构自己更换模型。 +**模型价格**:子租户第一次拿到某个模型服务时,会按总部当时的价格复制一份。此后子租户管理员可以在「用户可选模型」的价格列中修改本机构的价格,只影响本机构的积分倍率和积分扣减;总部修改价格不影响已有的子租户。取消共享后再重新共享,子租户原来的价格保留。总部本身没有设置价格的模型,在子租户中显示「价格缺失」,由子租户管理员填写。 + 点「取消」不做任何修改。 **新建子租户**时,「标记为子租户」弹窗中可以勾选要共享给它的模型服务,默认不勾选。之后也可以在模型服务的配置中修改。 diff --git a/features/v3.1.0/005-tenant-model-share-snapshot/design.md b/features/v3.1.0/005-tenant-model-share-snapshot/design.md index e3cc96c8b5..31a1c303cb 100644 --- a/features/v3.1.0/005-tenant-model-share-snapshot/design.md +++ b/features/v3.1.0/005-tenant-model-share-snapshot/design.md @@ -2,7 +2,7 @@ **关联**: [spec.md](./spec.md) · [tasks.md](./tasks.md) **版本**: v3.1.0 -**最后更新**: 2026-12-03 +**最后更新**: 2026-12-03(追加价格副本) --- @@ -15,7 +15,7 @@ - **C3 多租户**:快照和清理都要写其他租户的 `tenant_system_model_config` 行。写入必须在目标子租户的 tenant context 中进行,不能用 `bypass_tenant_filter` 直接写。现有 `current_model_default_tenant` 在 bypass 状态下会拒绝写入。 - **C4 权限**:共享事实只由 permission owner(`ModelSharingProjectionApplication`)写 FGA。本特性只改 `after` 集合怎么算,不新增直写 tuple 的路径。 -- **C2 双库**:不新增表和列,没有 DDL。存量快照是运维脚本,不放进 Alembic revision。 +- **C2 双库**:系统模型快照不新增表和列。价格副本(§2.5)新增一张表 `llm_model_tenant_pricing`,Alembic revision 只做 DDL,类型用项目已有的 `JsonType` / `BigInteger`,在 MySQL 和 DM8 上都要跑通。存量快照和存量价格复制都是运维脚本,不放进 Alembic revision。 - **C8 多节点**:快照和清理都是同步的 HTTP 请求内写库,不依赖本地文件或进程内状态。 - 共享操作的失败恢复(F025 AC-12、AC-13)继续有效:恢复者可以不是原操作者,恢复按冻结的 `after` 收尾。 @@ -124,6 +124,67 @@ - **被否方案**:resolver 保留 Root 回落一个版本作为过渡。这样两种语义会并存,页面提示也得保留,用户明确要去掉。 - **何时重新考虑**:如果客户环境不能在启动服务前运行脚本,改为在 API 启动钩子里单次执行,并加分布式锁防止多节点重复执行(C8)。 +### 决策 10:价格副本存在哪里(§2.5) + +- **现状**:价格只存在模型行的 `llm_model.config["pricing"]`。Root 共享的模型只有 Root 这一行,所以子租户读到的就是 Root 的价格,`save_model_pricing` 对子租户直接抛 `LLMModelSharedReadonlyError`。 +- **备选**: + - A. 沿用图片能力的做法,在全局 `config` 表按 `llm_price:{tenant}:{model}` 存键值。 + - B. 在 `dsh_model_visibility`(每个租户每个模型一行)加 `pricing` 列。 + - C. 新表 `llm_model_tenant_pricing`:`tenant_id`、`model_id`、`pricing`(JSON,结构同 `ModelPricing`)、`updated_by`、`create_time`、`update_time`,唯一键 `(tenant_id, model_id)`。 +- **选定**:C。 +- **原因**:A 不需要 DDL,但键值表没有租户列,C3 的自动过滤管不到;按租户列出价格也只能用 `LIKE` 前缀查询。B 让价格依赖 DSH 的可见范围行,而可见范围行可以被管理员删改,价格的生命周期也会跟着变。C 有 `tenant_id` 列,子租户上下文里的读取由 C3 自动过滤;它和价格的现有结构一致,只多了租户维度。 +- **适用范围**:只存「Root 的模型 × 子租户」。Root 自己的价格和子租户自有模型的价格仍然存在 `llm_model.config["pricing"]`,写路径不变。 +- **代价**:需要一个 DDL revision(C2);模型删除后副本留成孤儿行(见 §5 坑 8)。 + +### 决策 11:什么时候复制价格 + +- **选定**:在 F025 已有的「新接收方初始化」位置同时复制价格。现在凡是子租户新拿到 Root 的 LLM 模型,都会在提供方锁住的同一个事务里调用 `initialize_shared_model_visibility(child_ids, model_ids)`,它只给缺失的行补默认可见范围。新增 `initialize_shared_model_pricing(session, child_ids, model_ids, actor_user_id)`,规则相同: + 1. 在同一个 session 里读 Root 模型行的 `config["pricing"]`。 + 2. 对每个 `(child, model)`,已有副本就跳过(AC-24、AC-28)。 + 3. Root 价格缺失或损坏时不写副本,交给 AC-29 处理。 + 4. 否则把 Root 价格原样写成副本,`revision` 从 1 开始。 +- 把这两个调用合成 `model_sharing_lifecycle.initialize_shared_models(...)`,替换现有的全部调用点,保证以后新增的初始化路径不会只做一半: + - `ModelSharingApplication._finish_sharing`(清单新增子租户,包括挂载时勾选,AC-24); + - `initialize_sharing_update`(Root 带共享清单保存提供方,且同时新增模型,AC-25); + - `initialize_added_provider_models`(Root 在已共享的提供方下新增模型,AC-25); + - `model_deletion` 受保护更新路径,它冻结的初始化收据也在 `_finish_sharing` 里消费。 +- **为什么不在读价格时懒复制**:懒复制等于「没有副本就读 Root」,这正是 AC-27 要去掉的同步语义。 +- **取消共享**:不删副本(AC-28),F005 的整理函数 `aprune_unshared_model_defaults` 不碰价格。 +- **代价**:写副本是跨租户写(Root 请求写子租户行)。做法和 `SharedModelVisibilityRepository` 一样:在 Root 的提供方事务里用 `bypass_tenant_filter`,并显式写入 `tenant_id`。 + +### 决策 12:读价格统一走一个函数 + +- **选定**:新增 `llm/domain/pricing/tenant_pricing.py`,提供 `aread_effective_pricing(model, tenant_id) -> dict | None`: + - `model.tenant_id == tenant_id`(自有模型,或 Root 读 Root)时,返回 `model.config["pricing"]`; + - 否则(子租户读 Root 共享的模型)返回副本表中 `(tenant_id, model.id)` 的 `pricing`,没有就返回 `None`。不回退到 Root(AC-27、AC-29)。 +- `tenant_id` 取当前请求的 `get_current_tenant_id()`,也就是发起调用的用户所在租户。下面这些读取 `config["pricing"]` 的地方全部改用它: + +| 位置 | 用途 | +|---|---| +| `LLMService.read_model_pricing`(`ModelPricingRepository.read`) | 日常模式和深度研究开始时冻结价格 | +| `dsh/domain/services/model.py` 的 `billing_snapshot` | DSH 对话调用冻结价格 | +| `dsh/domain/services/model.py` 的 `pricing_hint` | 工作台模型列表的积分倍率 | +| `pricing.read_hint_context`、`save_credit_settings` | 基准模型价格 | +| `pricing.admin_model_pricing` | 管理端价格表 | + +- `ModelPricingRepository.read` 现在只按模型 id 读,改为接收租户参数,并按上面的规则分流。计费仍然每次直读数据库,不经过 60 秒的 `LLM_CACHE`(F016 决策 15 不变)。 + +### 决策 13:子租户编辑价格 + +- **选定**:`PUT /api/v1/llm/models/{id}/pricing` 不改路径,也不改请求体。`save_model_pricing` 按模型的归属分流: + - Root 的模型、当前不是 Root:确认该模型的提供方在 `aget_shared_server_ids_for_leaf(tenant)` 里,否则抛 `LLMModelNotAccessibleError`。然后在副本行上加锁(`SELECT … FOR UPDATE`,没有行时插入)。用现有的 `resolve_model_pricing(server_type, model_name, incoming, existing=副本)` 计算新价格,`revision` 比对和来源判定(CATALOG / MANUAL / DEFAULT)都沿用原逻辑。 + - 其他情况走原来的 `asave_model_pricing`。 +- 去掉子租户对 Root 模型的 `LLMModelSharedReadonlyError` 分支。`admin_model_pricing` 对能看到的行一律返回 `can_edit=true`。前端的 `PriceSummaryCell` 已经按 `can_edit` 显示「编辑价格」,不需要改;「Root 共享价格 · 只读」只在 `can_edit=false` 时出现,以后实际不会出现。 +- 两个管理员同时首次编辑同一个缺失副本时,后插入的一方撞唯一键,返回 `ModelPricingConflictError`,前端已有「价格已被修改,请刷新」的处理。 + +### 决策 14:存量价格复制 + +- **选定**:在 `scripts/snapshot_child_model_defaults.py` 里增加价格这一步。不新开脚本,上线步骤仍然只有一条命令。 + - 对每个子租户(包括停用的),读取它当前被共享的 Root 提供方下的 LLM 模型,给没有副本的模型复制 Root 价格。 + - Root 价格缺失的模型单独列出(AC-30)。 + - 预览和 `--apply` 的语义、幂等性和脚本原有部分一致。 +- 已经跑过旧版脚本的环境(如 test 116),部署新版后再跑一次 `--apply`:设置项部分会复制 0 项,价格部分做首次复制。 + ## 4. 系统现状(改动后) ### 4.1 数据流 @@ -136,6 +197,7 @@ 走受保护更新路径时(同时删了模型),`model_deletion._prepare_sharing` 用同一个函数计算 `after`,收尾后同样调用整理。 - **预览**:`POST /api/v1/llm/{id}/sharing-preview` → 计算被移除的子租户 → 对每个子租户执行 dry-run 整理 + 引用计数 + 名称披露。 - **挂载**:见决策 8。 +- **价格**:新接收方初始化(决策 11)写入副本;计费、倍率和价格表经 `aread_effective_pricing` 读取(决策 12);子租户编辑写副本(决策 13)。 - **运行时读默认模型**:`ModelDefaultReadRuntime` → `ModelDefaultRepository.aresolve`。只读本租户自己的行。 ### 4.2 对外契约变化 @@ -151,6 +213,8 @@ | 五个系统模型 GET 的 envelope | 字段不变,`inherited_from_root` 恒为 false | | `GET /api/v1/llm?root_only=true` | 新增,仅全局超管:列出全部 Root 提供方(挂载弹窗的提供方选择)。`only_shared` 不变 | | `POST /api/v1/departments/{id}/mount-tenant` | 请求新增 `shared_server_ids`,响应新增 `model_settings_pending: [{key, slots}]` | +| `PUT /api/v1/llm/models/{id}/pricing` | 路径和请求体不变;子租户对 Root 共享模型不再返回「只读」错误,而是写本租户的价格副本 | +| `GET /api/v1/dsh/admin/model-pricing`(DSH 价格表,`admin_model_pricing`) | 字段不变;子租户中 Root 共享模型的 `pricing` 取副本,`can_edit` 为 true | ### 4.3 模块职责 @@ -159,6 +223,7 @@ | `llm/application/model_sharing.py` | 计算清单命令的 `after`、digest,恢复,完成后触发整理 | 不直接写其他租户的配置 | | `llm/application/child_model_snapshot.py`(新) | 快照、整理(含 dry-run)、子租户可用模型集合 | 不写 FGA | | `llm/application/model_sharing_preview.py`(新) | 预览:整理 dry-run + 引用计数 + 名称披露 | 不写任何数据 | +| `llm/domain/pricing/tenant_pricing.py`(新) | 价格副本的初始化、读取分流、子租户写入 | 不改 Root 和自有模型的价格存储 | | `tenant/domain/services/tenant_mount_service.py` | 挂载时按所选 server 共享,然后快照 | 不再查询"全部开启的提供方" | ## 5. 已知坑 / 反直觉事实 @@ -171,6 +236,8 @@ | 4 | 停用租户时不撤销 `shared_with` | 以为要在重新启用时补授权,结果重复授权或误撤 | 决策 2:保存时保留停用租户的授权;删除 `areconcile_child` | | 5 | `aresume` 只认已有计划行的 provider | 挂载重试会漏掉还没开始共享的 provider | 决策 8:重试时重新提交 `shared_server_ids` | | 6 | 已有本地行但 `value` 为 NULL 的子租户,过去会继承 Root | 升级后这类租户突然变成空配置 | 迁移脚本把"value 为空"也当作没有本地行,同样做快照 | +| 7 | 计费读价格有多处入口,有的读 `model.config` 字典,有的经 `read_model_pricing` 直读数据库 | 只改一处,子租户的对话按 Root 价格扣积分,价格表却显示副本价格 | 决策 12 的表列出全部入口;测试用 grep 守住 `config["pricing"]` 的读取点 | +| 8 | 删除模型不清理价格副本 | 以为孤儿行会被新模型复用 | 模型 id 自增不复用,孤儿行不会被读到;不额外清理 | ## 6. 对外契约与依赖 @@ -192,6 +259,7 @@ - **后端**:使用 native SQLite 和隔离 HTTP 的现有测试模式(`test/llm/`、`test/tenant/`、`test/knowledge_unification/`)。 - 改写 F025 中与继承相关的测试,清单见 plan 第 5 节,删除恢复继承相关用例。 - 新增:清单的增减、停用租户保留授权、非法 id 被拒、清单 digest 的恢复、旧 bool 计划的恢复、整理覆盖五个栏目的各种形态、dry-run 与实际执行结果一致、快照三步规则与待补充清单、重试不覆盖已写入的栏目、迁移脚本预览不写入与 `--apply` 幂等。 +- **价格(§2.5)**:初始化只补缺失、Root 缺价不写副本;读取分流(自有模型、Root 读 Root、子租户读副本、无副本返回 None 且不回退);子租户编辑的 revision 冲突、未共享模型被拒、首次插入的并发冲突;取消共享保留副本、重新共享不覆盖;计费冻结价格和积分倍率在子租户中用副本;脚本的价格步骤在预览时不写入、`--apply` 幂等。 - **前端**:vitest 覆盖 `SharedTenantsField`、`SharingImpactDialog`、`MountTenantDialog`。 - **真实环境**:114 部署分支后,用非 admin 的子租户管理员账号按 plan 中的端到端 1–5 步验证。另外在 DM8 环境上跑一次迁移脚本(C2)。 - **日志**:整理失败时 `logger.exception`,记录 `server_id / child_id`;快照的待补充清单写进挂载审计的 metadata。 @@ -207,4 +275,5 @@ |---|---|---| | 2026-12-03 | 初版 | spec 确认 | | 2026-12-03 | 决策 2 允许选中集合包含当前已共享的停用子租户;`GET /api/v1/llm` 新增 `root_only`,供挂载弹窗列出全部 Root 提供方 | 前端回显清单时会带回停用租户的 id;挂载弹窗原来用的 `only_shared` 只列已共享的提供方 | +| 2026-12-03 | 追加决策 10–14(共享模型的价格副本);C2 允许新增 `llm_model_tenant_pricing` 表 | 追加需求 spec §2.5(AC-24–AC-30) | | 2026-12-03 | 决策 4 改为只删不增的写入;决策 5 的披露风险改为读代码核对;§4.2 补充 `ModelSharingStatusService` 的保留范围 | 实现中发现 `asave` 会被下线模型拦住;`ModelSharingStatusService` 仍被 beta1 升级修复脚本使用 | diff --git a/features/v3.1.0/005-tenant-model-share-snapshot/spec.md b/features/v3.1.0/005-tenant-model-share-snapshot/spec.md index fdd68ee1a4..aaaa4acfe1 100644 --- a/features/v3.1.0/005-tenant-model-share-snapshot/spec.md +++ b/features/v3.1.0/005-tenant-model-share-snapshot/spec.md @@ -2,7 +2,7 @@ > **本文档定位 — 纯 What。** How 见 [design.md](./design.md)(待写)。 -**关联需求**: 2026-12-03 用户需求「共享给子租户支持指定子租户」「子租户系统模型设置体验优化」 +**关联需求**: 2026-12-03 用户需求「共享给子租户支持指定子租户」「子租户系统模型设置体验优化」;追加需求「子租户管理员自行设置共享模型的价格」(2026-12-03,§2.5) **优先级**: P1 **所属版本**: v3.1.0 **依赖**: F025-tenant-system-models(v3.1.0-beta1,本特性取代其 AC-01、AC-04 及 AC-12 中的共享覆盖查询) @@ -14,6 +14,7 @@ > - 取消共享前展示影响并要求确认;确认后清理该子租户系统模型设置中失效的引用。 > - 子租户创建时把 Root 系统模型设置复制为自己的初始配置,之后与 Root 不再同步。 > - 存量子租户上线时做一次同规则的复制。 +> - (追加)Root 共享给子租户的模型,价格在共享时复制一份给子租户,之后由子租户管理员自己维护。 > - 删除依赖「继承」和「全部共享」的界面:共享覆盖、检查子租户继承影响、恢复继承、尚未共享给本租户提示。 > - **本次明确排除**: > - 工作台配置(日常模式工具等)的 Root 继承:它不属于五个系统模型栏目,另行处理。 @@ -29,6 +30,7 @@ - **B. Root 超级管理员**:我希望取消共享前看到哪些子租户、哪些配置和应用会受影响,以便判断能否取消、并提前通知对方。 - **C. Root 超级管理员**:我希望挂载子租户时就选好共享哪些提供方,并在创建完成时知道它还有哪些系统模型需要补充,以便新租户开通后立即可用。 - **D. 子租户管理员**:我希望系统模型设置页只出现本租户真正能用的模型,不出现「继承」「尚未共享」这类我无法处理的状态,以便我自己就能把配置维护完整。 +- **E. 子租户管理员**:我希望自己设置 Root 共享给本租户的模型的价格,以便按本租户的结算标准计算积分。 --- @@ -69,6 +71,18 @@ - **AC-22** — WHEN 子租户管理员为某栏目选择模型, THE SYSTEM SHALL 只提供本租户模型和当前共享给本租户的模型作为候选。 - **AC-23** — WHEN 升级到本版本, THE SYSTEM SHALL 为每个活跃子租户中尚无自己配置的栏目,按 AC-17 的规则生成配置,并输出仍有空项的租户与栏目清单;已有自己配置的栏目不变。 +### 2.5 共享模型的价格(追加需求) + +本节的「价格」指模型价格表中每个模型的输入、输出、缓存价格和币种,它决定积分倍率和积分扣减。「价格副本」指子租户为某个 Root 模型单独保存的一份价格。 + +- **AC-24** — WHEN Root 的提供方共享给一个子租户(挂载时勾选,或加入提供方的共享清单), THE SYSTEM SHALL 为该子租户复制该提供方下每个模型当时的 Root 价格,作为该子租户的价格副本;已有价格副本的模型不重新复制。 +- **AC-25** — WHEN Root 在已共享的提供方下新增模型, THE SYSTEM SHALL 为当前每个接收该提供方的子租户复制这个模型的 Root 价格。 +- **AC-26** — THE SYSTEM SHALL 允许子租户管理员在本租户的模型价格表中编辑 Root 共享模型的价格;保存后只影响本租户的价格显示、积分倍率和积分扣减。 +- **AC-27** — THE SYSTEM SHALL 在子租户内只使用该子租户的价格副本:Root 之后修改价格,不影响任何已存在的子租户价格副本;子租户修改价格副本,不影响 Root 和其他子租户。 +- **AC-28** — WHEN 取消对某子租户的共享, THE SYSTEM SHALL 保留它的价格副本;之后重新共享时按 AC-24 只为没有价格副本的模型复制。 +- **AC-29** — IF 子租户内某个 Root 共享模型没有价格副本, THEN THE SYSTEM SHALL 在价格表中显示价格缺失且允许子租户管理员填写,计费沿用现有的价格缺失规则,不读取 Root 的价格。 +- **AC-30** — WHEN 升级到本版本, THE SYSTEM SHALL 为每个子租户当前被共享的 Root 模型中没有价格副本的模型复制 Root 当前价格,并输出 Root 价格本身缺失的模型清单。 + --- ## 3. 边界情况 @@ -78,6 +92,10 @@ - 停用的子租户不出现在可选清单和挂载外的批量操作中,其已有共享保持不变(AC-05)。 - 单租户部署(多租户关闭)时,共享字段、影响确认和挂载提供方选择都不出现。 - 提供方被删除或模型下线不属于取消共享,沿用现有的删除影响确认与下线处理。 +- Root 价格本身缺失时,复制得到的也是「价格缺失」,由子租户管理员自己填写(AC-29)。 +- Root 修改价格后若希望子租户同步,需要子租户管理员自己修改;系统不提供「从 Root 重新复制」的操作。 +- 子租户自己的模型(非 Root 共享)的价格本来就由子租户维护,不受本节影响。 +- 子租户的积分设置(币种、汇率、积分单价、基准模型)本来就按租户独立,不在本节范围。 --- diff --git a/features/v3.1.0/005-tenant-model-share-snapshot/tasks.md b/features/v3.1.0/005-tenant-model-share-snapshot/tasks.md index 02173ff455..2d92dc9a31 100644 --- a/features/v3.1.0/005-tenant-model-share-snapshot/tasks.md +++ b/features/v3.1.0/005-tenant-model-share-snapshot/tasks.md @@ -12,7 +12,7 @@ | spec.md | ✅ 已评审 | 2026-12-03 用户确认 | | design.md | ✅ 已评审 | 2026-12-03 用户确认 | | tasks.md | ✅ 已拆解 | | -| 实现 | 🔄 进行中 | 21 / 23(后端、前端、文档已完成;待 T041 端到端和 T042 审查) | +| 实现 | 🔄 进行中 | 25 / 29(价格副本追加需求 T050–T055 进行中;T041 中 AC-01–AC-23 已在 test 116 通过) | --- @@ -208,7 +208,7 @@ **文件**: `docs/architecture/12-multi-tenant.md`(共享与继承两节)、`docs/customer-guides/多租户产品使用说明.md`(「共享给子租户」说明)、`features/v3.1.0-beta1/025-tenant-system-models/spec.md`(修订历史,写明被 F005 取代的 AC) **依赖**: T029, T034 -- [ ] **T041**: 端到端验收 +- [ ] **T041**: 端到端验收(AC-01–AC-23 部分已于 2026-12-03 在 test 116 通过 16/16,脚本 `scratchpad/f005_e2e.py`,测试租户 74、75;DM8 预览未执行) **逻辑**: 执行 `/e2e-test features/v3.1.0/005-tenant-model-share-snapshot`。在 114 部署本分支,用非 admin 的子租户管理员账号按 plan 中的端到端 1–5 步验证;在 DM8 环境(105)上跑一次迁移脚本的预览。环境不可用时,在本节注明未验证项。 **覆盖 AC**: AC-01, AC-02, AC-03, AC-10, AC-13, AC-17, AC-18, AC-21, AC-23 **依赖**: T040 @@ -217,6 +217,31 @@ **逻辑**: `/sdd-code-review --base feat/3.1.0`,按报告修复 NEEDS_FIX 项。 **依赖**: T041 +## Wave 5:共享模型的价格副本(追加需求,spec §2.5,design 决策 10–14) + +- [x] **T050**: 测试:价格副本的初始化、读取分流、子租户编辑、存量复制 + **文件**: `test/llm/test_tenant_model_pricing.py`(新)、`test/llm/test_snapshot_child_model_defaults_script.py`、`test/llm/test_model_pricing_edit.py`、`test/dsh/test_pricing_hints.py` + **覆盖 AC**: AC-24, AC-25, AC-26, AC-27, AC-28, AC-29, AC-30 + +- [x] **T051**: 实现:表和迁移 + **文件**: `bisheng/llm/domain/models/model_tenant_pricing.py`(新)、`alembic/versions/v3_1_0_f005_model_tenant_pricing.py`(新)、`core/database/tenant_filter.py`(登记租户表) + **依赖**: T050 + +- [x] **T052**: 实现:初始化、读取、写入 + **文件**: `bisheng/llm/domain/pricing/tenant_pricing.py`(新)、`model_sharing_lifecycle.initialize_shared_models`(替换全部新接收方初始化调用点)、`model_pricing_repository.py`、`LLMService.read_model_pricing`、`dsh/domain/services/model.py`、`dsh/domain/services/pricing.py`、`llm/domain/pricing/service.py` + **依赖**: T051 + +- [x] **T053**: 实现:升级脚本的价格步骤和升级说明 + **文件**: `scripts/snapshot_child_model_defaults.py`、`upgrade.md` + **依赖**: T052 + +- [ ] **T054**: 回归:`test/llm`、`test/dsh`、`test/knowledge_unification`(模型与共享相关)与基线对比 + **依赖**: T053 + +- [ ] **T055**: 端到端:116 部署后重跑升级脚本;用非 admin 子租户管理员编辑共享模型价格,确认 Root 价格不变、子租户价格表与工作台倍率用副本 + **覆盖 AC**: AC-24, AC-26, AC-27, AC-30 + **依赖**: T054 + --- ## 实际偏差记录 @@ -233,5 +258,7 @@ - T027 补充:`GET /api/v1/llm` 新增 `root_only`,挂载弹窗用它列出全部 Root 提供方;保存清单允许包含当前已共享的停用子租户 → design 决策 2、修订记录。 - T031:确认逻辑做成 `useSharingConfirm` hook,和确认框放在同一个文件里,`ModelConfig.tsx` 保持在 600 行以内。 - T032:「去补充」按钮先切换管理视图到新租户,再打开 `?systemModel=`,定位到第一个有空项的设置。 +- T052:DSH 测试替身里的模型没有 `tenant_id` 属性,读取分流按"自有模型"处理(`getattr`),不改测试替身。 +- T052:`initialize_shared_models` 通过模块属性调用可见范围初始化,保留现有测试对 `shared_model_visibility.initialize_shared_model_visibility` 的替换点。 - T033:五个设置页保存后不再刷新 `system-model-settings*` 查询(诊断组件已删除,没有读取方)。 - T041(2026-12-03 test 116):升级脚本原先复用 `repair_model_sharing.operator_identity` 自签 web token,在 `reject_legacy_web_tokens` 打开的环境被拒(`legacy_web_token_rejected`),改为 `UserPayload.init_login_user` 直接加载;脚本复制了部分设置项时漏报租户原有设置项里的空槽位,改为两部分合并报告。 diff --git a/features/v3.1.0/005-tenant-model-share-snapshot/upgrade.md b/features/v3.1.0/005-tenant-model-share-snapshot/upgrade.md index 30d8f0419d..c876b6cf20 100644 --- a/features/v3.1.0/005-tenant-model-share-snapshot/upgrade.md +++ b/features/v3.1.0/005-tenant-model-share-snapshot/upgrade.md @@ -10,19 +10,20 @@ | 模型服务提供方的共享 | 一个开关:共享给全部活跃子租户,或全部不共享 | 一个子租户清单:只共享给勾选的子租户 | | 已开启共享的提供方 | 共享给全部活跃子租户 | 不变。现有的共享就是新清单的初始值,不需要迁移 | | 新挂载的子租户 | 自动得到所有已开启共享的提供方 | 只得到挂载时勾选的提供方 | +| 子租户中 Root 共享模型的价格 | 读取 Root 的价格,子租户管理员只读 | 子租户有自己的一份价格,由子租户管理员维护。升级时由脚本从 Root 复制 | ## 2. 升级步骤 按顺序执行。第 3 步必须在第 4 步之前完成:新版本启动后不再读取 Root 的配置,没有自己配置的子租户会暂时没有系统模型。 1. 备份数据库。 -2. 执行数据库迁移:`alembic upgrade head`。本特性没有表结构变更。 +2. 执行数据库迁移:`alembic upgrade head`。本特性新增一张表 `llm_model_tenant_pricing`(子租户的价格副本)。 3. 用新版本镜像运行快照脚本。在 `src/backend/` 下执行,`config` 环境变量与服务使用的一致: 1. 预览,不写库: ```bash python scripts/snapshot_child_model_defaults.py --operator-user-id ``` - 2. 检查输出。每个子租户一项:`copied_keys` 是将要复制的设置项,`pending` 是复制后仍为空的槽位。 + 2. 检查输出。`tenants` 中每个子租户一项:`copied_keys` 是将要复制的设置项,`pending` 是复制后仍为空的槽位。`prices` 中每个子租户一项:`copied` 是将要复制 Root 价格的模型 ID,`root_price_missing` 是 Root 本身没有价格、因此不复制的模型 ID。 3. 写入: ```bash python scripts/snapshot_child_model_defaults.py --operator-user-id --apply @@ -30,6 +31,9 @@ 4. 如果退出码是 2,输出中带 `error` 的子租户没有处理完。排除原因后重新执行第 3 步;已经写入的设置项不会被覆盖。 4. 启动新版本服务。 5. 把第 3 步输出中 `pending` 不为空的租户和槽位发给对应租户的管理员,请他们在「模型管理 → 系统模型设置」里补充。 +6. 把 `root_price_missing` 中的模型发给对应子租户的管理员,请他们在「用户可选模型」的价格列里填写价格。没有价格的模型按免费计费。 + +如果环境已经用较早的 F005 版本执行过本脚本(只复制设置项),部署新版本后再执行一次第 3 步:设置项部分不会再写入,价格部分完成首次复制。 ## 3. 脚本的规则 @@ -41,6 +45,8 @@ 子租户已经有自己配置的设置项不变。重复执行 `--apply` 不会产生新的写入,输出仍会列出当前为空的槽位。 +价格部分处理每个未归档的子租户(包括停用的):对共享给它的 Root 提供方下的每个 LLM 模型,如果它还没有自己的价格,就复制 Root 当前的价格。已有价格的模型不变。 + ## 4. 注意事项 - **`scripts/repair_model_sharing.py`**:这是 v3.1.0-beta1 的升级修复步骤。它的 `--apply` 会把"已开启"的提供方共享给全部活跃子租户。如果需要执行它,必须在管理员开始按清单保存共享之前执行,否则会把管理员没有勾选的子租户加回去。 diff --git a/src/backend/bisheng/core/database/alembic/versions/v3_1_0_f005_model_tenant_pricing.py b/src/backend/bisheng/core/database/alembic/versions/v3_1_0_f005_model_tenant_pricing.py new file mode 100644 index 0000000000..b834618e24 --- /dev/null +++ b/src/backend/bisheng/core/database/alembic/versions/v3_1_0_f005_model_tenant_pricing.py @@ -0,0 +1,36 @@ +"""F005: a child tenant's own copy of a Root-shared model's price.""" + +import sqlalchemy as sa +from alembic import op + +from bisheng.core.database.alembic_helpers.online import table_exists +from bisheng.core.database.dialect_helpers import UPDATE_TIME_SERVER_DEFAULT, JsonType, update_time_server_default + +revision = "v310_f005_model_tenant_pricing" +down_revision = "v310_host_isolation_descriptor" +branch_labels = None +depends_on = None + + +def upgrade(): + if table_exists("llm_model_tenant_pricing"): + return + conn = op.get_bind() + update_default = UPDATE_TIME_SERVER_DEFAULT if conn.dialect.name == "sqlite" else update_time_server_default(conn) + op.create_table( + "llm_model_tenant_pricing", + sa.Column("id", sa.BigInteger().with_variant(sa.Integer, "sqlite"), primary_key=True, autoincrement=True), + sa.Column("tenant_id", sa.BigInteger(), nullable=False), + sa.Column("model_id", sa.BigInteger(), nullable=False), + sa.Column("pricing", JsonType(), nullable=False), + sa.Column("updated_by", sa.BigInteger(), nullable=False), + sa.Column("create_time", sa.DateTime(), nullable=False, server_default=sa.text("CURRENT_TIMESTAMP")), + sa.Column("update_time", sa.DateTime(), nullable=False, server_default=update_default), + sa.UniqueConstraint("tenant_id", "model_id", name="uq_llm_model_tenant_pricing"), + ) + op.create_index("ix_llm_model_tenant_pricing_tenant_id", "llm_model_tenant_pricing", ["tenant_id"]) + + +def downgrade(): + if table_exists("llm_model_tenant_pricing"): + op.drop_table("llm_model_tenant_pricing") diff --git a/src/backend/bisheng/core/database/tenant_filter.py b/src/backend/bisheng/core/database/tenant_filter.py index 9ea29b08d6..997ff723e6 100644 --- a/src/backend/bisheng/core/database/tenant_filter.py +++ b/src/backend/bisheng/core/database/tenant_filter.py @@ -72,6 +72,7 @@ "bisheng.llm.domain.models.llm_token_log", "bisheng.llm.domain.models.tenant_system_model_config", "bisheng.llm.domain.models.model_sharing_intent", + "bisheng.llm.domain.models.model_tenant_pricing", "bisheng.workstation.domain.models.tenant_workstation_config", "bisheng.org_sync.domain.models.org_sync", "bisheng.approval.domain.models.approval_request", diff --git a/src/backend/bisheng/dsh/domain/services/model.py b/src/backend/bisheng/dsh/domain/services/model.py index 6381aba2f0..b0a104e40c 100644 --- a/src/backend/bisheng/dsh/domain/services/model.py +++ b/src/backend/bisheng/dsh/domain/services/model.py @@ -38,6 +38,7 @@ from bisheng.dsh.infrastructure.responses_adapter import DshResponsesAdapter from bisheng.dsh.infrastructure.telemetry import record_settlement, request_trace from bisheng.dsh.infrastructure.usage_contract import enforce_inclusive +from bisheng.llm.domain.pricing.tenant_pricing import aread_effective_pricing def error_response(error, request_id: str) -> dict: @@ -150,9 +151,7 @@ async def list_models(self, principal: DshPrincipal) -> dict: else: policy = await self.policy_reader(int(principal.user_id)) model_ids = policy.allowed_model_ids if policy else [] - hint_context = ( - await self.hint_context_reader() if (billed and self.hint_context_reader) else None - ) + hint_context = await self.hint_context_reader() if (billed and self.hint_context_reader) else None result = [] for model_id in model_ids: try: @@ -168,6 +167,7 @@ async def list_models(self, principal: DshPrincipal) -> dict: continue if capabilities is None: continue + price = await aread_effective_pricing(model) if hint_context else None created = model.create_time if isinstance(created, datetime): created = created.replace(tzinfo=UTC) if created.tzinfo is None else created @@ -184,11 +184,7 @@ async def list_models(self, principal: DshPrincipal) -> dict: "capabilities": capabilities.client_fields(), **model_metadata(model, capabilities), # F016: optional field; older desktop clients ignore unknown keys. - **( - {"pricing_hint": pricing_hint(model.id, (model.config or {}).get("pricing"), hint_context)} - if hint_context - else {} - ), + **({"pricing_hint": pricing_hint(model.id, price, hint_context)} if hint_context else {}), **( {"reasoning": capabilities.reasoning.model_dump(exclude_none=True)} if capabilities.reasoning @@ -231,7 +227,7 @@ async def complete( # F016: the loaded model is read uncached, so its prices are current; freeze them now. if billed: setting = await self.credit_setting_reader() if self.credit_setting_reader else CreditSettingState() - pricing = billing_snapshot((model.config or {}).get("pricing"), setting, model_id=model.id) + pricing = billing_snapshot(await aread_effective_pricing(model), setting, model_id=model.id) else: pricing = PricingSnapshot( currency="CNY", diff --git a/src/backend/bisheng/dsh/domain/services/pricing.py b/src/backend/bisheng/dsh/domain/services/pricing.py index e0c72cc8ba..3719383799 100644 --- a/src/backend/bisheng/dsh/domain/services/pricing.py +++ b/src/backend/bisheng/dsh/domain/services/pricing.py @@ -17,6 +17,7 @@ format_micro, ) from bisheng.llm.domain.pricing import MICRO, ModelPricing, price_to_micro +from bisheng.llm.domain.pricing.tenant_pricing import aread_effective_pricing def convert_micro(value: int, source: str, target: str, usd_cny_rate_micro: int) -> int: @@ -140,7 +141,7 @@ async def read_hint_context(setting: CreditSettingState | None = None) -> HintCo if base_id: try: model, _ = await LLMService.get_dsh_model_snapshot(base_id) - snapshot = build_snapshot((model.config or {}).get("pricing"), setting) + snapshot = build_snapshot(await aread_effective_pricing(model), setting) if snapshot.free or not blended_micro(snapshot): reason = "base_price_not_positive" else: @@ -205,7 +206,7 @@ async def save_credit_settings(actor: int, value: CreditSettingInput) -> dict: usd_cny_rate_micro=value.usd_cny_rate_micro, credit_value_micro=value.credit_value_micro, ) - snapshot = build_snapshot((model.config or {}).get("pricing"), setting) + snapshot = build_snapshot(await aread_effective_pricing(model), setting) if snapshot.free or not blended_micro(snapshot): from bisheng.common.errcode.dsh import DshInvalidRequestError @@ -233,7 +234,6 @@ def converted(price: str) -> str: async def admin_model_pricing() -> list[dict]: """Price summary and ratio of every online LLM model of the tenant (user-selectable table).""" from bisheng.common.errcode.dsh import DshModelNotAllowedError - from bisheng.core.context.tenant import get_current_tenant_id from bisheng.llm.domain.services.llm import LLMService context = await read_hint_context() @@ -243,7 +243,7 @@ async def admin_model_pricing() -> list[dict]: model, server = await LLMService.get_dsh_model_metadata_snapshot(model_id) except DshModelNotAllowedError: continue - raw = (model.config or {}).get("pricing") + raw = await aread_effective_pricing(model) try: stored = ModelPricing.model_validate(raw) if raw is not None else None except ValidationError: @@ -251,8 +251,9 @@ async def admin_model_pricing() -> list[dict]: rows.append( { "model_id": model_id, - "can_edit": server.tenant_id == get_current_tenant_id(), - "read_only": server.tenant_id != get_current_tenant_id(), + # F005: a child edits its own copy of a Root-shared model's price. + "can_edit": True, + "read_only": False, "source_tenant_id": server.tenant_id, "base_reason": context.base_reason, "pricing": stored.model_dump() if stored else None, diff --git a/src/backend/bisheng/llm/application/model_sharing.py b/src/backend/bisheng/llm/application/model_sharing.py index e6db35402a..eb66949a89 100644 --- a/src/backend/bisheng/llm/application/model_sharing.py +++ b/src/backend/bisheng/llm/application/model_sharing.py @@ -493,10 +493,10 @@ async def _finish_sharing( await phase.call(sharing.arequire_finalized, phase.session, prepared) receipt = await phase.call(self.intents.aread_initialization, phase.session, plan_id=row.id) if receipt is not None: - from bisheng.dsh.domain.services.shared_model_visibility import initialize_shared_model_visibility + from bisheng.llm.application.model_sharing_lifecycle import initialize_shared_models await phase.call( - initialize_shared_model_visibility, + initialize_shared_models, phase.session, child_ids=receipt.child_ids, model_ids=receipt.model_ids, diff --git a/src/backend/bisheng/llm/application/model_sharing_lifecycle.py b/src/backend/bisheng/llm/application/model_sharing_lifecycle.py index fd5807d391..2b84a9583e 100644 --- a/src/backend/bisheng/llm/application/model_sharing_lifecycle.py +++ b/src/backend/bisheng/llm/application/model_sharing_lifecycle.py @@ -1,9 +1,25 @@ """Model-owner lifecycle work in the original provider-locked transaction.""" -from bisheng.dsh.domain.services.shared_model_visibility import initialize_shared_model_visibility +from bisheng.dsh.domain.services import shared_model_visibility +from bisheng.llm.domain.pricing.tenant_pricing import ainitialize_shared_model_pricing from bisheng.llm.domain.repositories.model_sharing_intent_repository import ModelSharingIntentRepository +async def initialize_shared_models(session, *, child_ids, model_ids, actor_user_id, plan_id, guard): + """Everything a child gets with a newly shared Root model, only where it is missing. + + Default visibility (DSH) and the child's own price copy (F005) are written in the + caller's provider-locked transaction; every new-receiver path goes through here. + """ + await shared_model_visibility.initialize_shared_model_visibility( + session, child_ids=child_ids, model_ids=model_ids, actor_user_id=actor_user_id, plan_id=plan_id, guard=guard + ) + await ainitialize_shared_model_pricing( + session, child_ids=child_ids, model_ids=model_ids, actor_user_id=actor_user_id + ) + guard() + + async def initialize_sharing_update(session, *, request, server_id, plan_id, enabled, new_model_ids, prepared_sharing): repository = ModelSharingIntentRepository() # A Root update includes an explicit sharing command. Its durable intent is @@ -11,7 +27,7 @@ async def initialize_sharing_update(session, *, request, server_id, plan_id, ena await repository.aset(session, server_id=server_id, enabled=enabled, plan_id=plan_id) receipt = await repository.aread_initialization(session, plan_id=plan_id) if receipt is not None: - await initialize_shared_model_visibility( + await initialize_shared_models( session, child_ids=receipt.child_ids, model_ids=receipt.model_ids, @@ -21,7 +37,7 @@ async def initialize_sharing_update(session, *, request, server_id, plan_id, ena ) if enabled and new_model_ids and prepared_sharing is not None: ids = await repository.adialogue_model_ids(session, server_id=server_id, model_ids=new_model_ids) - await initialize_shared_model_visibility( + await initialize_shared_models( session, child_ids=prepared_sharing.after, model_ids=ids, @@ -87,7 +103,7 @@ async def initialize_added_provider_models(session, *, server_id, model_ids, ide if request.actor_reference != sharing_snapshot["actor"]: raise KnowledgeOperationPlanChangedError() ids = await repository.adialogue_model_ids(session, server_id=server_id, model_ids=model_ids) - await initialize_shared_model_visibility( + await initialize_shared_models( session, child_ids=sharing_snapshot["subjects"], model_ids=ids, diff --git a/src/backend/bisheng/llm/domain/models/__init__.py b/src/backend/bisheng/llm/domain/models/__init__.py index d48839cad2..c653d29f79 100644 --- a/src/backend/bisheng/llm/domain/models/__init__.py +++ b/src/backend/bisheng/llm/domain/models/__init__.py @@ -1,4 +1,5 @@ -from .llm_server import LLMDao, LLMServer, LLMModel, LLMModelBase, LLMServerBase +from .llm_server import LLMDao, LLMModel, LLMModelBase, LLMServer, LLMServerBase +from .model_tenant_pricing import ModelTenantPricing from .tenant_system_model_config import ( TenantSystemModelConfig, TenantSystemModelConfigBase, @@ -7,10 +8,11 @@ __all__ = [ "LLMDao", - "LLMServer", "LLMModel", "LLMModelBase", + "LLMServer", "LLMServerBase", + "ModelTenantPricing", "TenantSystemModelConfig", "TenantSystemModelConfigBase", "TenantSystemModelConfigDao", diff --git a/src/backend/bisheng/llm/domain/models/model_tenant_pricing.py b/src/backend/bisheng/llm/domain/models/model_tenant_pricing.py new file mode 100644 index 0000000000..2adcbbba34 --- /dev/null +++ b/src/backend/bisheng/llm/domain/models/model_tenant_pricing.py @@ -0,0 +1,35 @@ +"""F005: a child tenant's own copy of the price of a Root model shared with it. + +Root's price and the prices of a tenant's own models stay in +``llm_model.config["pricing"]``; only the Root model x child tenant pair lives here. +""" + +from datetime import datetime + +from sqlalchemy import BigInteger, Column, DateTime, Integer, UniqueConstraint, text +from sqlmodel import Field + +from bisheng.common.models.base import SQLModelSerializable +from bisheng.core.database.dialect_helpers import UPDATE_TIME_SERVER_DEFAULT, JsonType + + +class ModelTenantPricing(SQLModelSerializable, table=True): + __tablename__ = "llm_model_tenant_pricing" + __table_args__ = (UniqueConstraint("tenant_id", "model_id", name="uq_llm_model_tenant_pricing"),) + + id: int | None = Field( + default=None, sa_column=Column(BigInteger().with_variant(Integer, "sqlite"), primary_key=True) + ) + tenant_id: int | None = Field(default=None, sa_column=Column(BigInteger, nullable=False, index=True)) + model_id: int = Field(sa_column=Column(BigInteger, nullable=False)) + pricing: dict = Field(sa_column=Column(JsonType, nullable=False)) + updated_by: int = Field(sa_column=Column(BigInteger, nullable=False)) + create_time: datetime | None = Field( + default=None, sa_column=Column(DateTime, nullable=False, server_default=text("CURRENT_TIMESTAMP")) + ) + update_time: datetime | None = Field( + default=None, + sa_column=Column( + DateTime, nullable=False, server_default=UPDATE_TIME_SERVER_DEFAULT, onupdate=text("CURRENT_TIMESTAMP") + ), + ) diff --git a/src/backend/bisheng/llm/domain/pricing/service.py b/src/backend/bisheng/llm/domain/pricing/service.py index 633091cf76..e9865c350d 100644 --- a/src/backend/bisheng/llm/domain/pricing/service.py +++ b/src/backend/bisheng/llm/domain/pricing/service.py @@ -109,29 +109,30 @@ def apply_pricing_on_save(server_type: str, models, stored_configs: dict) -> Non async def save_model_pricing(operator, model_id: int, incoming) -> dict: """Edit one model's price from the user-selectable model table (T04); returns the stored price.""" - from bisheng.common.errcode.llm_tenant import LLMModelNotAccessibleError, LLMModelSharedReadonlyError + from bisheng.common.errcode.llm_tenant import LLMModelNotAccessibleError from bisheng.core.context.tenant import bypass_tenant_filter, get_current_tenant_id from bisheng.database.models.tenant import ROOT_TENANT_ID from bisheng.llm.domain.models.llm_server import LLMDao + from bisheng.llm.domain.pricing.tenant_pricing import asave_tenant_model_pricing from bisheng.llm.domain.repositories.model_pricing_repository import asave_model_pricing from bisheng.llm.domain.utils import invalidate_llm_info_cache if incoming is None: raise ModelPricingInvalidError() - # Read past the tenant filter only to tell a Root-shared model (read-only here) from a missing one. + + def resolve(server_type, model_name, stored): + return resolve_model_pricing(server_type, model_name, incoming=incoming, existing=stored) + + # Read past the tenant filter only to tell a Root-shared model from a missing one. with bypass_tenant_filter(): model = await LLMDao.aget_model_by_id(model_id) server = await LLMDao.aget_server_by_id(model.server_id) if model else None if server is None: raise LLMModelNotAccessibleError() if server.tenant_id == ROOT_TENANT_ID and get_current_tenant_id() != ROOT_TENANT_ID: - raise LLMModelSharedReadonlyError() - pricing = await asave_model_pricing( - model_id, - lambda server_type, model_name, stored: resolve_model_pricing( - server_type, model_name, incoming=incoming, existing=stored - ), - ) + # F005: a child edits its own copy; Root's price is not touched. + return await asave_tenant_model_pricing(model_id, resolve, actor_user_id=operator.user_id) + pricing = await asave_model_pricing(model_id, resolve) invalidate_llm_info_cache(model_id=model_id) return pricing diff --git a/src/backend/bisheng/llm/domain/pricing/tenant_pricing.py b/src/backend/bisheng/llm/domain/pricing/tenant_pricing.py new file mode 100644 index 0000000000..ccb2fa6689 --- /dev/null +++ b/src/backend/bisheng/llm/domain/pricing/tenant_pricing.py @@ -0,0 +1,219 @@ +"""F005: child tenants keep their own copy of the price of a Root model shared with them. + +* ``ainitialize_shared_model_pricing`` copies Root's price when a child first + receives a Root model (design decision 11). It only fills missing copies. +* ``effective_pricing`` / ``aread_effective_pricing`` pick the price a tenant + uses: a model's own row for its owner, the tenant's copy for a Root model, and + never Root's price for a child (decision 12). +* ``asave_tenant_model_pricing`` is a child administrator's edit of its copy + (decision 13). +""" + +from pydantic import ValidationError +from sqlalchemy.exc import IntegrityError +from sqlmodel import col, select + +from bisheng.common.errcode.llm import ModelPricingConflictError, ModelPricingInvalidError +from bisheng.common.errcode.llm_tenant import LLMModelNotAccessibleError +from bisheng.core.context.tenant import bypass_tenant_filter, get_current_tenant_id +from bisheng.database.models.tenant import ROOT_TENANT_ID +from bisheng.llm.domain.const import LLMModelType +from bisheng.llm.domain.models.llm_server import LLMModel, LLMServer +from bisheng.llm.domain.models.model_tenant_pricing import ModelTenantPricing +from bisheng.llm.domain.pricing.schemas import ModelPricing + + +def _valid(value) -> dict | None: + try: + return ModelPricing.model_validate(value).model_dump() if value is not None else None + except ValidationError: + return None + + +def _own_pricing(model) -> dict | None: + config = model.config if isinstance(model.config, dict) else {} + pricing = config.get("pricing") + return pricing if isinstance(pricing, dict) else None + + +def _reads_copy(model, tenant_id) -> bool: + owner = getattr(model, "tenant_id", None) + return tenant_id is not None and owner == ROOT_TENANT_ID and tenant_id != ROOT_TENANT_ID + + +async def ainitialize_shared_model_pricing(session, *, child_ids, model_ids, actor_user_id): + """Copy Root's current price to each child that has no copy yet, in the caller's transaction.""" + if not child_ids or not model_ids: + return + with session.no_autoflush, bypass_tenant_filter(): + rows = ( + await session.execute( + select(LLMModel.id, LLMModel.config).where( + col(LLMModel.id).in_(sorted(set(model_ids))), + LLMModel.tenant_id == ROOT_TENANT_ID, + LLMModel.model_type == LLMModelType.LLM.value, + ) + ) + ).all() + prices = {model_id: _valid((config or {}).get("pricing")) for model_id, config in rows} + prices = {model_id: price for model_id, price in prices.items() if price is not None} + if not prices: + return + for child_id in sorted(set(child_ids)): + with session.no_autoflush, bypass_tenant_filter(): + existing = set( + ( + await session.execute( + select(ModelTenantPricing.model_id).where( + ModelTenantPricing.tenant_id == child_id, + col(ModelTenantPricing.model_id).in_(sorted(prices)), + ) + ) + ).scalars() + ) + for model_id in sorted(set(prices) - existing): + session.add( + ModelTenantPricing( + tenant_id=child_id, model_id=model_id, pricing=prices[model_id], updated_by=actor_user_id + ) + ) + await session.flush() + + +def read_effective_pricing(session, model_id: int, tenant_id: int | None) -> dict | None: + """Sync read of the price ``tenant_id`` uses for a model it was already authorized for.""" + with bypass_tenant_filter(): + model = session.exec(select(LLMModel).where(LLMModel.id == model_id)).first() + if model is None: + return None + if not _reads_copy(model, tenant_id): + return _own_pricing(model) + return session.exec( + select(ModelTenantPricing.pricing).where( + ModelTenantPricing.tenant_id == tenant_id, ModelTenantPricing.model_id == model_id + ) + ).first() + + +async def aread_price_copies(tenant_id: int, model_ids) -> dict[int, dict]: + """A tenant's stored copies of Root model prices, keyed by model id.""" + from bisheng.core.database import get_async_db_session + + async with get_async_db_session() as session: + with bypass_tenant_filter(): + rows = ( + await session.exec( + select(ModelTenantPricing.model_id, ModelTenantPricing.pricing).where( + ModelTenantPricing.tenant_id == tenant_id, + col(ModelTenantPricing.model_id).in_(sorted(set(model_ids))), + ) + ) + ).all() + return dict(rows) + + +async def aread_effective_pricings(models, tenant_id: int | None = None) -> dict[int, dict | None]: + """Prices the current (or given) tenant uses, keyed by model id; copies are read in one query.""" + tenant_id = get_current_tenant_id() if tenant_id is None else tenant_id + result = {model.id: _own_pricing(model) for model in models if not _reads_copy(model, tenant_id)} + shared = sorted({model.id for model in models if _reads_copy(model, tenant_id)}) + if shared: + copies = await aread_price_copies(tenant_id, shared) + result.update({model_id: copies.get(model_id) for model_id in shared}) + return result + + +async def aread_effective_pricing(model, tenant_id: int | None = None) -> dict | None: + return (await aread_effective_pricings([model], tenant_id))[model.id] + + +async def asave_tenant_model_pricing(model_id: int, resolve, *, actor_user_id: int) -> dict: + """Store the current child tenant's copy of a Root model's price. + + ``resolve(server_type, model_name, stored)`` is the same price decision the + owner's write path uses, so revision checks and the source rule do not change. + """ + from bisheng.core.database import get_async_db_session + from bisheng.llm.domain.models.llm_server import LLMDao + + tenant_id = get_current_tenant_id() + if tenant_id is None or tenant_id == ROOT_TENANT_ID: + raise LLMModelNotAccessibleError() + async with get_async_db_session() as session: + with bypass_tenant_filter(): + row = ( + await session.exec( + select(LLMModel.model_name, LLMModel.model_type, LLMModel.server_id, LLMServer.type) + .join(LLMServer, LLMServer.id == LLMModel.server_id) + .where(LLMModel.id == model_id, LLMModel.tenant_id == ROOT_TENANT_ID) + ) + ).first() + if row is None: + raise LLMModelNotAccessibleError() + model_name, model_type, server_id, server_type = row + if model_type != LLMModelType.LLM.value: + raise ModelPricingInvalidError() + if server_id not in set(await LLMDao.aget_shared_server_ids_for_leaf(tenant_id, raise_on_error=True)): + raise LLMModelNotAccessibleError() + with bypass_tenant_filter(): + copy = ( + await session.exec( + select(ModelTenantPricing) + .where(ModelTenantPricing.tenant_id == tenant_id, ModelTenantPricing.model_id == model_id) + .with_for_update() + ) + ).first() + pricing = resolve(server_type, model_name, copy.pricing if copy else None) + if copy is not None and pricing == copy.pricing: + return pricing + if copy is None: + copy = ModelTenantPricing(tenant_id=tenant_id, model_id=model_id, pricing=pricing, updated_by=actor_user_id) + else: + copy.pricing, copy.updated_by = pricing, actor_user_id + session.add(copy) + try: + await session.commit() + except IntegrityError as error: + # Two first edits of a missing copy: the later one must re-read. + raise ModelPricingConflictError() from error + return pricing + + +async def abackfill_child_pricing(child_id: int, *, actor_user_id: int, dry_run: bool) -> dict: + """Upgrade step (AC-30): copy Root's price for each shared Root model the child has no copy of. + + Returns the model ids copied and those left without a price because Root has none. + """ + from bisheng.core.database import get_async_db_session + from bisheng.llm.domain.models.llm_server import LLMDao + + server_ids = sorted(await LLMDao.aget_shared_server_ids_for_leaf(child_id, raise_on_error=True)) + if not server_ids: + return {"copied": [], "root_price_missing": []} + async with get_async_db_session() as session: + with bypass_tenant_filter(): + rows = ( + await session.exec( + select(LLMModel.id, LLMModel.config).where( + col(LLMModel.server_id).in_(server_ids), + LLMModel.tenant_id == ROOT_TENANT_ID, + LLMModel.model_type == LLMModelType.LLM.value, + ) + ) + ).all() + existing = set( + ( + await session.exec( + select(ModelTenantPricing.model_id).where(ModelTenantPricing.tenant_id == child_id) + ) + ).all() + ) + missing = sorted(model_id for model_id, _ in rows if model_id not in existing) + priced = {model_id for model_id, config in rows if _valid((config or {}).get("pricing")) is not None} + copied = [model_id for model_id in missing if model_id in priced] + if copied and not dry_run: + await ainitialize_shared_model_pricing( + session, child_ids=[child_id], model_ids=copied, actor_user_id=actor_user_id + ) + await session.commit() + return {"copied": copied, "root_price_missing": [model_id for model_id in missing if model_id not in priced]} diff --git a/src/backend/bisheng/llm/domain/repositories/model_pricing_repository.py b/src/backend/bisheng/llm/domain/repositories/model_pricing_repository.py index d45c323012..04a439a16a 100644 --- a/src/backend/bisheng/llm/domain/repositories/model_pricing_repository.py +++ b/src/backend/bisheng/llm/domain/repositories/model_pricing_repository.py @@ -6,7 +6,6 @@ from bisheng.common.errcode.llm import ModelPricingInvalidError from bisheng.common.errcode.llm_tenant import LLMModelNotAccessibleError -from bisheng.core.context.tenant import bypass_tenant_filter from bisheng.core.database import get_async_db_session from bisheng.llm.domain.const import LLMModelType from bisheng.llm.domain.models.llm_server import LLMModel, LLMServer @@ -19,17 +18,17 @@ class ModelPricingRepository: def __init__(self, session: Session): self.session = session - def read(self, model_id: int) -> dict | None: - """Current price config of a model the caller has ALREADY authorized. + def read(self, model_id: int, tenant_id: int | None = None) -> dict | None: + """Price ``tenant_id`` uses for a model the caller has ALREADY authorized. - Reads the row directly, never the 60s in-process LLM_CACHE, so a price saved in - another process applies to the next call (design decision 15). Tenant filtering + Reads the rows directly, never the 60s in-process LLM_CACHE, so a price saved in + another process applies to the next call (design decision 15). A child reads its + own copy of a Root model's price, never Root's (F005 decision 12). Tenant filtering is bypassed only to read Root-shared models; it never authorizes access. """ - with bypass_tenant_filter(): - config = self.session.exec(select(LLMModel.config).where(LLMModel.id == model_id)).first() - pricing = config.get("pricing") if isinstance(config, dict) else None - return pricing if isinstance(pricing, dict) else None + from bisheng.llm.domain.pricing.tenant_pricing import read_effective_pricing + + return read_effective_pricing(self.session, model_id, tenant_id) async def asave_model_pricing(model_id: int, resolve: PriceResolver) -> dict: diff --git a/src/backend/bisheng/llm/domain/services/llm.py b/src/backend/bisheng/llm/domain/services/llm.py index b7b16a9522..496f9db161 100644 --- a/src/backend/bisheng/llm/domain/services/llm.py +++ b/src/backend/bisheng/llm/domain/services/llm.py @@ -431,12 +431,15 @@ async def get_dsh_model_ids(cls) -> list[int]: @classmethod async def read_model_pricing(cls, model_id: int) -> dict | None: """F016: uncached price config of an already-authorized model, read at call start.""" + from bisheng.core.context.tenant import get_current_tenant_id from bisheng.core.database import get_sync_db_session from bisheng.llm.domain.repositories.model_pricing_repository import ModelPricingRepository + tenant_id = get_current_tenant_id() + def read(): with get_sync_db_session() as session: - return ModelPricingRepository(session).read(model_id) + return ModelPricingRepository(session).read(model_id, tenant_id) return await asyncio.to_thread(read) diff --git a/src/backend/scripts/snapshot_child_model_defaults.py b/src/backend/scripts/snapshot_child_model_defaults.py index d72b8daece..813be6c5a8 100644 --- a/src/backend/scripts/snapshot_child_model_defaults.py +++ b/src/backend/scripts/snapshot_child_model_defaults.py @@ -7,6 +7,11 @@ those models, leave the rest empty. Keys a child already configured are not changed. +It also copies Root's price of each Root model shared with a child tenant +(active or disabled) that has no price of its own yet. Models whose Root price is +missing are listed under ``root_price_missing``: a child administrator, or Root, +must fill them in. + Run from src/backend with the live service config, after alembic and before the new services start: @@ -83,8 +88,40 @@ async def snapshot_all(*, identity, apply): logger.exception("Snapshot of system model settings failed for tenant {}", child_id) row["error"] = type(error).__name__ tenants.append(row) - report = {"applied": apply, "tenants": tenants} - return report, EXIT_FAILED_TENANTS if any("error" in row for row in tenants) else 0 + prices = await backfill_prices(identity=identity, apply=apply) + report = {"applied": apply, "tenants": tenants, "prices": prices} + failed = any("error" in row for row in [*tenants, *prices]) + return report, EXIT_FAILED_TENANTS if failed else 0 + + +async def backfill_prices(*, identity, apply): + """Copy missing price copies for every non-archived child (F005 AC-30).""" + from sqlmodel import select + + from bisheng.core.database import get_async_db_session + from bisheng.database.models.tenant import Tenant + from bisheng.llm.domain.pricing.tenant_pricing import abackfill_child_pricing + + with bypass_tenant_filter(): + async with get_async_db_session() as session: + child_ids = sorted( + ( + await session.exec( + select(Tenant.id).where(Tenant.parent_tenant_id == ROOT_TENANT_ID, Tenant.status != "archived") + ) + ).all() + ) + rows = [] + for child_id in child_ids: + row = {"tenant_id": child_id} + try: + row.update(await abackfill_child_pricing(child_id, actor_user_id=identity.user_id, dry_run=not apply)) + except Exception as error: + logger.exception("Price copy failed for tenant {}", child_id) + row["error"] = type(error).__name__ + if row.get("copied") or row.get("root_price_missing") or "error" in row: + rows.append(row) + return rows async def run(args): diff --git a/src/backend/test/dsh/test_pricing_hints.py b/src/backend/test/dsh/test_pricing_hints.py index 48192d378e..28ad4a612a 100644 --- a/src/backend/test/dsh/test_pricing_hints.py +++ b/src/backend/test/dsh/test_pricing_hints.py @@ -12,6 +12,7 @@ from bisheng.dsh.domain.schemas.pricing import CreditSettingState from bisheng.dsh.domain.services import pricing as service from bisheng.dsh.domain.services.pricing import HintContext, build_snapshot, format_ratio, pricing_hint +from bisheng.llm.domain.pricing import ModelPricing DEEPSEEK = {"currency": "CNY", "input": "9", "cache_read": "0.3", "output": "27", "source": "CATALOG"} GPT41 = {"currency": "USD", "input": "2", "cache_read": "0.5", "output": "8", "source": "CATALOG"} @@ -207,16 +208,31 @@ def test_routes_avoid_the_word_config(): assert all("config" not in route.path.lower() for route in credit_pricing.router.routes) -async def test_price_metadata_is_read_only_for_shared_root_owner(llm): +async def test_a_child_reads_and_edits_its_own_copy_of_root_prices(llm, monkeypatch): + """F005 AC-26/27/29: a child sees its copy, never Root's price, and may edit every row.""" from bisheng.core.context.tenant import get_current_tenant_id from bisheng.dsh.domain.services.profile import profile_scope + from bisheng.llm.domain.pricing import tenant_pricing + copies = {69: {7: GPT41}} + reads = [] + + async def read_copies(tenant_id, model_ids): + reads.append((tenant_id, list(model_ids))) + return {key: value for key, value in copies.get(tenant_id, {}).items() if key in model_ids} + + monkeypatch.setattr(tenant_pricing, "aread_price_copies", read_copies) with profile_scope(69): - rows = await service.admin_model_pricing() + rows = {row["model_id"]: row for row in await service.admin_model_pricing()} assert get_current_tenant_id() == 69 - assert all(row["read_only"] and not row["can_edit"] and row["source_tenant_id"] == 1 for row in rows) + assert rows[7]["pricing"] == ModelPricing.model_validate(GPT41).model_dump() + assert rows[8]["missing"] and rows[8]["pricing"] is None # no copy: missing, not Root's price + assert all(row["can_edit"] and not row["read_only"] for row in rows.values()) + assert all(tenant == 69 for tenant, _ in reads) + reads.clear() with profile_scope(1): - assert all(row["can_edit"] and not row["read_only"] for row in await service.admin_model_pricing()) + rows = {row["model_id"]: row for row in await service.admin_model_pricing()} + assert rows[8]["pricing"] == ModelPricing.model_validate(GPT41).model_dump() and reads == [] async def test_unavailable_base_is_diagnostic_and_other_model_price_remains_usable(llm): diff --git a/src/backend/test/knowledge_unification/test_model_deletion_repository.py b/src/backend/test/knowledge_unification/test_model_deletion_repository.py index b14d26d4f3..3437f12f47 100644 --- a/src/backend/test/knowledge_unification/test_model_deletion_repository.py +++ b/src/backend/test/knowledge_unification/test_model_deletion_repository.py @@ -19,9 +19,11 @@ async def removal_session(tmp_path): engine = await models.async_database(f"sqlite+aiosqlite:///{tmp_path / 'model-deletion.db'}") from bisheng.dsh.domain.models.unified_policy import ModelVisibility, UnifiedPolicyAudit from bisheng.llm.domain.models.model_sharing_intent import ModelSharingInitialization, ModelSharingIntent + from bisheng.llm.domain.models.model_tenant_pricing import ModelTenantPricing + tables = (ModelSharingIntent, ModelSharingInitialization, ModelVisibility, UnifiedPolicyAudit, ModelTenantPricing) async with engine.begin() as connection: - for model in (ModelSharingIntent, ModelSharingInitialization, ModelVisibility, UnifiedPolicyAudit): + for model in tables: await connection.run_sync(lambda active, model=model: model.__table__.create(active, checkfirst=True)) async with AsyncSession(engine, expire_on_commit=False) as session: session.add(LLMServer(id=4, tenant_id=101, name="another-own", type="openai")) diff --git a/src/backend/test/llm/test_model_pricing_edit.py b/src/backend/test/llm/test_model_pricing_edit.py index 03b13f1903..c45ce1ee3a 100644 --- a/src/backend/test/llm/test_model_pricing_edit.py +++ b/src/backend/test/llm/test_model_pricing_edit.py @@ -16,7 +16,7 @@ from bisheng.common.dependencies.user_deps import UserPayload from bisheng.common.errcode.knowledge import KnowledgeProcessingConflictError from bisheng.common.errcode.llm import ModelPricingConflictError, ModelPricingInvalidError -from bisheng.common.errcode.llm_tenant import LLMModelNotAccessibleError, LLMModelSharedReadonlyError +from bisheng.common.errcode.llm_tenant import LLMModelNotAccessibleError from bisheng.core.context.tenant import current_tenant_id from bisheng.core.database import tenant_filter from bisheng.knowledge.domain.models.knowledge_operation_plan import KnowledgeOperationPlan @@ -94,10 +94,24 @@ async def test_service_rejects_a_stale_revision(lookup): lookup.invalidate.assert_not_called() -async def test_root_shared_model_is_read_only_for_a_child_and_missing_models_stay_hidden(lookup): +async def test_a_child_edits_its_own_copy_of_a_root_shared_price(lookup, monkeypatch): + from bisheng.llm.domain.pricing import tenant_pricing + + copies = [] + + async def save_copy(model_id, resolve, *, actor_user_id): + copies.append((model_id, actor_user_id)) + return resolve("qwen", "qwen-max", None) + + monkeypatch.setattr(tenant_pricing, "asave_tenant_model_pricing", save_copy) lookup.server.tenant_id = 1 - with pytest.raises(LLMModelSharedReadonlyError): - await service.save_model_pricing(object(), 7, QWEN_MAX) + result = await service.save_model_pricing(SimpleNamespace(user_id=9), 7, QWEN_MAX) + assert (result["input"], result["revision"]) == ("2.4", 1) + assert copies == [(7, 9)] and lookup.saved == [] + lookup.invalidate.assert_not_called() + + +async def test_missing_models_stay_hidden_and_a_price_is_required(lookup): lookup.model = None with pytest.raises(LLMModelNotAccessibleError): await service.save_model_pricing(object(), 7, QWEN_MAX) diff --git a/src/backend/test/llm/test_snapshot_child_model_defaults_script.py b/src/backend/test/llm/test_snapshot_child_model_defaults_script.py index 5dddd14e72..ca90ac2af9 100644 --- a/src/backend/test/llm/test_snapshot_child_model_defaults_script.py +++ b/src/backend/test/llm/test_snapshot_child_model_defaults_script.py @@ -1,6 +1,6 @@ """F005 T028: the upgrade script copies only missing keys, previews by default, and is repeatable. -覆盖 AC: AC-23 +覆盖 AC: AC-23, AC-30 """ from types import SimpleNamespace @@ -10,17 +10,18 @@ from scripts import snapshot_child_model_defaults as script from test.llm.test_child_model_snapshot import CHILD, ROOT, own, put, world # noqa: F401 +from test.llm.test_tenant_model_pricing import ROOT_PRICE, copies, priced # noqa: F401 ROOT_SUPER = SimpleNamespace(user_id=1, is_global_super=True, tenant_id=ROOT) @pytest.fixture -def tenants(monkeypatch, world): # noqa: F811 +def tenants(monkeypatch, priced): # noqa: F811 monkeypatch.setattr(script.TenantDao, "aget_children_ids_active", AsyncMock(return_value=[CHILD])) monkeypatch.setattr( script.TenantDao, "aget_by_ids", AsyncMock(return_value=[SimpleNamespace(id=CHILD, tenant_name="Child")]) ) - return world + return priced async def test_preview_reports_without_writing_and_apply_writes_the_same_result(tenants): @@ -104,3 +105,15 @@ async def test_the_operator_is_loaded_without_a_web_token(monkeypatch): load.return_value = SimpleNamespace(is_global_super=False, tenant_id=ROOT) with pytest.raises(ValueError, match="Root global-super"): await repair.operator_identity(1) + + +async def test_the_script_also_copies_missing_prices_of_every_non_archived_child(tenants): + """AC-30: the price step runs in the same command; preview writes nothing.""" + preview, code = await script.snapshot_all(identity=ROOT_SUPER, apply=False) + assert code == 0 and preview["prices"] == [{"tenant_id": CHILD, "copied": [101], "root_price_missing": []}] + assert await copies(tenants) == {} + applied, _ = await script.snapshot_all(identity=ROOT_SUPER, apply=True) + assert applied["prices"] == preview["prices"] + assert await copies(tenants) == {(CHILD, 101): ROOT_PRICE} + again, _ = await script.snapshot_all(identity=ROOT_SUPER, apply=True) + assert again["prices"] == [] diff --git a/src/backend/test/llm/test_tenant_model_pricing.py b/src/backend/test/llm/test_tenant_model_pricing.py new file mode 100644 index 0000000000..be76a84190 --- /dev/null +++ b/src/backend/test/llm/test_tenant_model_pricing.py @@ -0,0 +1,186 @@ +"""F005 §2.5: a child tenant keeps its own copy of the price of each Root model shared with it. + +覆盖 AC: AC-24, AC-25, AC-26, AC-27, AC-28, AC-29, AC-30 +""" + +from unittest.mock import AsyncMock + +import pytest +from sqlalchemy import select, update + +from bisheng.common.errcode.llm import ModelPricingConflictError +from bisheng.common.errcode.llm_tenant import LLMModelNotAccessibleError +from bisheng.core import database +from bisheng.core.context.tenant import bypass_tenant_filter, current_tenant_id +from bisheng.core.database import tenant_filter +from bisheng.llm.application import model_sharing_lifecycle as lifecycle +from bisheng.llm.domain.models.llm_server import LLMModel +from bisheng.llm.domain.models.model_tenant_pricing import ModelTenantPricing +from bisheng.llm.domain.pricing import service, tenant_pricing +from test.llm.test_child_model_snapshot import CHILD, ROOT, world # noqa: F401 + +ROOT_PRICE = { + "currency": "CNY", + "input": "2", + "cache_read": "0.5", + "cache_write": None, + "output": "8", + "source": "MANUAL", + "catalog_key": None, + "catalog_version": None, + "ref_key": None, + "revision": 3, +} +CHILD_PRICE = {**ROOT_PRICE, "input": "5", "revision": 1} +OWN_PRICE = {**ROOT_PRICE, "input": "9", "revision": 1} + + +@pytest.fixture +async def priced(world, monkeypatch): # noqa: F811 + """101 (shared, priced by Root), 201 (unshared, priced), 301 (the child's own model, priced).""" + names = {"llm_model_tenant_pricing"} + monkeypatch.setattr(tenant_filter, "_tenant_aware_tables", tenant_filter._tenant_aware_tables | names) + async with world["sessions"]() as session: + await session.run_sync(lambda sync: ModelTenantPricing.__table__.create(sync.connection())) + with bypass_tenant_filter(): + for model_id, price in ((101, ROOT_PRICE), (201, ROOT_PRICE), (301, OWN_PRICE)): + await session.execute( + update(LLMModel).where(LLMModel.id == model_id).values(config={"pricing": price, "keep": 1}) + ) + await session.commit() + monkeypatch.setattr(database, "get_async_db_session", world["sessions"]) + return world + + +async def copies(state): + async with state["sessions"]() as session: + with bypass_tenant_filter(): + rows = (await session.execute(select(ModelTenantPricing))).scalars().all() + return {(row.tenant_id, row.model_id): row.pricing for row in rows} + + +async def root_price(state, model_id=101): + async with state["sessions"]() as session: + with bypass_tenant_filter(): + return (await session.execute(select(LLMModel.config).where(LLMModel.id == model_id))).scalar_one() + + +async def initialize(state, model_ids, child_ids=(CHILD,)): + async with state["sessions"]() as session, session.begin(): + await tenant_pricing.ainitialize_shared_model_pricing( + session, child_ids=list(child_ids), model_ids=list(model_ids), actor_user_id=7 + ) + + +async def test_a_new_receiver_gets_roots_current_price_once(priced): + """AC-24/25/28: copy on first receipt, never over an existing copy; unpriced and non-LLM models get none.""" + await initialize(priced, [101, 102]) + assert await copies(priced) == {(CHILD, 101): ROOT_PRICE} + async with priced["sessions"]() as session, session.begin(): + with bypass_tenant_filter(): + await session.execute(update(ModelTenantPricing).values(pricing=CHILD_PRICE)) + await initialize(priced, [101]) # unshared, then shared again: the child's price stays + assert await copies(priced) == {(CHILD, 101): CHILD_PRICE} + async with priced["sessions"]() as session, session.begin(): + with bypass_tenant_filter(): + await session.execute(update(LLMModel).where(LLMModel.id == 201).values(config={})) + await initialize(priced, [201]) + assert (CHILD, 201) not in await copies(priced) + + +async def test_every_new_receiver_path_initializes_visibility_and_price_together(monkeypatch): + visibility, prices = AsyncMock(), AsyncMock() + monkeypatch.setattr(lifecycle.shared_model_visibility, "initialize_shared_model_visibility", visibility) + monkeypatch.setattr(lifecycle, "ainitialize_shared_model_pricing", prices) + guard = lambda: None # noqa: E731 + await lifecycle.initialize_shared_models( + "session", child_ids=[CHILD], model_ids=[101], actor_user_id=7, plan_id="p", guard=guard + ) + visibility.assert_awaited_once_with( + "session", child_ids=[CHILD], model_ids=[101], actor_user_id=7, plan_id="p", guard=guard + ) + prices.assert_awaited_once_with("session", child_ids=[CHILD], model_ids=[101], actor_user_id=7) + + +async def test_each_tenant_reads_its_own_price_and_a_child_never_reads_roots(priced): + """AC-27/29: Root and owners read the model row; a child reads its copy or nothing.""" + async with priced["sessions"]() as session: + with bypass_tenant_filter(): + models = {row.id: row for row in (await session.execute(select(LLMModel))).scalars()} + + async def read_sync(model_id, tenant_id): + async with priced["sessions"]() as session: + return await session.run_sync(lambda sync: tenant_pricing.read_effective_pricing(sync, model_id, tenant_id)) + + assert await tenant_pricing.aread_effective_pricings([models[101], models[301]], CHILD) == { + 101: None, + 301: OWN_PRICE, + } + assert await read_sync(101, CHILD) is None + await initialize(priced, [101]) + async with priced["sessions"]() as session, session.begin(): + with bypass_tenant_filter(): + await session.execute(update(ModelTenantPricing).values(pricing=CHILD_PRICE)) + assert await tenant_pricing.aread_effective_pricing(models[101], CHILD) == CHILD_PRICE + assert await read_sync(101, CHILD) == CHILD_PRICE + assert await tenant_pricing.aread_effective_pricing(models[101], ROOT) == ROOT_PRICE + assert await read_sync(101, ROOT) == ROOT_PRICE + + +@pytest.fixture +def child_admin(priced): + token = current_tenant_id.set(CHILD) + yield priced + current_tenant_id.reset(token) + + +def resolve(incoming): + return lambda server_type, name, stored: service.resolve_model_pricing( + server_type, name, incoming=incoming, existing=stored + ) + + +EDIT = {"currency": "CNY", "input": "6", "cache_read": "0.5", "output": "8"} + + +async def test_a_child_edit_changes_only_its_copy(child_admin): + """AC-26/27: the edit keeps revision checks, and Root's price does not move.""" + saved = await tenant_pricing.asave_tenant_model_pricing(101, resolve(EDIT), actor_user_id=7) + assert (saved["input"], saved["revision"]) == ("6", 1) # a missing copy is filled in (AC-29) + with pytest.raises(ModelPricingConflictError): + await tenant_pricing.asave_tenant_model_pricing(101, resolve({**EDIT, "revision": 5}), actor_user_id=7) + again = await tenant_pricing.asave_tenant_model_pricing( + 101, resolve({**EDIT, "output": "10", "revision": 1}), actor_user_id=7 + ) + assert (again["output"], again["revision"]) == ("10", 2) + assert await copies(child_admin) == {(CHILD, 101): again} + assert await root_price(child_admin) == {"pricing": ROOT_PRICE, "keep": 1} + + +async def test_a_child_cannot_price_a_model_that_is_not_shared_with_it(child_admin): + with pytest.raises(LLMModelNotAccessibleError): + await tenant_pricing.asave_tenant_model_pricing(201, resolve(EDIT), actor_user_id=7) + with pytest.raises(LLMModelNotAccessibleError): + await tenant_pricing.asave_tenant_model_pricing(301, resolve(EDIT), actor_user_id=7) # not a Root model + token = current_tenant_id.set(ROOT) + try: + with pytest.raises(LLMModelNotAccessibleError): + await tenant_pricing.asave_tenant_model_pricing(101, resolve(EDIT), actor_user_id=7) + finally: + current_tenant_id.reset(token) + assert await copies(child_admin) == {} + + +async def test_the_upgrade_step_previews_then_copies_once_and_lists_roots_missing_prices(priced): + """AC-30.""" + priced["shared"]["ids"] = [10, 20] + async with priced["sessions"]() as session, session.begin(): + with bypass_tenant_filter(): + await session.execute(update(LLMModel).where(LLMModel.id == 201).values(config={})) + preview = await tenant_pricing.abackfill_child_pricing(CHILD, actor_user_id=7, dry_run=True) + assert preview == {"copied": [101], "root_price_missing": [201]} + assert await copies(priced) == {} + assert await tenant_pricing.abackfill_child_pricing(CHILD, actor_user_id=7, dry_run=False) == preview + assert await copies(priced) == {(CHILD, 101): ROOT_PRICE} + again = await tenant_pricing.abackfill_child_pricing(CHILD, actor_user_id=7, dry_run=False) + assert again == {"copied": [], "root_price_missing": [201]}