feat(experiments): 支持动态多组分流并移除默认组
- 分组支持 A 至 Z,按整数比例验证合计100%,支持0%组人工验收 - 未入组使用类型默认值,分组持久化、指定与最终结果按实际组校验 - 保留历史双组哈希区间,新增多组与生命周期回归并同步文档
This commit is contained in:
@@ -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(),
|
||||
}),
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user