feat(experiments): 新增后台场景注册与应用接入映射

保留已有ui/chat场景与分组,支持命名、创建和停用;同一应用接入点实验互斥,保护历史场景类型与运行实验;增加自定义场景决策回归。
This commit is contained in:
湛兮
2026-10-27 11:01:52 +08:00
parent fd0b039729
commit 2e3a7c0a7e
7 changed files with 257 additions and 32 deletions
+23 -2
View File
@@ -1,5 +1,6 @@
/** 数字人 API:前台私有会话与后台内容/实验严格分权。 */
import { env } from "../../config/env";
import { scenes, saveScene, sceneSchema } from "./digital.scenes";
import { randomUUID } from "node:crypto";
import type { FastifyInstance, FastifyRequest } from "fastify";
import { z } from "zod";
@@ -128,7 +129,15 @@ export async function digitalRoutes(app: FastifyInstance) {
front.get("/conversations/:id", async (r) => {
const { id } = params.parse(r.params);
const c = await ownConversation(id, r.user.sub);
const messages = await rows<{id:string;role:string;content:string;status:string;pinned:number;sequenceId:number;createdAt:Date}>(
const messages = await rows<{
id: string;
role: string;
content: string;
status: string;
pinned: number;
sequenceId: number;
createdAt: Date;
}>(
"SELECT id,role,content,status,pinned,sequence_id AS sequenceId,created_at AS createdAt FROM dh_messages WHERE conversation_id=? ORDER BY sequence_id DESC LIMIT 300",
[id],
);
@@ -141,7 +150,13 @@ export async function digitalRoutes(app: FastifyInstance) {
title: c.title,
settings: c.settings,
busy,
messages: messages.reverse().map(m=>!busy&&m.status==='generating'?{...m,status:'stopped'}:m),
messages: messages
.reverse()
.map((m) =>
!busy && m.status === "generating"
? { ...m, status: "stopped" }
: m,
),
});
});
front.patch("/conversations/:id", async (r) => {
@@ -340,6 +355,12 @@ export async function digitalRoutes(app: FastifyInstance) {
});
return ok({ saved: true });
});
admin.get("/scenes", async () => ok(await scenes()));
admin.put("/scenes/:id", async (r) => {
const { id } = params.parse(r.params);
await saveScene(r.user.sub, id, sceneSchema.parse(r.body));
return ok({ saved: true });
});
admin.get("/experiments", async () => ok(await experiments()));
admin.put("/experiments/:id", async (r) => {
const { id } = params.parse(r.params);
+34 -13
View File
@@ -1,4 +1,5 @@
/** 后台实验生命周期与账号稳定分配;前台只消费短时决策并回报曝光。 */
import { scene } from "./digital.scenes";
import { createHash, randomUUID } from "node:crypto";
import type { PoolConnection } from "mysql2/promise";
import type { z } from "zod";
@@ -16,7 +17,9 @@ type Config = z.infer<typeof experimentSchema>["config"] & {
export type Experiment = {
id: string;
name: string;
scope: "ui" | "chat";
scope: string;
runtime: "ui" | "chat";
sceneEnabled: number;
state: "draft" | "running" | "paused" | "finished";
config: Config;
revision: number;
@@ -45,7 +48,7 @@ export function eligible(config: Config, account: string, createdAt: string) {
export async function experiments() {
return (
await rows<Experiment>(
"SELECT * FROM dh_experiments ORDER BY created_at DESC LIMIT 200",
"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",
)
).map((e) => ({ ...e, config: json<Config>(e.config) }));
}
@@ -73,6 +76,13 @@ export async function saveExperiment(
)
throw badRequest("新老用户实验必须设置注册时间分界");
return transaction(async (c) => {
await rows(
"SELECT version FROM schema_migrations ORDER BY version LIMIT 1 FOR UPDATE",
[],
c,
);
const registered = await scene(input.scope, c);
if (!registered.enabled) throw badRequest("场景已停用,不能创建或编辑实验");
const [old] = await rows<Experiment>(
"SELECT * FROM dh_experiments WHERE id=? FOR UPDATE",
[id],
@@ -136,15 +146,20 @@ export async function transition(
...json<Config>(e.config),
...(winner ? { winner } : {}),
};
const registered = await scene(e.scope, c);
if (state === "running") {
if (!registered.enabled) throw badRequest("场景已停用,不能启动实验");
const others = await rows(
"SELECT id FROM dh_experiments WHERE scope=? AND id<>? AND state IN ('running','paused')",
[e.scope, id],
"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],
c,
);
if (others.length) throw conflict("此场景已有未结束的实验");
if (others.length)
throw conflict(
"该应用接入点已有未结束的实验,请先结束,避免多个场景同时控制同一功能",
);
const cfg = config;
if (e.scope === "chat" && !cfg.presetSnapshots) {
if (registered.runtime === "chat" && !cfg.presetSnapshots) {
if (!cfg.presetA || !cfg.presetB)
throw badRequest("对话实验须分别选择两个已发布预设");
const available = await rows<{ id: string; body: unknown }>(
@@ -246,13 +261,19 @@ export async function resolveExperiment(
presetSnapshot: cfg.presetSnapshots?.[variant],
};
}
/** 从已按创建时间排序的场景实验中选择当前接入点的有效配置。 */
export function activeExperiment(list: Experiment[], runtime: "ui" | "chat") {
const candidates = list.filter(
(e) => e.runtime === runtime && !!e.sceneEnabled && e.state !== "draft",
);
return (
candidates.find((e) => e.state === "running" || e.state === "paused") ??
candidates[0]
);
}
/** 返回前台所需最小决策,规则、指定名单和提示词均不下发。 */
export async function decide(account: string, scope: "ui" | "chat") {
const list = (await experiments()).filter(
(e) => e.scope === scope && e.state !== "draft",
);
const e =
list.find((e) => e.state === "running" || e.state === "paused") ?? list[0];
const e = activeExperiment(await experiments(), scope);
if (!e)
return {
variant: "A" as const,
@@ -307,8 +328,8 @@ export async function trackUiEvent(
await write(
`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
WHERE d.id=? AND d.account=? AND e.scope='ui' AND d.reason IN ('allocated','sticky','override') AND ${validity}`,
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}`,
[
event,
conversationId,
+85
View File
@@ -0,0 +1,85 @@
/** 场景注册与启停;场景映射到现有应用接入点,不执行任意代码。 */
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";
/** 场景编辑契约,版本号保护并发编辑。 */
export const sceneSchema = z.object({
name: z.string().trim().min(1).max(120),
runtime: z.enum(["ui", "chat"]),
description: z.string().max(2000).default(""),
enabled: z.boolean().default(true),
revision: z.number().int().positive().optional(),
});
/** 后台场景记录。 */
export type Scene = {
id: string;
name: string;
runtime: "ui" | "chat";
description: string;
enabled: number;
builtin: number;
revision: number;
};
/** 已注册场景,包括停用场景以便解释历史实验。 */
export async function scenes() {
return rows<Scene>(
"SELECT * FROM dh_scenes 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>,
) {
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);
});
}
+1 -1
View File
@@ -55,7 +55,7 @@ export type ContentInput = z.infer<typeof contentSchema>;
/** 实验配置仅通过后台写入,分组语义在同一实验生命周期中固定。 */
export const experimentSchema = z.object({
name: z.string().min(1).max(120),
scope: z.enum(["ui", "chat"]),
scope: idSchema,
config: z.object({
audience: z.enum(["all", "new", "existing", "specified"]).default("all"),
cutoff: z.iso.datetime().optional(),