Files
streamline/scripts/poll_waste_report.ts
T
2026-11-16 17:26:44 -08:00

382 lines
21 KiB
TypeScript

/**
* 轮询浪费度量 —— `wait-for` 上线前后的同口径回测工具。
*
* bun scripts/poll_waste_report.ts --since 2026-07-16 --until 2026-09-14 [--limit 50]
* bun scripts/poll_waste_report.ts --since 2026-09-15 --json > after.json
*
* ## 为什么要有这个文件,而不是「到时候再查一遍」
*
* 2026-09-14 的 50 任务抽样得出四个数(见下方 BASELINE),`wait-for` 和放宽后的
* Bash 超时就是冲着这四个数去的。如果上线之后的复查是临时手搓的,口径一定会飘:
* 换一批样本、换一种归类、把评估轮算进去或不算进去,每一样都能凭空造出或抹掉
* 一成的"改善"。那样的对比说明不了任何事情,还会被当成结论。
*
* 所以度量本身必须是**同一段代码**跑两次。基线数字钉死在这个文件里,跟它们一起
* 钉死的是产生它们的那套过滤和分类规则。上线后重跑,差值才有意义。
*
* ## 口径(改动它就等于作废基线,要改请连 BASELINE 一起重算)
*
* - 样本:`finishedAt` 落在窗口内、已结束的 bug 与 feature,**剔除 `evaluate-` 前缀**
* (那是 evaluator 基准 lane,跑在专用节点上,节奏不代表生产)。
* - 只统计**执行轮**(session-r*.log),不含评估轮 —— 评估轮不碰设备也不构建,
* 本来就没有轮询,混进来只会稀释分母。
* - `--rounds-since` 只保留**在该时刻之后开跑**的轮次。样本按任务的 finishedAt 选,
* 但一个今天结束的任务,它前几批可能跑在几天前 —— 上线当天做回测时,这批旧轮次
* 会占到多数。实测 2026-09-15 首次回测:窗口内 54 个执行轮里 **35 轮跑在换装之前**,
* 不筛掉的话对比的是新旧混合体,而混合比例每天都在变,数字看着动其实什么也没说明。
* 轮次的开跑时刻按 `archivedAt - durationMs` 反推(与 runner 日志实测相差 9 秒)。
* - 「重复调用」= 同一任务内 **字节完全相同** 的 Bash 命令的多余次数。
* 不做归一化(不抹路径、不抹数字):归一化会把"每次改了轮次号的轮询"也算进来,
* 那是另一回事,分开看更诚实。
* - 「显式 sleep」只累加 **≤600s** 的字面量。更大的是守护/占位写法
* (`nohup … sleep 100000`),算进来会凭空多出上百小时。
*
* ## 想做归因,必须提前留对照组(2026-09-17 的教训)
*
* 这个脚本只能回答「改动之后这些数字是多少」,回答不了「是不是这次改动造成的」。
*
* 上线三天后想查单轮时长为什么涨了 47%,我以为其它节点池还跑着旧 bundle、可以当
* 对照 —— 查下来它们那几天已经升到同一版了(那组里有 229 次 wait-for 调用,就是
* 证据)。**根本没有对照组**,于是「变慢」既不能归因、也不能排除,而节点间的中位数
* 从 48min 到 135min,方差远大于要找的效应。
*
* 下面的 `--by-experiment` 就是为此做的。
*
* 做法**不是**把某台节点扣着不升级 —— 那台机器会同时错过其它所有改动,而且对照组
* 撑得越久,它和生产的差别就越不只是被测的那一项。改用按节点关单项:在对照节点的
* `.env` 里写 `STREAMLINE_EXPERIMENTS=waitfor=off`,它照常收所有新 bundle,只是这一项
* 退回改动前的行为。节点把被关掉的项随心跳上报,`/api/nodes` 的 `experiments` 能读到,
* 于是回测能按行为分组。
*
* 注意 `experiments` 只反映**当下**,不是历史 —— 开关一旦设好就别中途改,否则更早的
* 轮次无从回溯,又会回到 2026-09-17 那个说不清归因的局面。
*
* ## 先问「这个差值分得开吗」,再问「变好了没有」—— `--noise`
*
* 2026-09-17 量到单轮时长涨了 47%,差点当成效应。补做 A/A 才发现噪声底有多高:
*
* - 同平台、跑同一版代码的不同节点,中位数跨度 iOS 31% / Android 45%;
* - **同一台节点**、同一版代码,把轮次按时间对半切,自己跟自己比,差 −30% ~ +30%
* (每半 ~90 轮)。也就是说「前后对比」这种做法本身就带着 ±30% 的时间漂移。
*
* 自举出的可判别下限(同一总体抽两组,两组中位数之差的 p90):
*
* 每组 20 轮 → 46% 每组 100 轮 → 21% 每组 400 轮 → 11%
* 每组 50 轮 → 29% 每组 200 轮 → 15% 每组 800 轮 → 8%
*
* 换装后只有 66 轮、观测 +47% —— 刚出头,判不了。
*
* 结论不是「再等等」,而是**别拿单轮时长当这次改动的成败判据**:全量每天只产出
* ~20 轮,要把下限压到 15% 得攒 200 轮/组。真正该看的是那些近乎确定性的计数 ——
* 重复调用占比(14.3% → 0.6%,二十倍的变化,远在任何噪声之上)、wait-for 超时次数与
* 烧掉的时长、无哨兵轮占比。它们是改动的直接后果,不是墙钟的随机游走。
*
* `--noise` 把上面那张表按当前窗口重算一遍,回答「我这次看到的差值分得开吗」。
*
* ## 只读
*
* 全程 GET 内网只读 API,不连 DB,不写任何东西。会话日志只流式读取、就地统计,
* 不落盘 —— 单次全量约 600 MB。
*/
import { parseArgs } from "node:util";
const API = process.env.STREAMLINE_API ?? "https://streamline-internal-api.bytedance.net";
/**
* 2026-09-14 抽样得到的基线(窗口 2026-07-16 ~ 2026-09-14,50 任务 / 86 个执行轮
* 会话日志 / 12,487 次 Bash 调用)。上线后的复查跟它比。
*/
export const BASELINE = {
window: "2026-07-16 ~ 2026-09-14",
tasks: 50,
execRoundsWithLog: 86,
bashCalls: 12_487,
dupCalls: 1_790, // 13.9% —— 首要目标
dupRatio: 0.143,
sleepSeconds: 82_440, // 22.9 h
sleepPerRoundSec: 958,
callsPerRound: 161,
roundsNoSentinel: 52, // 占全部 140 个有 digest 的轮次的 37%
roundsTotal: 140,
} as const;
interface Row { id: string; kind: "bug" | "feature"; finishedAt: number; status: string }
/** nodeId → 该节点当前关掉的改动(来自 /api/nodes 的 experiments)。 */
async function nodeExperiments(): Promise<Map<string, string>> {
const out = new Map<string, string>();
const j = await getJson<{ nodes: { id: string; experiments?: string[] }[] }>("/api/nodes");
for (const n of j?.nodes ?? []) {
out.set(n.id, n.experiments == null ? "(未上报)" : (n.experiments.length ? n.experiments.join(",") : "全开"));
}
return out;
}
async function getJson<T>(path: string): Promise<T | null> {
try {
const r = await fetch(API + path, { signal: AbortSignal.timeout(120_000) });
if (!r.ok) return null;
return (await r.json()) as T;
} catch { return null; }
}
async function listTargets(sinceMs: number, untilMs: number): Promise<Row[]> {
const out: Row[] = [];
const bugs = await getJson<{ tasks: any[] }>("/api/tasks");
for (const t of bugs?.tasks ?? []) {
if (String(t.id).startsWith("evaluate-")) continue;
if (t.finishedAt == null || t.finishedAt < sinceMs || t.finishedAt > untilMs) continue;
out.push({ id: t.id, kind: "bug", finishedAt: t.finishedAt, status: t.status });
}
const feats = await getJson<{ features: any[] }>("/api/features");
for (const f of feats?.features ?? []) {
if (f.finishedAt == null || f.finishedAt < sinceMs || f.finishedAt > untilMs) continue;
out.push({ id: f.id, kind: "feature", finishedAt: f.finishedAt, status: f.status });
}
return out.sort((a, b) => b.finishedAt - a.finishedAt);
}
interface TaskStat {
id: string; kind: string; rounds: number;
bash: number; dup: number; sleepSec: number;
waitForCalls: number; // 上线后应当从 0 涨起来 —— 没涨就是提示词没生效,不是工具没用
/** wait-for 等到上限就放弃的次数(退出码 124)。 */
waitForTimeouts: number;
/** 那些超时按各自 --timeout 累计烧掉的秒数 —— 纯等待,什么也没换来。 */
waitForTimeoutSec: number;
digestRounds: number; noSentinel: number;
/** 因为开跑于 --rounds-since 之前而被跳过的执行轮。 */
skippedOldRounds: number;
/** 跑这些轮次的节点(取计入的第一轮的 nodeId)。用于按实验开关分组。 */
node: string | null;
}
const SLEEP_RE = /\bsleep\s+(\d+(?:\.\d+)?)/g;
/** `45s` / `10m` / `2h` / 裸数字(按秒) → 秒。认不出返回 0。 */
function durSec(raw: string): number {
const m = /^(\d+(?:\.\d+)?)(ms|s|m|h)?$/i.exec(raw.trim());
if (!m) return 0;
const n = Number(m[1]), u = (m[2] ?? "s").toLowerCase();
return u === "ms" ? n / 1000 : u === "s" ? n : u === "m" ? n * 60 : n * 3600;
}
async function measure(t: Row, roundsSinceMs: number | null): Promise<TaskStat | null> {
const p = t.kind === "bug" ? "tasks" : "features";
const st: TaskStat = { id: t.id, kind: t.kind, rounds: 0, bash: 0, dup: 0, sleepSec: 0, waitForCalls: 0, waitForTimeouts: 0, waitForTimeoutSec: 0, digestRounds: 0, noSentinel: 0, skippedOldRounds: 0, node: null };
// 轮次开跑时刻:archivedAt(控制面归档这批的时刻)减去这批的自报时长。
const roundStart = new Map<number, number>();
const dig = await getJson<{ rounds: any[] }>(`/api/${p}/${t.id}/round-digests`);
for (const r of dig?.rounds ?? []) {
const start = r.archivedAt && r.digest?.durationMs ? r.archivedAt - r.digest.durationMs : r.archivedAt;
if (start) roundStart.set(r.round, start);
if (roundsSinceMs && start && start < roundsSinceMs) continue; // 换装前跑的,不计
st.node ??= r.nodeId ?? null;
st.digestRounds++;
if (!r.digest?.status) st.noSentinel++;
}
const logs = await getJson<{ files: { name: string; kind: string }[] }>(`/api/${p}/${t.id}/logs`);
const sessions = (logs?.files ?? []).filter((f) => f.kind === "session");
for (const f of sessions) {
if (roundsSinceMs) {
const n = Number(f.name.match(/-r(\d+)\.log$/)?.[1] ?? 0);
const start = roundStart.get(n);
// 拿不到开跑时刻的轮次一律跳过 —— 宁可少算,也不要把旧轮次混进来冒充新数据。
if (!start || start < roundsSinceMs) { st.skippedOldRounds++; continue; }
}
const res = await fetch(`${API}/api/${p}/${t.id}/logs/${f.name}?lines=400000`, { signal: AbortSignal.timeout(300_000) }).catch(() => null);
if (!res?.ok || !res.body) continue;
st.rounds++;
const seen = new Set<string>();
let lastWaitFor: string | null = null;
// 一行一个 stream-json 事件;整份日志可能几 MB,按行流式处理,不整份读进内存。
let buf = "";
for await (const chunk of res.body as any) {
buf += Buffer.from(chunk).toString("utf8");
let nl: number;
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl); buf = buf.slice(nl + 1);
if (!line.startsWith("{")) continue;
let ev: any; try { ev = JSON.parse(line); } catch { continue; }
if (ev.type === "user") {
// wait-for 的超时只能从它自己的输出里认:「⌛ … 等到上限 …」。
// 与紧邻的上一次 wait-for 调用配对,才拿得到它当时设的 --timeout。
for (const c of ev.message?.content ?? []) {
if (c.type !== "tool_result" || !lastWaitFor) continue;
const out = typeof c.content === "string" ? c.content : JSON.stringify(c.content ?? "");
if (/等到上限/.test(out)) {
st.waitForTimeouts++;
st.waitForTimeoutSec += durSec(lastWaitFor.match(/--timeout\s+(\S+)/)?.[1] ?? "");
lastWaitFor = null;
} else if (/命令已结束|条件达成/.test(out)) {
lastWaitFor = null;
}
}
continue;
}
if (ev.type !== "assistant") continue;
for (const c of ev.message?.content ?? []) {
if (c.type !== "tool_use" || c.name !== "Bash") continue;
const cmd = String(c.input?.command ?? "").replace(/\s+/g, " ").trim();
if (!cmd) continue;
st.bash++;
if (/\bwait-for\b/.test(cmd)) { st.waitForCalls++; lastWaitFor = cmd; }
if (seen.has(cmd)) st.dup++; else seen.add(cmd);
for (const m of cmd.matchAll(SLEEP_RE)) {
const v = Number(m[1]);
if (v <= 600) st.sleepSec += v; // >600s 是守护/占位写法,见文件头口径
}
}
}
}
}
return st.bash || st.digestRounds || st.skippedOldRounds ? st : null;
}
async function main() {
const { values } = parseArgs({
options: {
since: { type: "string" }, until: { type: "string" },
limit: { type: "string", default: "50" },
"rounds-since": { type: "string" },
"by-experiment": { type: "boolean", default: false },
noise: { type: "boolean", default: false },
json: { type: "boolean", default: false },
concurrency: { type: "string", default: "6" },
},
});
const sinceMs = values.since ? Date.parse(values.since + "T00:00:00Z") : Date.now() - 60 * 86400_000;
const untilMs = values.until ? Date.parse(values.until + "T23:59:59Z") : Date.now();
const limit = Number(values.limit) || 50;
const conc = Math.max(1, Number(values.concurrency) || 6);
// 上线回测必须传它:样本按 finishedAt 选,但轮次是按开跑时刻算新旧的。
const roundsSinceMs = values["rounds-since"] ? Date.parse(values["rounds-since"] as string) : null;
if (values["rounds-since"] && Number.isNaN(roundsSinceMs)) { console.error("--rounds-since 解析不了,写成 2026-09-14T17:30:00-07:00"); process.exit(2); }
if (values.noise) { await noiseFloor(sinceMs, untilMs); return; }
const all = await listTargets(sinceMs, untilMs);
const picked = all.slice(0, limit);
if (!picked.length) { console.error("窗口内没有已结束的任务。"); process.exit(1); }
console.error(`[poll-waste] 窗口 ${values.since ?? "(60天前)"} ~ ${values.until ?? "(今天)"},命中 ${all.length},取最近 ${picked.length}`);
const stats: TaskStat[] = [];
for (let i = 0; i < picked.length; i += conc) {
const batch = await Promise.all(picked.slice(i, i + conc).map((t) => measure(t, roundsSinceMs)));
for (const s of batch) if (s) stats.push(s);
console.error(`[poll-waste] ${Math.min(i + conc, picked.length)}/${picked.length}`);
}
const sum = (f: (s: TaskStat) => number) => stats.reduce((a, s) => a + f(s), 0);
const rounds = sum((s) => s.rounds);
const out = {
window: `${new Date(sinceMs).toISOString().slice(0, 10)} ~ ${new Date(untilMs).toISOString().slice(0, 10)}`,
tasks: stats.length,
execRoundsWithLog: rounds,
bashCalls: sum((s) => s.bash),
dupCalls: sum((s) => s.dup),
dupRatio: sum((s) => s.bash) ? sum((s) => s.dup) / sum((s) => s.bash) : 0,
sleepSeconds: sum((s) => s.sleepSec),
sleepPerRoundSec: rounds ? Math.round(sum((s) => s.sleepSec) / rounds) : 0,
callsPerRound: rounds ? Math.round(sum((s) => s.bash) / rounds) : 0,
waitForCalls: sum((s) => s.waitForCalls),
waitForTimeouts: sum((s) => s.waitForTimeouts),
waitForTimeoutHours: +(sum((s) => s.waitForTimeoutSec) / 3600).toFixed(1),
skippedOldRounds: sum((s) => s.skippedOldRounds),
roundsSince: values["rounds-since"] ?? null,
waitForAdoptionRounds: stats.filter((s) => s.waitForCalls > 0).length,
roundsTotal: sum((s) => s.digestRounds),
roundsNoSentinel: sum((s) => s.noSentinel),
};
if (values.json) { console.log(JSON.stringify({ baseline: BASELINE, current: out, perTask: stats }, null, 2)); return; }
const pctDelta = (now: number, base: number) => base ? `${((now - base) / base * 100).toFixed(1).padStart(6)}%` : " —";
const line = (label: string, now: string | number, base: string | number, delta = "") =>
console.log(` ${label.padEnd(26)} ${String(now).padStart(10)} 基线 ${String(base).padStart(10)} ${delta}`);
console.log(`\n=== 轮询浪费回测 · ${out.window} ===\n`);
line("任务数", out.tasks, BASELINE.tasks);
line("执行轮(有会话日志)", out.execRoundsWithLog, BASELINE.execRoundsWithLog);
line("Bash 调用", out.bashCalls, BASELINE.bashCalls);
if (roundsSinceMs) console.log(` ${"(已跳过换装前开跑的轮次)".padEnd(26)} ${String(out.skippedOldRounds).padStart(10)}`);
console.log("");
line("重复调用占比 ★", `${(out.dupRatio * 100).toFixed(1)}%`, `${(BASELINE.dupRatio * 100).toFixed(1)}%`, pctDelta(out.dupRatio, BASELINE.dupRatio));
line("每轮 sleep 秒数 ★", out.sleepPerRoundSec, BASELINE.sleepPerRoundSec, pctDelta(out.sleepPerRoundSec, BASELINE.sleepPerRoundSec));
line("每轮 Bash 调用数 ★", out.callsPerRound, BASELINE.callsPerRound, pctDelta(out.callsPerRound, BASELINE.callsPerRound));
line("无哨兵轮占比", `${out.roundsTotal ? (out.roundsNoSentinel / out.roundsTotal * 100).toFixed(0) : 0}%`,
`${(BASELINE.roundsNoSentinel / BASELINE.roundsTotal * 100).toFixed(0)}%`);
console.log("");
line("wait-for 调用次数", out.waitForCalls, 0);
line("★ 其中超时放弃(124)", out.waitForTimeouts, 0);
line("★ 超时烧掉(小时)", out.waitForTimeoutHours, 0);
line("用上 wait-for 的任务", out.waitForAdoptionRounds, 0);
console.log(`\n★ = 这次改动直接冲着去的指标。wait-for 调用次数若仍是 0,先查节点跑的是不是这次部署的提示词(控制面与卫星版本),再谈效果。\n`);
if (values["by-experiment"]) {
const exps = await nodeExperiments();
const groups = new Map<string, TaskStat[]>();
for (const st of stats) {
const key = st.node ? (exps.get(st.node) ?? "(节点已不在册)") : "(不知道跑在哪台)";
groups.set(key, [...(groups.get(key) ?? []), st]);
}
console.log("按节点的实验开关分组(对照组比较用):\n");
console.log(" 开关状态 任务 轮次 重复调用 每轮 sleep(s) 每轮 Bash wait-for");
for (const [key, g] of [...groups].sort((a, b) => b[1].length - a[1].length)) {
const r = g.reduce((s, x) => s + x.rounds, 0);
const bash = g.reduce((s, x) => s + x.bash, 0);
const dup = g.reduce((s, x) => s + x.dup, 0);
const slp = g.reduce((s, x) => s + x.sleepSec, 0);
const wf = g.reduce((s, x) => s + x.waitForCalls, 0);
console.log(` ${key.padEnd(16)} ${String(g.length).padStart(4)} ${String(r).padStart(5)}` +
` ${(bash ? (dup / bash * 100).toFixed(1) : "—").padStart(6)}%` +
` ${String(r ? Math.round(slp / r) : 0).padStart(11)}` +
` ${String(r ? Math.round(bash / r) : 0).padStart(8)}` +
` ${String(wf).padStart(7)}`);
}
console.log("\n 注:开关状态取自 /api/nodes 的**当下**值,不是历史 —— 对照组设好后别中途改。");
console.log(" 「(未上报)」= 该节点还跑着不认识这个字段的旧 bundle。\n");
}
}
if (import.meta.main) await main();
/**
* A/A 噪声底 —— 「我看到的这个差值,和纯随机分得开吗」。
*
* 做法:从**同一个窗口**的真实轮次里反复随机抽两组各 n 轮。两组来自同一总体,所以
* 真实效应是 0;它们中位数之差的分布,就是这个样本量下「什么都没变」时的正常波动。
* 观测到的差值没超过 p90,就不能当成效应。
*
* 用真实轮次自举而不是假设正态:轮时长是重尾的(一轮能从 2 分钟到 8 小时),
* 套正态会把下限估得过于乐观。
*/
async function noiseFloor(sinceMs: number, untilMs: number): Promise<void> {
const rows = await listTargets(sinceMs, untilMs);
const durs: number[] = [];
for (let i = 0; i < rows.length; i += 8) {
const batch = await Promise.all(rows.slice(i, i + 8).map(async (t) => {
const p = t.kind === "bug" ? "tasks" : "features";
const d = await getJson<{ rounds: any[] }>(`/api/${p}/${t.id}/round-digests`);
return (d?.rounds ?? []).map((r) => r.digest?.durationMs ?? 0).filter((x: number) => x > 0);
}));
for (const b of batch) durs.push(...b);
}
if (durs.length < 60) { console.error(`窗口内只有 ${durs.length} 轮,不足以估噪声底`); return; }
const med = (a: number[]) => { const s = [...a].sort((x, y) => x - y); return s[Math.floor(s.length / 2)]; };
const pick = (n: number) => { const o: number[] = []; for (let i = 0; i < n; i++) o.push(durs[(Math.random() * durs.length) | 0]); return o; };
console.log(`\n=== A/A 噪声底 · 窗口内 ${durs.length} 轮,中位 ${(med(durs) / 60000).toFixed(0)}min ===\n`);
console.log(" 每组轮次 两组中位数之差(真实效应=0) 可判别下限");
console.log(" p50 p90 p95 (取 p90)");
for (const n of [20, 50, 100, 200, 400, 800]) {
const d: number[] = [];
for (let k = 0; k < 4000; k++) { const a = med(pick(n)), b = med(pick(n)); d.push(Math.abs(b - a) / a); }
d.sort((x, y) => x - y);
const q = (p: number) => (d[Math.floor(d.length * p)] * 100).toFixed(0) + "%";
console.log(` ${String(n).padStart(6)} ${q(0.5).padStart(5)} ${q(0.9).padStart(6)} ${q(0.95).padStart(6)} > ${q(0.9)}`);
}
console.log("\n 读法:同一总体抽两组,有一成概率飘出 p90 那一列。观测差值不超过它就判不了。");
console.log(" 提醒:单轮时长是重尾的。近乎确定性的计数(重复调用占比、超时次数)信噪比高得多。\n");
}