feat: compare history indexes on uneven chats in bench

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-02 04:24:59 +03:00
co-authored by Claude Opus 5.5
parent 3f3acc95b8
commit d2656ab986
12 changed files with 1597 additions and 162 deletions
+13 -21
View File
@@ -1,14 +1,15 @@
// Этап плана: три страницы истории читаемого чата подряд, пока в Postgres
// стенда включён auto_explain. Первая — без курсора, средняя и последняя
// полная — курсоры из пула (середина и конец). Порядок запросов = порядок
// планов в журнале: оркестратор сопоставляет их по нему.
// Этап плана: страницы истории из plan_pages.json подряд, пока в Postgres
// стенда включён auto_explain. Для читаемого чата и первого чата каждого
// фонового уровня — первая, средняя и последняя полная страница (у
// короткого чата — первая). Порядок запросов = порядок планов в журнале:
// оркестратор сопоставляет их по нему.
import http from "k6/http";
import { check, fail } from "k6";
import { API, PAGE_LIMIT, WORK_DIR, authHeaders } from "./lib.js";
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
const pool = JSON.parse(open(`${WORK_DIR}/cursors.json`));
const pages = JSON.parse(open(`${WORK_DIR}/plan_pages.json`));
export const options = {
vus: 1,
@@ -16,26 +17,17 @@ export const options = {
};
export default function () {
const cursors = pool.cursors;
if (cursors.length === 0) {
fail("cursor pool is empty: history is shorter than a walk page");
}
const pages = [
["first", null],
["middle", cursors[Math.floor(cursors.length / 2)]],
["last", cursors[cursors.length - 1]],
];
const url = `${API}/chats/${fixture.readChatId}/messages`;
const params = { headers: authHeaders(fixture.tokens[fixture.readerId]) };
for (const [name, cursor] of pages) {
const query = cursor === null
for (const page of pages) {
const name = `${page.chat} ${page.page}`;
const query = page.cursor === null
? `?limit=${PAGE_LIMIT}`
: `?limit=${PAGE_LIMIT}&cursor=${encodeURIComponent(cursor)}`;
const res = http.get(url + query, params);
: `?limit=${PAGE_LIMIT}&cursor=${encodeURIComponent(page.cursor)}`;
const res = http.get(`${API}/chats/${page.chat_id}/messages${query}`, params);
const ok = check(res, {
[`${name} 200`]: (r) => r.status === 200,
[`${name} full page`]: (r) =>
r.status === 200 && r.json("items.#") === PAGE_LIMIT,
[`${name} ${page.items} items`]: (r) =>
r.status === 200 && r.json("items.#") === page.items,
});
if (!ok) {
fail(`explain page ${name}: ${res.status}`);
+51
View File
@@ -0,0 +1,51 @@
// Курсоры страниц плана фоновых чатов (трек 2): проход истории каждого чата
// из plan_chats.json страницами по WALK_LIMIT, позиция и курсор после каждой
// страницы. Идёт до включения auto_explain, поэтому в журнал не попадает;
// заодно прогревает страницы этих чатов, как cursors.js — читаемого.
import http from "k6/http";
import { fail } from "k6";
import { API, WORK_DIR, authHeaders } from "./lib.js";
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
const chats = JSON.parse(open(`${WORK_DIR}/plan_chats.json`));
const WALK_LIMIT = Number(__ENV.WALK_LIMIT || 100);
export const options = {
vus: 1,
iterations: 1,
setupTimeout: "10m",
};
export function setup() {
const params = { headers: authHeaders(fixture.tokens[fixture.readerId]) };
return chats.map((chat) => {
const url = `${API}/chats/${chat.id}/messages`;
const positions = [];
let cursor = null;
let walked = 0;
for (;;) {
const query = cursor === null
? `?limit=${WALK_LIMIT}`
: `?limit=${WALK_LIMIT}&cursor=${encodeURIComponent(cursor)}`;
const res = http.get(url + query, params);
if (res.status !== 200) {
fail(`chat ${chat.id} after ${walked}: ${res.status} ${res.body}`);
}
const body = res.json();
walked += body.items.length;
if (body.next_cursor === null) {
break;
}
positions.push({ after: walked, cursor: body.next_cursor });
cursor = body.next_cursor;
}
return { id: chat.id, walked, positions };
});
}
export default function () {}
export function handleSummary(data) {
return { [`${WORK_DIR}/plan_walks.json`]: JSON.stringify(data.setup_data) };
}
+11 -3
View File
@@ -1,6 +1,9 @@
// Одна порция наполнения читаемого чата: COUNT сообщений от участников по
// кругу. OFFSET — сколько сообщений уже отправлено, для номеров в тексте.
// Одна порция наполнения: COUNT сообщений от участников по кругу. Чат
// сообщения n берётся из расписания оркестратора (schedule.json: 0 —
// читаемый чат, дальше фоновые в порядке фикстуры), так что сообщения всех
// чатов идут вперемешку. OFFSET — сколько сообщений уже отправлено.
import exec from "k6/execution";
import { SharedArray } from "k6/data";
import {
SUMMARY_THRESHOLDS,
@@ -12,6 +15,11 @@ import {
} from "./lib.js";
const fixture = JSON.parse(open(`${WORK_DIR}/fixture.json`));
const schedule = new SharedArray(
"schedule",
() => JSON.parse(open(`${WORK_DIR}/schedule.json`)),
);
const chats = [fixture.readChatId, ...fixture.bgChats.map((c) => c.id)];
const OFFSET = Number(__ENV.OFFSET || 0);
export const options = {
@@ -32,7 +40,7 @@ export default function () {
const n = OFFSET + exec.scenario.iterationInTest;
const sender = fixture.memberIds[n % fixture.memberIds.length];
sendMessage(
fixture.readChatId,
chats[schedule[n]],
fixture.tokens[sender],
syntheticText("p", n),
);
+21 -5
View File
@@ -1,15 +1,21 @@
// Пользователи и два чата стенда: читаемый (сценарий read) и чат записи
// (сценарий write). Каждый пользователь регистрируется с паролем и входит по
// Basic; в фикстуру идут id и Bearer-токены, пароли — нет. Итог —
// fixture.json в рабочем каталоге: оркестратор удаляет его в конце прогона.
// Пользователи и чаты стенда: читаемый (сценарий read), чат записи
// (сценарий write) и фоновые чаты неравномерных размеров (трек 2). Каждый
// пользователь регистрируется с паролем и входит по Basic; в фикстуру идут
// id и Bearer-токены, пароли — нет. Итог — fixture.json в рабочем каталоге:
// оркестратор удаляет его в конце прогона.
import { WORK_DIR, createChat, register } from "./lib.js";
const MEMBERS = Number(__ENV.MEMBERS || 10);
// уровни фоновых чатов: «10x5000,100x400» — число чатов x сообщений в чате
const BACKGROUND = (__ENV.BACKGROUND || "")
.split(",")
.filter((tier) => tier !== "")
.map((tier) => tier.split("x").map(Number));
export const options = {
vus: 1,
iterations: 1,
setupTimeout: "60s",
setupTimeout: "5m",
};
export function setup() {
@@ -25,12 +31,22 @@ export function setup() {
memberIds.push(member.id);
}
const everyone = [reader.id, ...memberIds];
// фоновые чаты в порядке уровней: номер чата в расписании наполнения —
// 1 + индекс в этом списке (0 — читаемый чат)
const bgChats = [];
for (const [count, size] of BACKGROUND) {
for (let i = 0; i < count; i++) {
const title = `bench bg ${size} #${i}`;
bgChats.push({ id: createChat(reader.token, title, everyone), size });
}
}
return {
readerId: reader.id,
memberIds,
tokens,
readChatId: createChat(reader.token, "bench read", everyone),
writeChatId: createChat(reader.token, "bench write", everyone),
bgChats,
};
}