fix: count bg lines in k6 so SIGINT-interrupted iterations do not fail the check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-23 07:55:42 +03:00
co-authored by Claude Opus 5.5
parent aaf3fa3b29
commit a42dd27c24
6 changed files with 157 additions and 18 deletions
+14 -1
View File
@@ -5,12 +5,14 @@
// сообщений в чат записи и чтение его первой страницы истории. Каждый
// запрос — строка «bg,<d|w|r>,<отправка мс>,<длительность мс>,<статус>» в
// файл консоли k6; run.py делит их на окна до, во время и после прохода
// сверки и сверяет число строк с итерациями сценариев. Оркестратор
// сверки и сверяет число строк со счётчиком bg_lines_<сценарий> (точно) и
// с итерациями сценариев (снизу). Оркестратор
// останавливает прогон сигналом SIGINT, когда блок проходов закончен:
// итог (handleSummary) k6 пишет и тогда.
import exec from "k6/execution";
import http from "k6/http";
import { SharedArray } from "k6/data";
import { Counter } from "k6/metrics";
import {
API,
@@ -34,6 +36,16 @@ const PRE_VUS = Number(__ENV.PRE_VUS || 100);
const MAX_VUS = Number(__ENV.MAX_VUS || 600);
const TIMEOUT = __ENV.TIMEOUT || "15s";
const READER = authHeaders(fixture.tokens[fixture.readerId]);
// счёт строк bg,… тем же кодом, что их пишет: итерация, которую остановка
// SIGINT прервала уже после строки, в iterations не входит, а в этот
// счётчик — входит. run.py сверяет строки файла консоли с ним точно, а с
// iterations — снизу (design change track2-reconcile-cost, «Уточнения
// apply», п. 15)
const LINES = {
d: new Counter("bg_lines_download"),
w: new Counter("bg_lines_write"),
r: new Counter("bg_lines_read"),
};
const WRITE_URL = `${API}/chats/${fixture.writeChatId}/messages`;
function scenario(fn, rate) {
@@ -76,6 +88,7 @@ function report(kind, start, res) {
0,
Math.round((res.status === 0 ? Date.now() - start : measured) * 100) / 100,
);
LINES[kind].add(1);
console.log(`bg,${kind},${start},${duration},${res.status}`);
}
+90
View File
@@ -531,6 +531,54 @@ def parse_background(text: str) -> list[Request]:
return out
def summary_count(k6_data: dict[str, Any], name: str) -> int | None:
value = k6_data.get("metrics", {}).get(name, {}).get("values", {})
count = value.get("count")
return None if count is None else int(count)
def line_problems(
requests: list[Request],
k6_data: dict[str, Any],
*,
max_vus: int,
) -> tuple[list[str], dict[str, int]]:
"""Полнота строк `bg,…` по итогу k6 (design, «Уточнения apply», п.
15): строк каждого сценария ровно столько, сколько насчитал счётчик
`bg_lines_<сценарий>` (его увеличивает тот же код, что пишет строку, —
пропавшая строка видна точно), и не меньше итераций. Строк больше
итераций — итерации, прерванные остановкой SIGINT уже после строки:
их не больше VU сценария. Возвращает расхождения и число прерванных по
сценариям."""
problems = []
interrupted: dict[str, int] = {}
for kind, scenario in SCENARIOS.items():
lines = sum(1 for r in requests if r.kind == kind)
counted = summary_count(k6_data, f"bg_lines_{scenario}")
iterations = summary_count(
k6_data,
f"iterations{{scenario:{scenario}}}",
)
if counted is None or iterations is None:
problems.append(
f"{scenario}: no bg_lines or iterations in the k6 summary",
)
continue
if lines != counted:
problems.append(
f"{scenario}: {lines} k6 lines, {counted} counted by "
"bg_lines (lines lost)",
)
extra = lines - iterations
interrupted[scenario] = extra
if not 0 <= extra <= max_vus:
problems.append(
f"{scenario}: {lines} k6 lines, {iterations} iterations "
f"(interrupted must be 0–{max_vus})",
)
return problems, interrupted
def percentile(values: list[float], q: float) -> float | None:
"""Перцентиль ближайшего ранга, как у k6 (p(95))."""
if not values:
@@ -1723,6 +1771,48 @@ def selftest() -> int:
)
parsed = parse_background(console + "\nnoise\nbg,x,1,2,3\n")
expect("bg parsed", len(parsed), len(reqs))
# полнота строк: точное равенство со счётчиком, прерванные — сверху
counts = {
kind: sum(1 for r in parsed if r.kind == kind) for kind in SCENARIOS
}
def summary(extra: int, lost: int) -> dict[str, Any]:
metrics = {}
for kind, scenario in SCENARIOS.items():
metrics[f"bg_lines_{scenario}"] = {
"values": {
"count": counts[kind] + (lost if kind == "d" else 0),
},
}
metrics[f"iterations{{scenario:{scenario}}}"] = {
"values": {
"count": counts[kind] - (extra if kind == "d" else 0),
},
}
return {"metrics": metrics}
expect("lines ok", line_problems(parsed, summary(0, 0), max_vus=5)[0], [])
problems, interrupted = line_problems(parsed, summary(1, 0), max_vus=5)
expect(
"lines interrupted ok",
(problems, interrupted["download"]),
([], 1),
)
expect(
"lines lost",
len(line_problems(parsed, summary(0, 1), max_vus=5)[0]),
1,
)
expect(
"lines too many interrupted",
len(line_problems(parsed, summary(6, 0), max_vus=5)[0]),
1,
)
expect(
"lines no counter",
len(line_problems(parsed, {"metrics": {}}, max_vus=5)[0]),
3,
)
bounds = {"before": (0, 10), "pass": (10, 20), "after": (20, 30)}
rows, ratios_one = windows_of(parsed, bounds)
expect("window rows", len(rows), 12)
+15 -13
View File
@@ -389,6 +389,9 @@ class Profile:
("read", 50),
)
reconcile_downloads: int = 5000
# предел VU сценария фоновой нагрузки (MAX_VUS background.js): им же
# ограничено число итераций, прерванных остановкой SIGINT
reconcile_bg_max_vus: int = 600
reconcile_quiet_s: int = 30
reconcile_fill_processes: int = 3
reconcile_fill_threads: int = 24
@@ -6417,6 +6420,7 @@ class Bench:
"WRITE_RATE": rates["write"],
"READ_RATE": rates["read"],
"DURATION": "6h",
"MAX_VUS": p.reconcile_bg_max_vus,
"NAME": "h4-k6",
},
log_name,
@@ -6463,19 +6467,17 @@ class Bench:
),
)
k6_data = json.loads(summary.read_text(encoding="utf-8"))
for kind, scenario in reconcile.SCENARIOS.items():
iterations = (
k6_data["metrics"]
.get(f"iterations{{scenario:{scenario}}}", {})
.get("values", {})
.get("count")
)
lines = sum(1 for r in requests if r.kind == kind)
if iterations != lines:
raise BenchError(
f"{stage}: {lines} k6 lines of {scenario}, {iterations} "
"iterations",
)
problems, interrupted = reconcile.line_problems(
requests,
k6_data,
max_vus=p.reconcile_bg_max_vus,
)
self.results.meta["reconcile"].setdefault("bg_interrupted", {})[
stage
] = interrupted
self.results.write_meta()
if problems:
raise BenchError(f"{stage}: " + "; ".join(problems))
for entry, result in done:
bounds = {
"before": (result["started_at"] - quiet, result["started_at"]),