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