feat(experiments): 独立注册实验类型并分离用户分组查询

- 实验类型:自定义标识、数据契约、默认值和真实调用后的接入验收

- 测试方案:按类型校验 A/B 值,保留历史分组与预设快照,未验收禁止发布

- 用户管理:真实账号分页搜索、只读预览与有效账号人工指定校验

- 文档与验证:同步迁移014及消费者接口说明,15项核心回归通过
This commit is contained in:
湛兮
2026-10-27 11:40:02 +08:00
parent 7ba4241995
commit 094d0c17e8
10 changed files with 590 additions and 82 deletions
+57 -2
View File
@@ -1,4 +1,14 @@
/** 数字人 API:前台私有会话与后台内容/实验严格分权。 */
import {
experimentTypes,
saveExperimentType,
typeInputSchema,
confirmTypeIntegration,
} from "./digital.experiment-types";
import {
experimentUsers,
assertActiveExperimentAccount,
} from "./digital.experiment-users";
import { env } from "../../config/env";
import { scenes, saveScene, sceneSchema } from "./digital.scenes";
import { randomUUID } from "node:crypto";
@@ -26,7 +36,6 @@ import {
transition,
resolveExperiment,
decide,
accountCreated,
} from "./digital.experiments";
import {
createConversation,
@@ -52,6 +61,22 @@ export async function digitalRoutes(app: FastifyInstance) {
app.register(
async (front) => {
front.addHook("preHandler", userGuard);
front.get("/decisions/:key", async (r) => {
const { key } = z.object({ key: idSchema }).parse(r.params);
const d = await decide(r.user.sub, key);
// 通用消费者不接收服务端预设正文或账号创建信息。
return ok({
variant: d.variant,
reason: d.reason,
experimentId: d.experimentId,
decisionId: d.decisionId,
value: d.value,
typeKey: d.typeKey,
typeRevision: d.typeRevision,
expiresAt: d.expiresAt,
fallbackVariant: d.fallbackVariant,
});
});
front.get("/bootstrap", async (r) => {
const [catalog, profile, decision] = await Promise.all([
rows<ContentRow>(
@@ -355,6 +380,36 @@ export async function digitalRoutes(app: FastifyInstance) {
});
return ok({ saved: true });
});
admin.get("/experiment-types", async () => ok(await experimentTypes()));
admin.put("/experiment-types/:id", async (r) => {
const { id } = params.parse(r.params);
await saveExperimentType(r.user.sub, id, typeInputSchema.parse(r.body));
return ok({ saved: true });
});
admin.post("/experiment-types/:id/integration", async (r) => {
const { id } = params.parse(r.params);
const input = z
.object({
revision: z.number().int().positive(),
contractRevision: z.number().int().positive(),
verified: z.boolean(),
notes: z.string().max(2000),
})
.parse(r.body);
await confirmTypeIntegration(r.user.sub, id, input);
return ok({ saved: true });
});
admin.get("/experiment-users", async (r) => {
const input = z
.object({
q: z.string().max(100).default(""),
page: z.coerce.number().int().min(1).default(1),
size: z.coerce.number().int().min(1).max(50).default(20),
experiment: idSchema.optional(),
})
.parse(r.query);
return ok(await experimentUsers(input));
});
admin.get("/scenes", async () => ok(await scenes()));
admin.put("/scenes/:id", async (r) => {
const { id } = params.parse(r.params);
@@ -440,7 +495,7 @@ export async function digitalRoutes(app: FastifyInstance) {
Date.parse(b.expiresAt) > Date.now() + 30 * 86400000
)
throw badRequest("指定用户有效期须在未来30天内");
await accountCreated(b.account);
await assertActiveExperimentAccount(b.account);
await transaction(async (c) => {
const [e] = await rows<{ state: string }>(
"SELECT state FROM dh_experiments WHERE id=? FOR UPDATE",
@@ -0,0 +1,240 @@
/** 实验类型注册表:业务类型由后台创建,接入证明与运营发布分开。 */
import { z } from "zod";
import type { PoolConnection } from "mysql2/promise";
import { rows, write, json, transaction, audit } from "./digital.repository";
import { badRequest, conflict, notFound } from "../../shared/http-error";
/** 只描述数据契约,不包含可执行脚本或固定业务功能下拉框。 */
export const typeInputSchema = z.object({
name: z.string().trim().min(1).max(120),
description: z.string().max(2000).default(""),
valueType: z.enum(["string", "number", "boolean", "json"]),
defaultValue: z.json(),
enabled: z.boolean().default(true),
revision: z.number().int().positive().optional(),
});
/** 类型数据契约及真实接入状态。 */
export type ExperimentType = {
id: string;
name: string;
description: string;
enabled: number;
builtin: number;
revision: number;
runtime: string | null;
consumerKey: string;
valueType: "string" | "number" | "boolean" | "json";
defaultValue: unknown;
contract: {
fixedValues?: { A: unknown; B: unknown };
labels?: { A: string; B: string };
optionsSource?: string;
};
contractRevision: number;
integrationState: "pending" | "confirmed";
lastSeenAt: Date | null;
lastSeenRevision: number | null;
confirmedAt: Date | null;
confirmedBy: string | null;
integrationNotes: string;
hasPlans: number;
};
const columns = `id,name,description,enabled,builtin,revision,runtime,consumer_key AS consumerKey,value_type AS valueType,CAST(default_value AS CHAR) AS defaultValue,CAST(contract AS CHAR) AS contract,contract_revision AS contractRevision,integration_state AS integrationState,last_seen_at AS lastSeenAt,last_seen_revision AS lastSeenRevision,confirmed_at AS confirmedAt,confirmed_by AS confirmedBy,integration_notes AS integrationNotes,EXISTS(SELECT 1 FROM dh_experiments WHERE scope=dh_scenes.id) AS hasPlans`;
function decode(t: ExperimentType) {
return {
...t,
defaultValue: json(t.defaultValue),
contract: json<ExperimentType["contract"]>(t.contract) ?? {},
};
}
/** 按数据契约验证默认值和方案值,支持false、0及JSON null。 */
export function validateTypeValue(
kind: ExperimentType["valueType"],
value: unknown,
) {
if (kind === "string" && typeof value !== "string")
throw badRequest("该类型必须返回字符串");
if (
kind === "number" &&
(typeof value !== "number" || !Number.isFinite(value))
)
throw badRequest("该类型必须返回有限数字");
if (kind === "boolean" && typeof value !== "boolean")
throw badRequest("该类型必须返回开关值");
if (!z.json().safeParse(value).success)
throw badRequest("返回值必须是有限且可序列化的 JSON 数据");
const encoded = JSON.stringify(value);
if (encoded === undefined || Buffer.byteLength(encoded) > 24000)
throw badRequest("返回值须为有效JSON且不超过24KB");
}
/** 后台类型列表;待接入类型不会被伪装成已生效功能。 */
export async function experimentTypes() {
return (
await rows<ExperimentType>(
`SELECT ${columns} FROM dh_scenes ORDER BY builtin DESC,created_at,id`,
)
).map(decode);
}
/** 写配置时锁住类型契约,避免接入验收和方案发布竞争。 */
export async function experimentType(id: string, c?: PoolConnection) {
const [t] = await rows<ExperimentType>(
`SELECT ${columns} FROM dh_scenes WHERE id=?${c ? " FOR UPDATE" : ""}`,
[id],
c,
);
if (!t) throw notFound("实验类型不存在");
return decode(t);
}
/** 新类型的消费标识就是稳定类型标识,绝不自动绑定到某个预置功能。 */
export async function saveExperimentType(
actor: string,
id: string,
input: z.infer<typeof typeInputSchema>,
) {
validateTypeValue(input.valueType, input.defaultValue);
await transaction(async (c) => {
await rows(
"SELECT version FROM schema_migrations ORDER BY version LIMIT 1 FOR UPDATE",
[],
c,
);
const [raw] = await rows<ExperimentType>(
`SELECT ${columns} FROM dh_scenes WHERE id=? FOR UPDATE`,
[id],
c,
);
const old = raw ? decode(raw) : undefined;
if (!old && !/^[a-z][a-z0-9_-]{1,63}$/.test(id))
throw badRequest(
"类型标识使用2到64位小写字母、数字、下划线或连字符,并以字母开头",
);
if (old && old.revision !== input.revision)
throw conflict("类型已更新,请刷新");
const usage = await rows<{ state: string }>(
"SELECT state FROM dh_experiments WHERE scope=?",
[id],
c,
);
const changed =
!!old &&
(old.valueType !== input.valueType ||
JSON.stringify(old.defaultValue) !==
JSON.stringify(input.defaultValue));
if (changed && (old!.builtin || old!.runtime || usage.length))
throw conflict(
"内置、历史接入或已有方案的类型不能修改数据契约,请创建新类型",
);
if (
!input.enabled &&
usage.some((e) => e.state === "running" || e.state === "paused")
)
throw conflict("请先结束运行或暂停中的方案,再停用类型");
if (old)
await write(
`UPDATE dh_scenes SET name=?,description=?,enabled=?,value_type=?,default_value=?,revision=revision+1,contract_revision=contract_revision+?,integration_state=IF(?,'pending',integration_state),confirmed_at=IF(?,NULL,confirmed_at),confirmed_by=IF(?,NULL,confirmed_by) WHERE id=?`,
[
input.name,
input.description,
input.enabled,
input.valueType,
JSON.stringify(input.defaultValue),
changed ? 1 : 0,
changed,
changed,
changed,
id,
],
c,
);
else
await write(
"INSERT INTO dh_scenes(id,name,runtime,consumer_key,value_type,default_value,contract,description,enabled,builtin) VALUES (?,?,NULL,?,?,?,?,?,?,FALSE)",
[
id,
input.name,
id,
input.valueType,
JSON.stringify(input.defaultValue),
JSON.stringify({}),
input.description,
input.enabled,
],
c,
);
await audit(
actor,
old ? "type.update" : "type.create",
id,
{ ...input, contractChanged: changed },
c,
);
});
}
/** 只有真实消费者的决策调用更新回执;后台预览不会更新。 */
export async function recordTypeRead(id: string, contractRevision: number) {
await write(
"UPDATE dh_scenes SET last_seen_at=NOW(3),last_seen_revision=? WHERE id=? AND contract_revision=?",
[contractRevision, id, contractRevision],
);
}
/** 接口调用只是证据之一,还要求运营明确确认应用已使用返回值并填写验收记录。 */
export async function confirmTypeIntegration(
actor: string,
id: string,
input: {
revision: number;
contractRevision: number;
verified: boolean;
notes: string;
},
) {
if (!input.verified || input.notes.trim().length < 8)
throw badRequest("请确认实际业务已使用返回值,并填写至少8字的验收记录");
await transaction(async (c) => {
await rows(
"SELECT version FROM schema_migrations ORDER BY version LIMIT 1 FOR UPDATE",
[],
c,
);
const t = await experimentType(id, c);
if (
t.revision !== input.revision ||
t.contractRevision !== input.contractRevision
)
throw conflict("类型契约已变更,请重新验收");
if (!t.lastSeenAt || t.lastSeenRevision !== t.contractRevision)
throw conflict("尚未收到当前契约的应用调用,不能确认接入");
await write(
"UPDATE dh_scenes SET integration_state='confirmed',confirmed_at=NOW(3),confirmed_by=?,integration_notes=?,revision=revision+1 WHERE id=?",
[actor, input.notes, id],
c,
);
await audit(actor, "type.integration.confirm", id, input, c);
});
}
/** 对历史预置能力保留原含义,新类型按注册格式校验A/B值。 */
export function normalizePlanValues(
type: ExperimentType,
config: {
values?: { A: unknown; B: unknown };
presetA?: string;
presetB?: string;
},
) {
let values = config.values;
if (type.contract.fixedValues) values = type.contract.fixedValues;
else if (type.contract.optionsSource === "presets")
values = {
A: config.values?.A ?? config.presetA ?? "",
B: config.values?.B ?? config.presetB ?? "",
};
if (!values) throw badRequest("请分别配置A组和B组的返回值");
validateTypeValue(type.valueType, values.A);
validateTypeValue(type.valueType, values.B);
return {
...config,
values,
...(type.contract.optionsSource === "presets"
? { presetA: String(values.A), presetB: String(values.B) }
: {}),
};
}
@@ -0,0 +1,89 @@
/** 独立用户分组查询,读取不产生分组或曝光,人工指定沿用既有审计接口。 */
import { rows } from "./digital.repository";
import {
experiments,
resolveExperiment,
planValue,
} from "./digital.experiments";
import { experimentType } from "./digital.experiment-types";
import { notFound } from "../../shared/http-error";
const accountUnion = `SELECT CONCAT('employee:',e.id) account,e.phone username,e.name,e.status,e.created_at AS createdAt FROM employees e WHERE e.deleted_at IS NULL UNION ALL SELECT CONCAT('super_admin:',a.id) account,a.username,a.display_name name,a.status,a.created_at FROM super_admins a`;
/** 搜索账号、姓名或ID,按页最多50人,精确呈现所选方案的预览与人工指定记录。 */
export async function experimentUsers(input: {
q: string;
page: number;
size: number;
experiment?: string;
}) {
const escaped = "%" + input.q.replace(/[=%_]/g, "=$&") + "%";
const where = input.q
? "WHERE (account LIKE ? ESCAPE '=' OR username LIKE ? ESCAPE '=' OR name LIKE ? ESCAPE '=')"
: "";
const args = input.q ? [escaped, escaped, escaped] : [];
const [count] = await rows<{ total: number }>(
`SELECT COUNT(*) total FROM (${accountUnion}) accounts ${where}`,
args,
);
const accounts = await rows<{
account: string;
username: string;
name: string;
status: string;
createdAt: Date;
}>(
`SELECT * FROM (${accountUnion}) accounts ${where} ORDER BY account LIMIT ? OFFSET ?`,
[...args, input.size, (input.page - 1) * input.size],
);
const plan = input.experiment
? (await experiments()).find((e) => e.id === input.experiment)
: undefined;
if (input.experiment && !plan) throw notFound("测试方案不存在");
const type = plan ? await experimentType(plan.scope) : undefined;
const items = await Promise.all(
accounts.map(async (a) => {
if (!plan)
return { ...a, decision: null, override: null, assignment: null };
const [decision, overrides, assignments] = await Promise.all([
resolveExperiment(plan, a.account, true),
rows<{
variant: string;
reason: string;
expiresAt: Date;
bypassAudience: number;
}>(
"SELECT variant,reason,expires_at AS expiresAt,bypass_audience AS bypassAudience FROM dh_overrides WHERE experiment_id=? AND account=?",
[plan.id, a.account],
),
rows<{ variant: string; createdAt: Date }>(
"SELECT variant,created_at AS createdAt FROM dh_assignments WHERE experiment_id=? AND account=?",
[plan.id, a.account],
),
]);
return {
...a,
decision: {
...decision,
presetSnapshot: undefined,
value: planValue(plan, decision.variant, type?.defaultValue),
},
override: overrides[0] ?? null,
assignment: assignments[0] ?? null,
};
}),
);
return {
items,
total: Number(count.total),
page: input.page,
size: input.size,
};
}
/** 只允许给仍可登录的真实账号设置人工分组。 */
export async function assertActiveExperimentAccount(account: string) {
const [user] = await rows<{ status: string }>(
`SELECT status FROM (${accountUnion}) accounts WHERE account=?`,
[account],
);
if (!user || user.status !== "ACTIVE")
throw notFound("账号不存在或已停用,不能指定分组");
}
+66 -18
View File
@@ -1,5 +1,9 @@
/** 后台实验生命周期与账号稳定分配;前台只消费短时决策并回报曝光。 */
import { scene } from "./digital.scenes";
import {
experimentType as scene,
normalizePlanValues,
recordTypeRead,
} from "./digital.experiment-types";
import { createHash, randomUUID } from "node:crypto";
import type { PoolConnection } from "mysql2/promise";
import type { z } from "zod";
@@ -18,7 +22,10 @@ export type Experiment = {
id: string;
name: string;
scope: string;
runtime: "ui" | "chat";
runtime: string | null;
consumerKey: string;
integrationState: string;
defaultValue: unknown;
sceneEnabled: number;
state: "draft" | "running" | "paused" | "finished";
config: Config;
@@ -48,7 +55,7 @@ export function eligible(config: Config, account: string, createdAt: string) {
export async function experiments() {
return (
await rows<Experiment>(
"SELECT e.*,s.runtime,s.name AS sceneName,s.enabled AS sceneEnabled FROM dh_experiments e JOIN dh_scenes s ON s.id=e.scope ORDER BY e.created_at DESC LIMIT 200",
"SELECT e.*,s.runtime,s.consumer_key AS consumerKey,s.integration_state AS integrationState,s.default_value AS defaultValue,s.name AS sceneName,s.name AS typeName,s.enabled AS sceneEnabled FROM dh_experiments e JOIN dh_scenes s ON s.id=e.scope ORDER BY e.created_at DESC,e.id DESC",
)
).map((e) => ({ ...e, config: json<Config>(e.config) }));
}
@@ -82,7 +89,12 @@ export async function saveExperiment(
c,
);
const registered = await scene(input.scope, c);
if (!registered.enabled) throw badRequest("场景已停用,不能创建或编辑实验");
if (!registered.enabled) throw badRequest("类型已停用,不能创建或编辑方案");
const config = {
...input.config,
...normalizePlanValues(registered, input.config),
typeRevision: registered.contractRevision,
};
const [old] = await rows<Experiment>(
"SELECT * FROM dh_experiments WHERE id=? FOR UPDATE",
[id],
@@ -93,13 +105,13 @@ export async function saveExperiment(
if (old)
await write(
"UPDATE dh_experiments SET name=?,scope=?,config=?,revision=revision+1 WHERE id=?",
[input.name, input.scope, JSON.stringify(input.config), id],
[input.name, input.scope, JSON.stringify(config), id],
c,
);
else
await write(
"INSERT INTO dh_experiments(id,name,scope,config) VALUES (?,?,?,?)",
[id, input.name, input.scope, JSON.stringify(input.config)],
[id, input.name, input.scope, JSON.stringify(config)],
c,
);
await audit(
@@ -148,18 +160,25 @@ export async function transition(
};
const registered = await scene(e.scope, c);
if (state === "running") {
if (!registered.enabled) throw badRequest("场景已停用,不能启动实验");
if (!registered.enabled) throw badRequest("类型已停用,不能启动方案");
if (registered.integrationState !== "confirmed")
throw conflict("该类型尚未完成应用接入验收,请先到实验类型页确认接入");
if (
config.typeRevision &&
config.typeRevision !== registered.contractRevision
)
throw conflict("类型契约已变更,请重新保存草稿");
if (config.audience === "specified" && !config.accounts.length)
throw badRequest("指定名单不能为空");
const others = await rows(
"SELECT e.id FROM dh_experiments e JOIN dh_scenes s ON s.id=e.scope WHERE s.runtime=? AND e.id<>? AND e.state IN ('running','paused')",
[registered.runtime, id],
"SELECT e.id FROM dh_experiments e JOIN dh_scenes s ON s.id=e.scope WHERE s.consumer_key=? AND e.id<>? AND e.state IN ('running','paused')",
[registered.consumerKey, id],
c,
);
if (others.length)
throw conflict(
"该应用接入点已有未结束的实验,请先结束,避免多个场景同时控制同一功能",
);
throw conflict("该类型的消费标识已有未结束方案,请先结束现有方案");
const cfg = config;
if (registered.runtime === "chat" && !cfg.presetSnapshots) {
if (registered.consumerKey === "chat" && !cfg.presetSnapshots) {
if (!cfg.presetA || !cfg.presetB)
throw badRequest("对话实验须分别选择两个已发布预设");
const available = await rows<{ id: string; body: unknown }>(
@@ -262,18 +281,41 @@ export async function resolveExperiment(
};
}
/** 从已按创建时间排序的场景实验中选择当前接入点的有效配置。 */
export function activeExperiment(list: Experiment[], runtime: "ui" | "chat") {
export function activeExperiment(list: Experiment[], runtime: string) {
const candidates = list.filter(
(e) => e.runtime === runtime && !!e.sceneEnabled && e.state !== "draft",
(e) =>
(e.consumerKey ?? e.runtime) === runtime &&
!!e.sceneEnabled &&
e.state !== "draft",
);
return (
candidates.find((e) => e.state === "running" || e.state === "paused") ??
candidates[0]
);
}
/** 历史方案没有typed values时保留原UI/预设含义,不重算账号分组。 */
export function planValue(
e: Experiment,
variant: "A" | "B",
fallback: unknown,
) {
if (e.config.values && Object.hasOwn(e.config.values, variant))
return e.config.values[variant];
const consumer = e.consumerKey ?? e.runtime;
if (consumer === "ui") return variant === "A" ? "old" : "new";
if (consumer === "chat")
return variant === "A"
? (e.config.presetA ?? fallback)
: (e.config.presetB ?? fallback);
return fallback;
}
/** 返回前台所需最小决策,规则、指定名单和提示词均不下发。 */
export async function decide(account: string, scope: "ui" | "chat") {
const e = activeExperiment(await experiments(), scope);
export async function decide(account: string, scope: string) {
const type = await scene(scope);
await recordTypeRead(type.id, type.contractRevision);
const e = type.enabled
? activeExperiment(await experiments(), type.consumerKey)
: undefined;
if (!e)
return {
variant: "A" as const,
@@ -283,6 +325,9 @@ export async function decide(account: string, scope: "ui" | "chat") {
experimentId: null,
presetId: undefined,
presetSnapshot: undefined,
value: type.defaultValue,
typeKey: type.id,
typeRevision: type.contractRevision,
expiresAt: Date.now() + 60000,
};
const d = await resolveExperiment(e, account);
@@ -297,6 +342,9 @@ export async function decide(account: string, scope: "ui" | "chat") {
);
return {
...d,
value: planValue(e, d.variant, type.defaultValue),
typeKey: type.id,
typeRevision: type.contractRevision,
decisionId,
fallbackVariant:
e.state === "finished"
@@ -329,7 +377,7 @@ export async function trackUiEvent(
`INSERT IGNORE INTO dh_events(experiment_id,decision_id,account,variant,cohort,event_name,conversation_id,request_id)
SELECT d.experiment_id,d.id,d.account,d.variant,IF(d.reason='override','manual','random'),?,?,?
FROM dh_decisions d JOIN dh_experiments e ON e.id=d.experiment_id JOIN dh_scenes s ON s.id=e.scope
WHERE d.id=? AND d.account=? AND s.runtime='ui' AND d.reason IN ('allocated','sticky','override') AND ${validity}`,
WHERE d.id=? AND d.account=? AND s.consumer_key='ui' AND d.reason IN ('allocated','sticky','override') AND ${validity}`,
[
event,
conversationId,
+9 -58
View File
@@ -1,8 +1,7 @@
/** 场景注册与启停;场景映射到现有应用接入点,不执行任意代码。 */
/** 历史场景只读兼容;新类型使用独立注册表。 */
import { z } from "zod";
import type { PoolConnection } from "mysql2/promise";
import { rows, write, audit, transaction } from "./digital.repository";
import { badRequest, conflict, notFound } from "../../shared/http-error";
import { rows } from "./digital.repository";
import { badRequest } from "../../shared/http-error";
/** 场景编辑契约,版本号保护并发编辑。 */
export const sceneSchema = z.object({
name: z.string().trim().min(1).max(120),
@@ -24,62 +23,14 @@ export type Scene = {
/** 已注册场景,包括停用场景以便解释历史实验。 */
export async function scenes() {
return rows<Scene>(
"SELECT * FROM dh_scenes ORDER BY builtin DESC,created_at,id",
"SELECT * FROM dh_scenes WHERE runtime IS NOT NULL ORDER BY builtin DESC,created_at,id",
);
}
/** 查询场景并在配置事务内锁定映射,避免修改执行类型与发布竞争。 */
export async function scene(id: string, c?: PoolConnection) {
const [s] = await rows<Scene>(
`SELECT * FROM dh_scenes WHERE id=?${c ? " FOR UPDATE" : ""}`,
[id],
c,
);
if (!s) throw notFound("实验场景不存在,请先创建场景");
return s;
}
/** 已使用场景不能切换接入点;运行/暂停中的场景不可停用。 */
/** 兼容旧版缓存后台的失败响应,禁止再创建固定能力的场景别名。 */
export async function saveScene(
actor: string,
id: string,
input: z.infer<typeof sceneSchema>,
_actor: string,
_id: string,
_input: z.infer<typeof sceneSchema>,
) {
await transaction(async (c) => {
await rows(
"SELECT version FROM schema_migrations ORDER BY version LIMIT 1 FOR UPDATE",
[],
c,
);
const [old] = await rows<Scene>(
"SELECT * FROM dh_scenes WHERE id=? FOR UPDATE",
[id],
c,
);
if (old && old.revision !== input.revision)
throw conflict("场景已更新,请刷新后重试");
const usage = await rows<{ state: string }>(
"SELECT state FROM dh_experiments WHERE scope=?",
[id],
c,
);
if (old && old.runtime !== input.runtime && (old.builtin || usage.length))
throw badRequest("系统预置或已用于实验的场景不能更换接入点");
if (
!input.enabled &&
usage.some((e) => e.state === "running" || e.state === "paused")
)
throw conflict("请先结束该场景的运行/暂停实验,再停用场景");
if (old)
await write(
"UPDATE dh_scenes SET name=?,runtime=?,description=?,enabled=?,revision=revision+1 WHERE id=?",
[input.name, input.runtime, input.description, input.enabled, id],
c,
);
else
await write(
"INSERT INTO dh_scenes(id,name,runtime,description,enabled) VALUES (?,?,?,?,?)",
[id, input.name, input.runtime, input.description, input.enabled],
c,
);
await audit(actor, old ? "scene.update" : "scene.create", id, input, c);
});
throw badRequest("场景入口已升级,请刷新后台后使用「实验类型」创建入口");
}
+2
View File
@@ -70,6 +70,8 @@ export const experimentSchema = z.object({
presetA: idSchema.optional(),
presetB: idSchema.optional(),
description: z.string().max(2000).default(""),
values: z.object({ A: z.json(), B: z.json() }).optional(),
typeRevision: z.number().int().positive().optional(),
}),
});
/** 用户自己的会话配置,不包含实验或服务端模型选择。 */