feat(experiments): 发布 A 至 Z 动态多组分流 #10
@@ -831,3 +831,11 @@ docker compose ps
|
||||
`016_remove_builtin_experiment_types.sql` 在事务中清理历史系统预置的 `ui`、`chat` 类型及其方案、分组、人工指定、决策和漏斗事件,并写入清理审计;用户自己创建的类型(包括 `ui-new-old`)及其数据保留。历史迁移不改写,新库执行完整迁移后也不会留下这两条预置类型。执行前应确认目标环境,并按现有数据库迁移流程发布。
|
||||
|
||||
未注册 `ui` / `chat` 时,应用启动沿用默认界面,聊天沿用会话或角色预设;不会自动创建类型或生成接入记录。通用决策接口请求未注册类型仍返回 404。后台不再预选 UI 类型,验收示例要求用户自行选择已创建并接入的类型。
|
||||
|
||||
### 多组实验配置
|
||||
|
||||
`src/modules/digital/digital.experiment-groups.ts` 负责组配置解码、历史双组兼容和多组哈希区间。新方案的 `config.groups` 为 1~26 个 `{key, weight, value}`:组别只能是唯一的 A~Z,`weight` 为 0~10000 的整数万分比,合计必须为10000(100%);每组 `value` 都须符合类型数据格式,即使该组是0%。默认创建 A/B 两行,允许添加、删除和平均分配,不自动保存或启动。
|
||||
|
||||
不再配置默认组:草稿、暂停、不符合人群或未进入实验流量的账号均返回类型默认值,决策 `variant=null`,不会记录实验曝光。0%组不参与自动分流,但允许人工指定;结束时可保留任意已配置组,不能选择不存在的组。启动后组别、比例和返回值冻结,恢复保持已保存分组。
|
||||
|
||||
旧JSON配置只在读取时转换,保留原B组低位哈希区间和稳定分组,无需数据库DDL或批量迁移。用户端使用决策的 `value` 消费功能,不能以 `variant === 'B'` 作为通用新版判断。当前UI消费者识别 `new` / `true` 为新版,其他值为旧版;这不等于自动接入任意新建类型。
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
|
||||
## 实验
|
||||
|
||||
后台创建草稿后启动;运行后规则冻结,支持暂停/恢复,结束必须选择最终A/B方案且不能重开。同一类型消费标识仅允许一个未结束方案。新老用户由真实账号创建时间与显式注册分界定义。流量与组别采用独立哈希域;人工指定有原因、有效期和人群绕过开关。预览解释不分组、不曝光。前台无实验控制,短时决策过期后回默认方案。
|
||||
后台创建草稿后启动;运行后规则冻结,支持暂停/恢复,结束必须选择最终保留的配置组且不能重开。同一类型消费标识仅允许一个未结束方案。新老用户由真实账号创建时间与显式注册分界定义。流量与组别采用独立哈希域;人工指定有原因、有效期和人群绕过开关。预览解释不分组、不曝光。前台无实验控制,短时决策过期后回类型默认返回值(无组别)。
|
||||
|
||||
## 初始化与验证
|
||||
|
||||
@@ -31,11 +31,11 @@
|
||||
|
||||
## 指标与审计边界
|
||||
|
||||
未入组、默认方案、暂停和结束状态不会污染实验曝光。人工指定与规则分组分别统计。UI 漏斗覆盖开启会话、发送消息、回复完成/停止/失败,前台只携带服务端签发的不透明 decisionId,组别与账号归属均由服务端校验。对话预设在实验首次启动时冻结正文,避免后台编辑原预设改变已运行实验。
|
||||
未入组、类型默认返回值、暂停和结束状态不会污染实验曝光。人工指定与规则分组分别统计。UI 漏斗覆盖开启会话、发送消息、回复完成/停止/失败,前台只携带服务端签发的不透明 decisionId,组别与账号归属均由服务端校验。对话预设在实验首次启动时冻结正文,避免后台编辑原预设改变已运行实验。
|
||||
|
||||
## 类型、方案与用户管理
|
||||
|
||||
三个后台入口分开:实验类型定义稳定 key、返回值格式和默认值;测试方案定义类型下的 A/B 返回值、人群、百分比和发布状态;用户管理按方案查人、预览分组、人工指定或恢复自动。
|
||||
三个后台入口分开:实验类型定义稳定 key、返回值格式和默认值;测试方案定义类型下的 A~Z 各组返回值、人群、分流比例(合计100%)和发布状态;用户管理按方案查人、预览分组、人工指定或恢复自动。
|
||||
|
||||
新类型由用户在后台创建,不再选择固定 UI/chat 接入点。创建后状态为待应用调用:应用使用登录会话请求 `GET /api/digital/decisions/:key` 并把 `data.value` 用于真实功能;后台收到当前契约调用证据后,管理员填写业务验收记录并确认,才能启动方案。调用接口不等于功能已实现,类型页清楚区分待应用调用、待业务验收和已确认接入。当前 UI 与服务端预设类型有明确系统来源,迁移014保留原有方案与分组。
|
||||
|
||||
|
||||
@@ -29,8 +29,13 @@ import {
|
||||
contentSchema,
|
||||
experimentSchema,
|
||||
idSchema,
|
||||
groupKeySchema,
|
||||
settingsSchema,
|
||||
} from "./digital.schema";
|
||||
import {
|
||||
decodeExperimentConfig,
|
||||
hasExperimentGroup,
|
||||
} from "./digital.experiment-groups";
|
||||
import {
|
||||
experiments,
|
||||
saveExperiment,
|
||||
@@ -73,6 +78,7 @@ export async function digitalRoutes(app: FastifyInstance) {
|
||||
experimentId: d.experimentId,
|
||||
decisionId: d.decisionId,
|
||||
value: d.value,
|
||||
fallbackValue: d.fallbackValue,
|
||||
typeKey: d.typeKey,
|
||||
typeRevision: d.typeRevision,
|
||||
expiresAt: d.expiresAt,
|
||||
@@ -92,6 +98,8 @@ export async function digitalRoutes(app: FastifyInstance) {
|
||||
]);
|
||||
const publicDecision = {
|
||||
variant: decision.variant,
|
||||
value: decision.value,
|
||||
fallbackValue: decision.fallbackValue,
|
||||
decisionId: decision.decisionId,
|
||||
experimentId: decision.experimentId,
|
||||
expiresAt: decision.expiresAt,
|
||||
@@ -458,7 +466,7 @@ export async function digitalRoutes(app: FastifyInstance) {
|
||||
.object({
|
||||
state: z.enum(["running", "paused", "finished"]),
|
||||
revision: z.number().int().positive(),
|
||||
winner: z.enum(["A", "B"]).optional(),
|
||||
winner: groupKeySchema.optional(),
|
||||
})
|
||||
.parse(r.body);
|
||||
await transition(r.user.sub, id, b.state, b.revision, b.winner);
|
||||
@@ -508,7 +516,7 @@ export async function digitalRoutes(app: FastifyInstance) {
|
||||
b = z
|
||||
.object({
|
||||
account: accountSchema,
|
||||
variant: z.enum(["A", "B"]),
|
||||
variant: groupKeySchema,
|
||||
reason: z.string().min(2).max(500),
|
||||
bypassAudience: z.boolean().default(false),
|
||||
expiresAt: z.iso.datetime(),
|
||||
@@ -521,13 +529,20 @@ export async function digitalRoutes(app: FastifyInstance) {
|
||||
throw badRequest("指定用户有效期须在未来30天内");
|
||||
await assertActiveExperimentAccount(b.account);
|
||||
await transaction(async (c) => {
|
||||
const [e] = await rows<{ state: string }>(
|
||||
"SELECT state FROM dh_experiments WHERE id=? FOR UPDATE",
|
||||
const [e] = await rows<{ state: string; config: unknown }>(
|
||||
"SELECT state,config FROM dh_experiments WHERE id=? FOR UPDATE",
|
||||
[id],
|
||||
c,
|
||||
);
|
||||
if (!e || e.state === "finished")
|
||||
throw conflict("实验不存在或已结束");
|
||||
if (
|
||||
!hasExperimentGroup(
|
||||
decodeExperimentConfig(json(e.config)),
|
||||
b.variant,
|
||||
)
|
||||
)
|
||||
throw badRequest("指定组不属于该测试方案");
|
||||
await write(
|
||||
"INSERT INTO dh_overrides(experiment_id,account,variant,reason,bypass_audience,expires_at) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE variant=VALUES(variant),reason=VALUES(reason),bypass_audience=VALUES(bypass_audience),expires_at=VALUES(expires_at)",
|
||||
[
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
/** 多组分流与历史配置解码;新方案不再包含默认组或固定B组比例。 */
|
||||
import { z } from "zod";
|
||||
import {
|
||||
experimentSchema,
|
||||
experimentGroupsSchema,
|
||||
type ContentInput,
|
||||
} from "./digital.schema";
|
||||
/** 分组配置在保存和启动后保持稳定,返回值可为false、0或null。 */
|
||||
export type ExperimentConfig = z.infer<typeof experimentSchema>["config"] & {
|
||||
presetSnapshots?: Record<string, ContentInput["body"]>;
|
||||
};
|
||||
/** 单次实验中的组配置。 */
|
||||
export type ExperimentGroup = ExperimentConfig["groups"][number];
|
||||
/** 只读升级历史双组配置;保留旧哈希区间,不重分配已存在账号。 */
|
||||
export function decodeExperimentConfig(
|
||||
raw: unknown,
|
||||
consumerKey?: string,
|
||||
): ExperimentConfig {
|
||||
const c = raw as ExperimentConfig & {
|
||||
weightB?: number;
|
||||
baseline?: string;
|
||||
values?: Record<string, unknown>;
|
||||
presetA?: string;
|
||||
presetB?: string;
|
||||
};
|
||||
if (c.groups) return c;
|
||||
const value = (key: string): ExperimentGroup["value"] =>
|
||||
c.values && Object.hasOwn(c.values, key)
|
||||
? z.json().parse(c.values[key])
|
||||
: consumerKey === "ui"
|
||||
? key === "A"
|
||||
? "old"
|
||||
: "new"
|
||||
: consumerKey === "chat"
|
||||
? ((key === "A" ? c.presetA : c.presetB) ?? "")
|
||||
: null;
|
||||
const weightB = c.weightB ?? 5000;
|
||||
// 旧算法以B占据低位区间;保留这个顺序才能保证尚未落库的历史分组也稳定。
|
||||
const groups = [
|
||||
{ key: "B", weight: weightB, value: value("B") },
|
||||
{ key: "A", weight: 10000 - weightB, value: value("A") },
|
||||
];
|
||||
const {
|
||||
weightB: _weight,
|
||||
baseline: _baseline,
|
||||
values: _values,
|
||||
presetA: _a,
|
||||
presetB: _b,
|
||||
...rest
|
||||
} = c;
|
||||
return { ...rest, groups: experimentGroupsSchema.parse(groups) };
|
||||
}
|
||||
/** 半开区间覆盖全部流量;0%组从不命中自动分流。 */
|
||||
export function groupAtBucket(
|
||||
groups: ExperimentGroup[],
|
||||
point: number,
|
||||
): string {
|
||||
if (!Number.isInteger(point) || point < 0 || point >= 10000)
|
||||
throw new Error("分流位置须在0到9999之间");
|
||||
let end = 0;
|
||||
for (const group of groups) {
|
||||
end += group.weight;
|
||||
if (point < end) return group.key;
|
||||
}
|
||||
throw new Error("分组比例未覆盖当前流量,请检查配置");
|
||||
}
|
||||
/** 判断人工指定或保留结果引用的组是否仍属于本实验。 */
|
||||
export function hasExperimentGroup(config: ExperimentConfig, key: string) {
|
||||
return config.groups.some((g) => g.key === key);
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
/** 实验类型注册表:业务类型由后台创建,接入证明与运营发布分开。 */
|
||||
import { z } from "zod";
|
||||
import { experimentGroupsSchema } from "./digital.schema";
|
||||
import type { ExperimentGroup } from "./digital.experiment-groups";
|
||||
import type { PoolConnection } from "mysql2/promise";
|
||||
import { rows, write, json, transaction, audit } from "./digital.repository";
|
||||
import { badRequest, conflict, notFound } from "../../shared/http-error";
|
||||
@@ -216,30 +218,12 @@ export async function confirmTypeIntegration(
|
||||
await audit(actor, "type.integration.confirm", id, input, c);
|
||||
});
|
||||
}
|
||||
/** 对历史预置能力保留原含义,新类型按注册格式校验A/B值。 */
|
||||
/** 每个组独立校验返回值,0%组也必须符合类型契约。 */
|
||||
export function normalizePlanValues(
|
||||
type: ExperimentType,
|
||||
config: {
|
||||
values?: { A: unknown; B: unknown };
|
||||
presetA?: string;
|
||||
presetB?: string;
|
||||
},
|
||||
config: { groups: ExperimentGroup[] },
|
||||
) {
|
||||
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) }
|
||||
: {}),
|
||||
};
|
||||
const groups = experimentGroupsSchema.parse(config.groups);
|
||||
for (const group of groups) validateTypeValue(type.valueType, group.value);
|
||||
return { groups };
|
||||
}
|
||||
|
||||
@@ -5,19 +5,19 @@ import {
|
||||
normalizePlanValues,
|
||||
recordTypeRead,
|
||||
} from "./digital.experiment-types";
|
||||
import {
|
||||
decodeExperimentConfig,
|
||||
groupAtBucket,
|
||||
hasExperimentGroup,
|
||||
type ExperimentConfig,
|
||||
} from "./digital.experiment-groups";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import type { PoolConnection } from "mysql2/promise";
|
||||
import type { z } from "zod";
|
||||
import {
|
||||
contentSchema,
|
||||
type ContentInput,
|
||||
experimentSchema,
|
||||
} from "./digital.schema";
|
||||
import { contentSchema, experimentSchema } from "./digital.schema";
|
||||
import { rows, write, json, audit, transaction } from "./digital.repository";
|
||||
import { badRequest, conflict, notFound } from "../../shared/http-error";
|
||||
type Config = z.infer<typeof experimentSchema>["config"] & {
|
||||
presetSnapshots?: { A: ContentInput["body"]; B: ContentInput["body"] };
|
||||
};
|
||||
type Config = ExperimentConfig;
|
||||
/** 实验数据库记录,revision 保护后台并发编辑。 */
|
||||
export type Experiment = {
|
||||
id: string;
|
||||
@@ -58,7 +58,10 @@ export async function experiments() {
|
||||
await rows<Experiment>(
|
||||
"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) }));
|
||||
).map((e) => ({
|
||||
...e,
|
||||
config: decodeExperimentConfig(json(e.config), e.consumerKey),
|
||||
}));
|
||||
}
|
||||
/** 创建时间从受信账号表获取,所有查询中的表名均来自固定枚举。 */
|
||||
export async function accountCreated(account: string) {
|
||||
@@ -130,7 +133,7 @@ export async function transition(
|
||||
id: string,
|
||||
state: Experiment["state"],
|
||||
revision: number,
|
||||
winner?: "A" | "B",
|
||||
winner?: string,
|
||||
) {
|
||||
await transaction(async (c) => {
|
||||
// 锁住已有固定行,不使用进程内互斥保证部署重启期间的一致性。
|
||||
@@ -154,12 +157,14 @@ export async function transition(
|
||||
};
|
||||
if (!allowed[e.state].includes(state)) throw conflict("不允许的状态流转");
|
||||
if (state === "finished" && !winner)
|
||||
throw badRequest("结束实验时必须选择长期生效的方案");
|
||||
throw badRequest("结束实验时必须选择最终保留的组");
|
||||
const config: Config = {
|
||||
...json<Config>(e.config),
|
||||
...decodeExperimentConfig(json(e.config)),
|
||||
...(winner ? { winner } : {}),
|
||||
};
|
||||
const registered = await scene(e.scope, c);
|
||||
if (winner && !hasExperimentGroup(config, winner))
|
||||
throw badRequest("所选最终组不属于该测试方案");
|
||||
if (state === "running") {
|
||||
if (!registered.enabled) throw badRequest("类型已停用,不能启动方案");
|
||||
if (registered.integrationState !== "confirmed")
|
||||
@@ -178,29 +183,29 @@ export async function transition(
|
||||
);
|
||||
if (others.length)
|
||||
throw conflict("该类型的消费标识已有未结束方案,请先结束现有方案");
|
||||
normalizePlanValues(registered, config);
|
||||
const cfg = config;
|
||||
if (registered.consumerKey === "chat" && !cfg.presetSnapshots) {
|
||||
if (!cfg.presetA || !cfg.presetB)
|
||||
throw badRequest("对话实验须分别选择两个已发布预设");
|
||||
if (
|
||||
registered.contract.optionsSource === "presets" &&
|
||||
!cfg.presetSnapshots
|
||||
) {
|
||||
const ids = [...new Set(cfg.groups.map((g) => String(g.value)))];
|
||||
const available = await rows<{ id: string; body: unknown }>(
|
||||
"SELECT id,body FROM dh_content WHERE id IN (?,?) AND kind='preset' AND status='published'",
|
||||
[cfg.presetA, cfg.presetB],
|
||||
`SELECT id,body FROM dh_content WHERE id IN (${ids.map(() => "?").join(",")}) AND kind='preset' AND status='published'`,
|
||||
ids,
|
||||
c,
|
||||
);
|
||||
if (
|
||||
new Set(available.map((v) => v.id)).size !==
|
||||
new Set([cfg.presetA, cfg.presetB]).size
|
||||
)
|
||||
throw badRequest("预设未发布");
|
||||
// 冻结预设正文,运营后续编辑原预设不会改变已启动实验的处理。
|
||||
cfg.presetSnapshots = {
|
||||
A: contentSchema.shape.body.parse(
|
||||
json(available.find((v) => v.id === cfg.presetA)!.body),
|
||||
),
|
||||
B: contentSchema.shape.body.parse(
|
||||
json(available.find((v) => v.id === cfg.presetB)!.body),
|
||||
),
|
||||
};
|
||||
if (available.length !== ids.length)
|
||||
throw badRequest("每个组都须选择已发布预设");
|
||||
// 按组冻结正文,后续内容编辑不改变正在运行的实验。
|
||||
cfg.presetSnapshots = Object.fromEntries(
|
||||
cfg.groups.map((g) => [
|
||||
g.key,
|
||||
contentSchema.shape.body.parse(
|
||||
json(available.find((v) => v.id === g.value)!.body),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
await write(
|
||||
@@ -225,43 +230,47 @@ export async function resolveExperiment(
|
||||
) {
|
||||
const cfg = e.config;
|
||||
const createdAt = await accountCreated(account);
|
||||
let variant: "A" | "B" = cfg.baseline;
|
||||
let reason = "baseline";
|
||||
let variant: string | null = null;
|
||||
let reason = "default";
|
||||
if (e.state === "finished") {
|
||||
variant = cfg.winner ?? cfg.baseline;
|
||||
variant = cfg.winner ?? null;
|
||||
reason = "finished";
|
||||
} else if (e.state === "running") {
|
||||
const [override] = await rows<{
|
||||
variant: "A" | "B";
|
||||
variant: string;
|
||||
bypass_audience: number;
|
||||
}>(
|
||||
"SELECT variant,bypass_audience FROM dh_overrides WHERE experiment_id=? AND account=? AND expires_at>NOW(3)",
|
||||
[e.id, account],
|
||||
);
|
||||
const inAudience = eligible(cfg, account, createdAt);
|
||||
if (override && (inAudience || override.bypass_audience)) {
|
||||
if (
|
||||
override &&
|
||||
hasExperimentGroup(cfg, override.variant) &&
|
||||
(inAudience || override.bypass_audience)
|
||||
) {
|
||||
variant = override.variant;
|
||||
reason = "override";
|
||||
} else if (!inAudience) reason = "outside_audience";
|
||||
else {
|
||||
const [sticky] = await rows<{ variant: "A" | "B"; reason: string }>(
|
||||
const [sticky] = await rows<{ variant: string; reason: string }>(
|
||||
"SELECT variant,reason FROM dh_assignments WHERE experiment_id=? AND account=?",
|
||||
[e.id, account],
|
||||
);
|
||||
if (sticky) {
|
||||
if (sticky && hasExperimentGroup(cfg, sticky.variant)) {
|
||||
variant = sticky.variant;
|
||||
reason = "sticky";
|
||||
} else if (bucket(e.id, account, "traffic") >= cfg.traffic)
|
||||
reason = "outside_traffic";
|
||||
else {
|
||||
variant = bucket(e.id, account, "variant") < cfg.weightB ? "B" : "A";
|
||||
variant = groupAtBucket(cfg.groups, bucket(e.id, account, "variant"));
|
||||
reason = "allocated";
|
||||
if (!preview) {
|
||||
await write(
|
||||
"INSERT IGNORE INTO dh_assignments(experiment_id,account,variant,reason) VALUES (?,?,?,?)",
|
||||
[e.id, account, variant, reason],
|
||||
);
|
||||
const [saved] = await rows<{ variant: "A" | "B" }>(
|
||||
const [saved] = await rows<{ variant: string }>(
|
||||
"SELECT variant FROM dh_assignments WHERE experiment_id=? AND account=?",
|
||||
[e.id, account],
|
||||
);
|
||||
@@ -270,6 +279,7 @@ export async function resolveExperiment(
|
||||
}
|
||||
}
|
||||
} else reason = e.state;
|
||||
const group = variant ? cfg.groups.find((g) => g.key === variant) : undefined;
|
||||
return {
|
||||
experimentId: e.id,
|
||||
scope: e.scope,
|
||||
@@ -277,8 +287,8 @@ export async function resolveExperiment(
|
||||
reason,
|
||||
revision: e.revision,
|
||||
createdAt,
|
||||
presetId: variant === "A" ? cfg.presetA : cfg.presetB,
|
||||
presetSnapshot: cfg.presetSnapshots?.[variant],
|
||||
presetId: typeof group?.value === "string" ? group.value : undefined,
|
||||
presetSnapshot: variant ? cfg.presetSnapshots?.[variant] : undefined,
|
||||
};
|
||||
}
|
||||
/** 从已按创建时间排序的场景实验中选择当前接入点的有效配置。 */
|
||||
@@ -294,33 +304,32 @@ export function activeExperiment(list: Experiment[], runtime: string) {
|
||||
candidates[0]
|
||||
);
|
||||
}
|
||||
/** 历史方案没有typed values时保留原UI/预设含义,不重算账号分组。 */
|
||||
/** 未入组、暂停或草稿使用类型默认值,不能冒充某个实验组。 */
|
||||
export function planValue(
|
||||
e: Experiment,
|
||||
variant: "A" | "B",
|
||||
variant: string | null,
|
||||
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;
|
||||
if (!variant) return fallback;
|
||||
const group = e.config.groups.find((g) => g.key === variant);
|
||||
return group ? group.value : fallback;
|
||||
}
|
||||
/** 未配置方案或类型时返回默认行为,不创建类型、分组或接入记录。 */
|
||||
function defaultDecision(typeKey: string, typeRevision: number, value: unknown) {
|
||||
function defaultDecision(
|
||||
typeKey: string,
|
||||
typeRevision: number,
|
||||
value: unknown,
|
||||
) {
|
||||
return {
|
||||
variant: "A" as const,
|
||||
variant: null,
|
||||
reason: "default",
|
||||
fallbackVariant: "A" as const,
|
||||
fallbackVariant: null,
|
||||
decisionId: null,
|
||||
experimentId: null,
|
||||
presetId: undefined,
|
||||
presetSnapshot: undefined,
|
||||
value,
|
||||
fallbackValue: value,
|
||||
typeKey,
|
||||
typeRevision,
|
||||
expiresAt: Date.now() + 60000,
|
||||
@@ -359,10 +368,11 @@ export async function decide(
|
||||
typeKey: type.id,
|
||||
typeRevision: type.contractRevision,
|
||||
decisionId,
|
||||
fallbackVariant:
|
||||
fallbackVariant: e.state === "finished" ? (e.config.winner ?? null) : null,
|
||||
fallbackValue:
|
||||
e.state === "finished"
|
||||
? (e.config.winner ?? e.config.baseline)
|
||||
: e.config.baseline,
|
||||
? planValue(e, e.config.winner ?? null, type.defaultValue)
|
||||
: type.defaultValue,
|
||||
expiresAt: Date.now() + 60000,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -52,6 +52,25 @@ export const contentSchema = z.object({
|
||||
});
|
||||
/** 内容记录只保存经过 schema 解析的数据。 */
|
||||
export type ContentInput = z.infer<typeof contentSchema>;
|
||||
/** 组标识仅限单个大写字母;允许0%保留用于人工验收。 */
|
||||
export const groupKeySchema = z.string().regex(/^[A-Z]$/, "组别须为 A 到 Z");
|
||||
/** 比例按万分比整数保存,避免小数累计误差。 */
|
||||
export const experimentGroupsSchema = z
|
||||
.array(
|
||||
z.object({
|
||||
key: groupKeySchema,
|
||||
weight: z.number().int().min(0).max(10000),
|
||||
value: z.json(),
|
||||
}),
|
||||
)
|
||||
.min(1)
|
||||
.max(26)
|
||||
.superRefine((groups, ctx) => {
|
||||
if (new Set(groups.map((g) => g.key)).size !== groups.length)
|
||||
ctx.addIssue({ code: "custom", message: "组别不能重复" });
|
||||
if (groups.reduce((sum, g) => sum + g.weight, 0) !== 10000)
|
||||
ctx.addIssue({ code: "custom", message: "分组比例合计必须为100%" });
|
||||
});
|
||||
/** 实验配置仅通过后台写入,分组语义在同一实验生命周期中固定。 */
|
||||
export const experimentSchema = z.object({
|
||||
name: z.string().min(1).max(120),
|
||||
@@ -64,13 +83,9 @@ export const experimentSchema = z.object({
|
||||
.max(500)
|
||||
.default([]),
|
||||
traffic: z.number().int().min(0).max(10000).default(10000),
|
||||
weightB: z.number().int().min(0).max(10000).default(5000),
|
||||
baseline: z.enum(["A", "B"]).default("A"),
|
||||
winner: z.enum(["A", "B"]).optional(),
|
||||
presetA: idSchema.optional(),
|
||||
presetB: idSchema.optional(),
|
||||
groups: experimentGroupsSchema,
|
||||
winner: groupKeySchema.optional(),
|
||||
description: z.string().max(2000).default(""),
|
||||
values: z.object({ A: z.json(), B: z.json() }).optional(),
|
||||
typeRevision: z.number().int().positive().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
+307
-37
@@ -34,7 +34,13 @@ import {
|
||||
const config = experimentSchema.parse({
|
||||
name: "test",
|
||||
scope: "ui",
|
||||
config: { audience: "all" },
|
||||
config: {
|
||||
audience: "all",
|
||||
groups: [
|
||||
{ key: "A", weight: 5000, value: false },
|
||||
{ key: "B", weight: 5000, value: true },
|
||||
],
|
||||
},
|
||||
}).config;
|
||||
test("新老用户在注册分界精确互补,指定名单不能混入其他账号", () => {
|
||||
const cutoff = "2026-10-26T00:00:00.000Z";
|
||||
@@ -418,36 +424,37 @@ test("类型数据契约保留 false、0、null,拒绝错误格式和非 JSON
|
||||
] as const)
|
||||
assert.throws(() => validateTypeValue(kind, value));
|
||||
});
|
||||
test("自定义 A/B 值按注册契约验证,旧 UI 值和预设合同保持兼容", () => {
|
||||
const t = { valueType: "boolean", contract: {} } as ExperimentType;
|
||||
assert.deepEqual(
|
||||
normalizePlanValues(t, { values: { A: false, B: true } }).values,
|
||||
{ A: false, B: true },
|
||||
);
|
||||
assert.throws(() => normalizePlanValues(t, {}));
|
||||
test("动态分组独立验证返回值,0%组仍需合法,保留false、0、null", () => {
|
||||
const type = { valueType: "boolean", contract: {} } as ExperimentType;
|
||||
const groups = [
|
||||
{ key: "A", weight: 10000, value: false },
|
||||
{ key: "B", weight: 0, value: true },
|
||||
];
|
||||
assert.deepEqual(normalizePlanValues(type, { groups }).groups, groups);
|
||||
assert.throws(() =>
|
||||
normalizePlanValues(t, { values: { A: "false", B: true } }),
|
||||
normalizePlanValues(type, {
|
||||
groups: [{ ...groups[0], value: "false" }, groups[1]],
|
||||
}),
|
||||
);
|
||||
const ui = {
|
||||
...t,
|
||||
valueType: "string",
|
||||
contract: { fixedValues: { A: "old", B: "new" } },
|
||||
} as ExperimentType;
|
||||
assert.deepEqual(
|
||||
normalizePlanValues(ui, { values: { A: "malicious", B: "other" } }).values,
|
||||
{ A: "old", B: "new" },
|
||||
);
|
||||
const chat = { ...ui, contract: { optionsSource: "presets" } };
|
||||
assert.equal(
|
||||
normalizePlanValues(chat, { presetA: "one", presetB: "two" }).presetA,
|
||||
"one",
|
||||
assert.throws(() =>
|
||||
normalizePlanValues(type, {
|
||||
groups: [groups[0], { ...groups[1], value: 1 }],
|
||||
}),
|
||||
);
|
||||
const plan = {
|
||||
config: { values: { A: false, B: 0 } },
|
||||
consumerKey: "custom",
|
||||
} as unknown as Experiment;
|
||||
config: {
|
||||
groups: [
|
||||
{ key: "A", weight: 5000, value: false },
|
||||
{ key: "C", weight: 5000, value: 0 },
|
||||
{ key: "Z", weight: 0, value: null },
|
||||
],
|
||||
},
|
||||
} as Experiment;
|
||||
assert.equal(planValue(plan, "A", "fallback"), false);
|
||||
assert.equal(planValue(plan, "B", "fallback"), 0);
|
||||
assert.equal(planValue(plan, "C", "fallback"), 0);
|
||||
assert.equal(planValue(plan, "Z", "fallback"), null);
|
||||
assert.equal(planValue(plan, null, "fallback"), "fallback");
|
||||
assert.equal(planValue(plan, "B", "fallback"), "fallback");
|
||||
});
|
||||
test("独立新类型不会共享分流;历史同消费者别名仍互斥选择", () => {
|
||||
const e = (id: string, consumerKey: string, state: Experiment["state"]) =>
|
||||
@@ -499,10 +506,11 @@ test("新增预设的数据库迁移与初始化种子保持同一数据契约",
|
||||
assert.ok(/INSERT IGNORE/.test(sql));
|
||||
});
|
||||
|
||||
|
||||
test("空白实验注册表保持为空,应用默认决策不创建类型或伪造接入", async (t) => {
|
||||
const { pool } = await import("../src/db/pool");
|
||||
const { experimentTypes } = await import("../src/modules/digital/digital.experiment-types");
|
||||
const { experimentTypes } = await import(
|
||||
"../src/modules/digital/digital.experiment-types"
|
||||
);
|
||||
const queries: string[] = [];
|
||||
t.mock.method(pool, "query", async (options: { sql: string }) => {
|
||||
queries.push(options.sql);
|
||||
@@ -510,7 +518,11 @@ test("空白实验注册表保持为空,应用默认决策不创建类型或
|
||||
return [[], []];
|
||||
});
|
||||
assert.deepEqual(await experimentTypes(), []);
|
||||
for (const [key, value] of [["ui", "old"], ["chat", ""], ["custom", false]] as const) {
|
||||
for (const [key, value] of [
|
||||
["ui", "old"],
|
||||
["chat", ""],
|
||||
["custom", false],
|
||||
] as const) {
|
||||
const d = await decide("employee:1", key, { value });
|
||||
assert.equal(d.value, value);
|
||||
assert.equal(d.typeRevision, 0);
|
||||
@@ -519,23 +531,36 @@ test("空白实验注册表保持为空,应用默认决策不创建类型或
|
||||
assert.equal(d.experimentId, null);
|
||||
assert.equal(d.presetId, undefined);
|
||||
}
|
||||
await assert.rejects(decide("employee:1", "missing"), (e: unknown) =>
|
||||
!!e && typeof e === "object" && "statusCode" in e && e.statusCode === 404);
|
||||
await assert.rejects(
|
||||
decide("employee:1", "missing"),
|
||||
(e: unknown) =>
|
||||
!!e && typeof e === "object" && "statusCode" in e && e.statusCode === 404,
|
||||
);
|
||||
assert.equal(queries.length, 5);
|
||||
});
|
||||
|
||||
test("应用未配置实验的默认行为不能吞掉数据库故障", async (t) => {
|
||||
const { pool } = await import("../src/db/pool");
|
||||
t.mock.method(pool, "query", async () => { throw new Error("database unavailable"); });
|
||||
await assert.rejects(decide("employee:1", "ui", { value: "old" }), /database unavailable/);
|
||||
t.mock.method(pool, "query", async () => {
|
||||
throw new Error("database unavailable");
|
||||
});
|
||||
await assert.rejects(
|
||||
decide("employee:1", "ui", { value: "old" }),
|
||||
/database unavailable/,
|
||||
);
|
||||
});
|
||||
|
||||
test("空白实验系统仍能启动前台,且不为默认界面写入实验记录", async (t) => {
|
||||
const { pool } = await import("../src/db/pool");
|
||||
const { authService } = await import("../src/modules/auth/auth.service");
|
||||
t.mock.method(authService, "getCurrentUser", async () => ({ accountType: "EMPLOYEE" }));
|
||||
t.mock.method(authService, "getCurrentUser", async () => ({
|
||||
accountType: "EMPLOYEE",
|
||||
}));
|
||||
t.mock.method(pool, "query", async (options: { sql: string }) => {
|
||||
assert.match(options.sql, /^SELECT .* FROM (dh_scenes|dh_content|dh_profiles) /);
|
||||
assert.match(
|
||||
options.sql,
|
||||
/^SELECT .* FROM (dh_scenes|dh_content|dh_profiles) /,
|
||||
);
|
||||
return [[], []];
|
||||
});
|
||||
const app = createApp();
|
||||
@@ -543,16 +568,261 @@ test("空白实验系统仍能启动前台,且不为默认界面写入实验
|
||||
await app.ready();
|
||||
const token = app.jwt.sign({ sub: "employee:1", accountType: "EMPLOYEE" });
|
||||
const result = await app.inject({
|
||||
method: "GET", url: "/api/digital/bootstrap",
|
||||
method: "GET",
|
||||
url: "/api/digital/bootstrap",
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
});
|
||||
assert.equal(result.statusCode, 200);
|
||||
const data = result.json().data;
|
||||
assert.deepEqual(data.catalog, []);
|
||||
assert.equal(data.decision.variant, "A");
|
||||
assert.equal(data.decision.variant, null);
|
||||
assert.equal(data.decision.experimentId, null);
|
||||
assert.equal(data.decision.decisionId, null);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("A至Z动态组校验数量、唯一性、百分比总和与两位小数精度", async () => {
|
||||
const { experimentGroupsSchema } = await import(
|
||||
"../src/modules/digital/digital.schema"
|
||||
);
|
||||
const good = [
|
||||
{ key: "A", weight: 2000, value: false },
|
||||
{ key: "C", weight: 3000, value: true },
|
||||
{ key: "Z", weight: 5000, value: "new" },
|
||||
];
|
||||
assert.equal(experimentGroupsSchema.safeParse(good).success, true);
|
||||
assert.equal(
|
||||
experimentGroupsSchema.safeParse(
|
||||
Array.from({ length: 26 }, (_, i) => ({
|
||||
key: String.fromCharCode(65 + i),
|
||||
weight: i === 0 ? 10000 : 0,
|
||||
value: i,
|
||||
})),
|
||||
).success,
|
||||
true,
|
||||
);
|
||||
for (const bad of [
|
||||
[],
|
||||
[...good, good[0]],
|
||||
[{ key: "a", weight: 10000, value: 0 }],
|
||||
[{ key: "AA", weight: 10000, value: 0 }],
|
||||
[{ key: "A", weight: 9999, value: 0 }],
|
||||
[{ key: "A", weight: 10001, value: 0 }],
|
||||
[{ key: "A", weight: 9999.5, value: 0 }],
|
||||
])
|
||||
assert.equal(experimentGroupsSchema.safeParse(bad).success, false);
|
||||
});
|
||||
|
||||
test("多组哈希区间全覆盖,零比例永远不分配,A100%时B0%", async () => {
|
||||
const { groupAtBucket } = await import(
|
||||
"../src/modules/digital/digital.experiment-groups"
|
||||
);
|
||||
const groups = [
|
||||
{ key: "A", weight: 2000, value: "a" },
|
||||
{ key: "B", weight: 0, value: "b" },
|
||||
{ key: "C", weight: 3000, value: "c" },
|
||||
{ key: "Z", weight: 5000, value: "z" },
|
||||
];
|
||||
const counts: Record<string, number> = {};
|
||||
for (let p = 0; p < 10000; p++) {
|
||||
const g = groupAtBucket(groups, p);
|
||||
counts[g] = (counts[g] ?? 0) + 1;
|
||||
assert.equal(
|
||||
groupAtBucket(
|
||||
[
|
||||
{ key: "A", weight: 10000, value: false },
|
||||
{ key: "B", weight: 0, value: true },
|
||||
],
|
||||
p,
|
||||
),
|
||||
"A",
|
||||
);
|
||||
}
|
||||
assert.deepEqual(counts, { A: 2000, C: 3000, Z: 5000 });
|
||||
assert.equal(groupAtBucket(groups, 2000), "C");
|
||||
assert.equal(groupAtBucket(groups, 5000), "Z");
|
||||
});
|
||||
|
||||
test("历史双组配置保留原哈希区间,自定义多组配置不会丢组或改值", async () => {
|
||||
const { decodeExperimentConfig, groupAtBucket } = await import(
|
||||
"../src/modules/digital/digital.experiment-groups"
|
||||
);
|
||||
const legacy = {
|
||||
weightB: 2500,
|
||||
baseline: "A",
|
||||
values: { A: "old", B: "new" },
|
||||
};
|
||||
const converted = decodeExperimentConfig(legacy);
|
||||
assert.equal("baseline" in converted, false);
|
||||
assert.equal("weightB" in converted, false);
|
||||
for (let p = 0; p < 10000; p++)
|
||||
assert.equal(groupAtBucket(converted.groups, p), p < 2500 ? "B" : "A");
|
||||
assert.equal(converted.groups.find((g) => g.key === "B")?.value, "new");
|
||||
assert.deepEqual(decodeExperimentConfig(converted), converted);
|
||||
});
|
||||
|
||||
test("未入组和暂停没有组别,人工指定可到零比例组,结束可保留C组", async (t) => {
|
||||
const { pool } = await import("../src/db/pool");
|
||||
const { resolveExperiment } = await import(
|
||||
"../src/modules/digital/digital.experiments"
|
||||
);
|
||||
let override: unknown[] = [];
|
||||
t.mock.method(pool, "query", async (q: { sql: string }) => {
|
||||
if (q.sql.includes("created_at FROM"))
|
||||
return [[{ created_at: new Date("2026-01-01T00:00:00Z") }], []];
|
||||
if (q.sql.includes("FROM dh_overrides")) return [override, []];
|
||||
if (q.sql.includes("FROM dh_assignments")) return [[], []];
|
||||
throw new Error("预览不得写入:" + q.sql);
|
||||
});
|
||||
const e = {
|
||||
id: "multi",
|
||||
state: "running",
|
||||
config: {
|
||||
...config,
|
||||
groups: [
|
||||
{ key: "A", weight: 10000, value: false },
|
||||
{ key: "C", weight: 0, value: true },
|
||||
],
|
||||
traffic: 0,
|
||||
},
|
||||
} as Experiment;
|
||||
const outside = await resolveExperiment(e, "employee:1", true);
|
||||
assert.equal(outside.variant, null);
|
||||
assert.equal(outside.reason, "outside_traffic");
|
||||
assert.equal(planValue(e, outside.variant, "default"), "default");
|
||||
override = [{ variant: "C", bypass_audience: false }];
|
||||
assert.equal((await resolveExperiment(e, "employee:1", true)).variant, "C");
|
||||
const paused = await resolveExperiment(
|
||||
{ ...e, state: "paused" },
|
||||
"employee:1",
|
||||
true,
|
||||
);
|
||||
assert.equal(paused.variant, null);
|
||||
assert.equal(paused.reason, "paused");
|
||||
assert.equal(
|
||||
(
|
||||
await resolveExperiment(
|
||||
{ ...e, state: "finished", config: { ...e.config, winner: "C" } },
|
||||
"employee:1",
|
||||
true,
|
||||
)
|
||||
).variant,
|
||||
"C",
|
||||
);
|
||||
override = [{ variant: "Z", bypass_audience: true }];
|
||||
assert.equal((await resolveExperiment(e, "employee:1", true)).variant, null);
|
||||
});
|
||||
|
||||
test("自动分流可持久化C组,后续读取保持同一组且不重复写入", async (t) => {
|
||||
const { pool } = await import("../src/db/pool");
|
||||
const { resolveExperiment } = await import(
|
||||
"../src/modules/digital/digital.experiments"
|
||||
);
|
||||
let saved: string | null = null,
|
||||
writes = 0;
|
||||
t.mock.method(pool, "query", async (q: { sql: string }, args: unknown[]) => {
|
||||
if (q.sql.includes("created_at FROM"))
|
||||
return [[{ created_at: new Date("2026-01-01T00:00:00Z") }], []];
|
||||
if (q.sql.includes("FROM dh_overrides")) return [[], []];
|
||||
if (q.sql.includes("INSERT IGNORE INTO dh_assignments")) {
|
||||
saved = String(args[2]);
|
||||
writes++;
|
||||
return [{ affectedRows: 1 }, []];
|
||||
}
|
||||
if (q.sql.includes("FROM dh_assignments"))
|
||||
return [saved ? [{ variant: saved, reason: "allocated" }] : [], []];
|
||||
throw new Error("意外查询:" + q.sql);
|
||||
});
|
||||
const e = {
|
||||
id: "multi-persist",
|
||||
state: "running",
|
||||
config: {
|
||||
...config,
|
||||
groups: [
|
||||
{ key: "A", weight: 0, value: false },
|
||||
{ key: "C", weight: 10000, value: true },
|
||||
],
|
||||
},
|
||||
} as Experiment;
|
||||
const first = await resolveExperiment(e, "employee:1");
|
||||
assert.equal(first.variant, "C");
|
||||
assert.equal(first.reason, "allocated");
|
||||
const second = await resolveExperiment(e, "employee:1");
|
||||
assert.equal(second.variant, "C");
|
||||
assert.equal(second.reason, "sticky");
|
||||
assert.equal(writes, 1);
|
||||
});
|
||||
|
||||
test("结束实验拒绝不存在的组,允许保留零比例C组", async (t) => {
|
||||
const { pool } = await import("../src/db/pool");
|
||||
const { transition } = await import(
|
||||
"../src/modules/digital/digital.experiments"
|
||||
);
|
||||
let rollback = 0,
|
||||
commit = 0,
|
||||
updated: unknown[] | undefined;
|
||||
const cfg = {
|
||||
...config,
|
||||
groups: [
|
||||
{ key: "A", weight: 10000, value: false },
|
||||
{ key: "C", weight: 0, value: true },
|
||||
],
|
||||
};
|
||||
t.mock.method(pool, "getConnection", async () => ({
|
||||
beginTransaction: async () => {},
|
||||
commit: async () => {
|
||||
commit++;
|
||||
},
|
||||
rollback: async () => {
|
||||
rollback++;
|
||||
},
|
||||
release: () => {},
|
||||
query: async (q: { sql: string }, args: unknown[]) => {
|
||||
if (q.sql.includes("schema_migrations"))
|
||||
return [[{ version: "001" }], []];
|
||||
if (q.sql.includes("FROM dh_experiments WHERE id"))
|
||||
return [
|
||||
[
|
||||
{
|
||||
id: "test",
|
||||
scope: "custom",
|
||||
state: "running",
|
||||
revision: 1,
|
||||
config: cfg,
|
||||
},
|
||||
],
|
||||
[],
|
||||
];
|
||||
if (q.sql.includes("FROM dh_scenes"))
|
||||
return [
|
||||
[
|
||||
{
|
||||
id: "custom",
|
||||
valueType: "boolean",
|
||||
defaultValue: false,
|
||||
contract: {},
|
||||
},
|
||||
],
|
||||
[],
|
||||
];
|
||||
if (q.sql.startsWith("UPDATE dh_experiments")) {
|
||||
updated = args;
|
||||
return [{ affectedRows: 1 }, []];
|
||||
}
|
||||
if (q.sql.startsWith("INSERT INTO dh_audits"))
|
||||
return [{ affectedRows: 1 }, []];
|
||||
throw new Error("意外查询:" + q.sql);
|
||||
},
|
||||
}));
|
||||
await assert.rejects(
|
||||
transition("super_admin:1", "test", "finished", 1, "Z"),
|
||||
/不属于/,
|
||||
);
|
||||
assert.equal(rollback, 1);
|
||||
assert.equal(updated, undefined);
|
||||
await transition("super_admin:1", "test", "finished", 1, "C");
|
||||
assert.equal(commit, 1);
|
||||
assert.equal(JSON.parse(String(updated?.[1])).winner, "C");
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user