feat: run load bench on PostgreSQL with query plans
- bench stand is a separate compose project mtusi-bench (API, Postgres, Valkey) with fixed limits, fresh volume per size and migrations - k6 registers with a password, logs in with Basic and sends Bearer - VACUUM (ANALYZE) and CHECKPOINT after prefill - EXPLAIN (ANALYZE, BUFFERS) of the app's history query via auto_explain, plus the same query without the index in a rolled back transaction - Postgres CPU, table and index size in results; storages in passport - bench_compare checks storage limits, images and settings - remove inproc.py and make bench_inproc Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+3
-1
@@ -19,7 +19,7 @@ export const options = {
|
||||
|
||||
export function setup() {
|
||||
const url = `${API}/chats/${fixture.readChatId}/messages`;
|
||||
const params = { headers: authHeaders(fixture.readerId) };
|
||||
const params = { headers: authHeaders(fixture.tokens[fixture.readerId]) };
|
||||
const positions = [];
|
||||
let cursor = null;
|
||||
let walked = 0;
|
||||
@@ -50,6 +50,8 @@ export function setup() {
|
||||
eligible: eligible.length,
|
||||
first_after: pool.length ? pool[0].after : null,
|
||||
last_after: pool.length ? pool[pool.length - 1].after : null,
|
||||
// позиции курсоров пула: сколько сообщений до каждого (для плана)
|
||||
afters: pool.map((p) => p.after),
|
||||
cursors: pool.map((p) => p.cursor),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// Этап плана: три страницы истории читаемого чата подряд, пока в 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`));
|
||||
|
||||
export const options = {
|
||||
vus: 1,
|
||||
iterations: 1,
|
||||
};
|
||||
|
||||
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
|
||||
? `?limit=${PAGE_LIMIT}`
|
||||
: `?limit=${PAGE_LIMIT}&cursor=${encodeURIComponent(cursor)}`;
|
||||
const res = http.get(url + query, params);
|
||||
const ok = check(res, {
|
||||
[`${name} 200`]: (r) => r.status === 200,
|
||||
[`${name} full page`]: (r) =>
|
||||
r.status === 200 && r.json("items.#") === PAGE_LIMIT,
|
||||
});
|
||||
if (!ok) {
|
||||
fail(`explain page ${name}: ${res.status}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// итог не нужен: планы оркестратор берёт из журнала Postgres
|
||||
export function handleSummary() {
|
||||
return {};
|
||||
}
|
||||
+28
-9
@@ -1,5 +1,6 @@
|
||||
// Общие хелперы сценариев стенда: адрес, идентификация, текст, генератор
|
||||
// случайных чисел, запись итога. Не Node.js: только встроенные модули k6.
|
||||
import encoding from "k6/encoding";
|
||||
import http from "k6/http";
|
||||
import { check, fail } from "k6";
|
||||
|
||||
@@ -20,9 +21,18 @@ export const SUCCESS_DURATION = "http_req_duration{expected_response:true}";
|
||||
// порог всегда выполняется: он нужен, чтобы подметрика попала в итог
|
||||
export const SUMMARY_THRESHOLDS = { [SUCCESS_DURATION]: ["max>=0"] };
|
||||
|
||||
// идентификация лабы 1; с лабы 2 здесь Bearer, как Actor.headers()
|
||||
export function authHeaders(userId) {
|
||||
return { "X-User-Id": userId, "Content-Type": "application/json" };
|
||||
// идентификация, как Actor.headers() в student-tests: Bearer-токен сессии
|
||||
export function authHeaders(token) {
|
||||
return {
|
||||
Authorization: `Bearer ${token}`,
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
}
|
||||
|
||||
// синтетический пароль (72 символа, контракт — 12–128): только в памяти
|
||||
// prepare.js, в фикстуру и результаты не попадает
|
||||
function syntheticPassword() {
|
||||
return `${crypto.randomUUID()}-${crypto.randomUUID()}`;
|
||||
}
|
||||
|
||||
// синтетический текст ровно TEXT_LENGTH ASCII-символов
|
||||
@@ -43,23 +53,32 @@ export function mulberry32(seed) {
|
||||
};
|
||||
}
|
||||
|
||||
// регистрация с паролем и вход по Basic: { id, token } пользователя
|
||||
export function register(username, displayName) {
|
||||
const password = syntheticPassword();
|
||||
const res = http.post(
|
||||
`${API}/users`,
|
||||
JSON.stringify({ username, display_name: displayName }),
|
||||
JSON.stringify({ username, display_name: displayName, password }),
|
||||
{ headers: { "Content-Type": "application/json" } },
|
||||
);
|
||||
if (!check(res, { "register 201": (r) => r.status === 201 })) {
|
||||
fail(`register ${username}: ${res.status} ${res.body}`);
|
||||
}
|
||||
return res.json("id");
|
||||
const basic = encoding.b64encode(`${username}:${password}`);
|
||||
const login = http.post(`${API}/auth/sessions`, null, {
|
||||
headers: { Authorization: `Basic ${basic}` },
|
||||
});
|
||||
if (!check(login, { "login 201": (r) => r.status === 201 })) {
|
||||
fail(`login ${username}: ${login.status} ${login.body}`);
|
||||
}
|
||||
return { id: res.json("id"), token: login.json("token") };
|
||||
}
|
||||
|
||||
export function createChat(ownerId, title, memberIds) {
|
||||
export function createChat(ownerToken, title, memberIds) {
|
||||
const res = http.post(
|
||||
`${API}/chats`,
|
||||
JSON.stringify({ title, member_ids: memberIds }),
|
||||
{ headers: authHeaders(ownerId) },
|
||||
{ headers: authHeaders(ownerToken) },
|
||||
);
|
||||
if (!check(res, { "chat 201": (r) => r.status === 201 })) {
|
||||
fail(`create chat ${title}: ${res.status} ${res.body}`);
|
||||
@@ -67,12 +86,12 @@ export function createChat(ownerId, title, memberIds) {
|
||||
return res.json("id");
|
||||
}
|
||||
|
||||
export function sendMessage(chatId, senderId, text) {
|
||||
export function sendMessage(chatId, senderToken, text) {
|
||||
const res = http.post(
|
||||
`${API}/chats/${chatId}/messages`,
|
||||
JSON.stringify({ text }),
|
||||
{
|
||||
headers: authHeaders(senderId),
|
||||
headers: authHeaders(senderToken),
|
||||
responseCallback: http.expectedStatuses(201),
|
||||
},
|
||||
);
|
||||
|
||||
+5
-1
@@ -31,7 +31,11 @@ export const options = {
|
||||
export default function () {
|
||||
const n = OFFSET + exec.scenario.iterationInTest;
|
||||
const sender = fixture.memberIds[n % fixture.memberIds.length];
|
||||
sendMessage(fixture.readChatId, sender, syntheticText("p", n));
|
||||
sendMessage(
|
||||
fixture.readChatId,
|
||||
fixture.tokens[sender],
|
||||
syntheticText("p", n),
|
||||
);
|
||||
}
|
||||
|
||||
export function handleSummary(data) {
|
||||
|
||||
+15
-8
@@ -1,5 +1,7 @@
|
||||
// Пользователи и два чата стенда: читаемый (сценарий read) и чат записи
|
||||
// (сценарий write). Итог — fixture.json в рабочем каталоге.
|
||||
// (сценарий write). Каждый пользователь регистрируется с паролем и входит по
|
||||
// Basic; в фикстуру идут id и Bearer-токены, пароли — нет. Итог —
|
||||
// fixture.json в рабочем каталоге: оркестратор удаляет его в конце прогона.
|
||||
import { WORK_DIR, createChat, register } from "./lib.js";
|
||||
|
||||
const MEMBERS = Number(__ENV.MEMBERS || 10);
|
||||
@@ -11,19 +13,24 @@ export const options = {
|
||||
};
|
||||
|
||||
export function setup() {
|
||||
// размер начинается с пустого процесса, поэтому имени хватает времени
|
||||
// размер начинается с пустой базы, поэтому имени хватает времени
|
||||
const stamp = Date.now().toString(36);
|
||||
const readerId = register(`b${stamp}_reader`, "Bench reader");
|
||||
const tokens = {};
|
||||
const reader = register(`b${stamp}_reader`, "Bench reader");
|
||||
tokens[reader.id] = reader.token;
|
||||
const memberIds = [];
|
||||
for (let i = 0; i < MEMBERS; i++) {
|
||||
memberIds.push(register(`b${stamp}_m${i}`, `Bench member ${i}`));
|
||||
const member = register(`b${stamp}_m${i}`, `Bench member ${i}`);
|
||||
tokens[member.id] = member.token;
|
||||
memberIds.push(member.id);
|
||||
}
|
||||
const everyone = [readerId, ...memberIds];
|
||||
const everyone = [reader.id, ...memberIds];
|
||||
return {
|
||||
readerId,
|
||||
readerId: reader.id,
|
||||
memberIds,
|
||||
readChatId: createChat(readerId, "bench read", everyone),
|
||||
writeChatId: createChat(readerId, "bench write", everyone),
|
||||
tokens,
|
||||
readChatId: createChat(reader.token, "bench read", everyone),
|
||||
writeChatId: createChat(reader.token, "bench write", everyone),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ const SEED = Number(__ENV.SEED || 0);
|
||||
const TRACE = Number(__ENV.TRACE || 0);
|
||||
const URL = `${API}/chats/${fixture.readChatId}/messages`;
|
||||
const PARAMS = {
|
||||
headers: authHeaders(fixture.readerId),
|
||||
headers: authHeaders(fixture.tokens[fixture.readerId]),
|
||||
responseCallback: http.expectedStatuses(200),
|
||||
};
|
||||
|
||||
|
||||
+1
-1
@@ -18,7 +18,7 @@ export const options = {
|
||||
|
||||
export function setup() {
|
||||
const url = `${API}/chats/${fixture.readChatId}/messages`;
|
||||
const params = { headers: authHeaders(fixture.readerId) };
|
||||
const params = { headers: authHeaders(fixture.tokens[fixture.readerId]) };
|
||||
// пустой пул (история короче страницы обхода) — читаем с начала
|
||||
const hasPool = pool.cursors.length > 0;
|
||||
let cursor = hasPool ? pool.cursors[pool.cursors.length - 1] : null;
|
||||
|
||||
+5
-1
@@ -31,7 +31,11 @@ export const options = {
|
||||
export default function () {
|
||||
const n = OFFSET + exec.scenario.iterationInTest;
|
||||
const sender = fixture.memberIds[n % fixture.memberIds.length];
|
||||
sendMessage(fixture.writeChatId, sender, syntheticText("w", n));
|
||||
sendMessage(
|
||||
fixture.writeChatId,
|
||||
fixture.tokens[sender],
|
||||
syntheticText("w", n),
|
||||
);
|
||||
}
|
||||
|
||||
export function handleSummary(data) {
|
||||
|
||||
Reference in New Issue
Block a user