feat(experiments): 支持动态多组分流并移除默认组

- 分组支持 A 至 Z,按整数比例验证合计100%,支持0%组人工验收
- 未入组使用类型默认值,分组持久化、指定与最终结果按实际组校验
- 保留历史双组哈希区间,新增多组与生命周期回归并同步文档
This commit is contained in:
湛兮
2026-10-27 15:15:21 +08:00
parent 9350aa9632
commit 78109942d2
8 changed files with 504 additions and 132 deletions
@@ -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);
}