Prepare verified laboratory 3 implementation and evidence

This commit is contained in:
rey
2026-11-17 17:31:17 +03:00
parent 0ab3a341aa
commit 3d67e677d0
176 changed files with 21076 additions and 38 deletions
+428
View File
@@ -0,0 +1,428 @@
import { resolve } from "node:path";
const root = resolve(import.meta.dir, "..");
const lab = (await Bun.file(resolve(root, "lab.json")).json()).number;
const base = process.env.BASE_URL ?? "http://127.0.0.1:28203";
const kubernetes = process.env.VP_RUNTIME !== "compose";
if (kubernetes) {
const p = Bun.spawn(
[
process.execPath,
"--no-env-file",
resolve(root, "scripts/k3s.ts"),
"info",
],
{ cwd: root, stdout: "pipe", stderr: "pipe" },
);
const [out, err] = await Promise.all([
new Response(p.stdout).text(),
new Response(p.stderr).text(),
]);
if ((await p.exited) !== 0)
throw new Error("Claimed Kubernetes endpoint unavailable");
const info = JSON.parse(out);
if (new URL(base).origin !== "http://127.0.0.1:" + info.port)
throw new Error("HTTP target differs from the claimed cluster");
}
const prefix = `st_${crypto.randomUUID().replaceAll("-", "").slice(0, 16)}`;
let assertions = 0;
let operation = "initialization";
function check(value: unknown, message: string): asserts value {
if (!value) throw new Error(message);
assertions++;
}
async function call(
method: string,
path: string,
status: number,
token?: string,
body?: unknown,
headers: Record<string, string> = {},
) {
operation = method + " " + path;
const response = await fetch(base + path, {
method,
headers: {
...(token ? { Authorization: `Bearer ${token}` } : {}),
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
...headers,
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(8000),
});
const bytes = await response.arrayBuffer();
let json: any;
try {
json = JSON.parse(new TextDecoder().decode(bytes));
} catch {}
check(
response.status === status,
`${method} ${path}: expected ${status}, got ${response.status}`,
);
check(Boolean(response.headers.get("X-Request-Id")), "Missing request ID");
if (status >= 400)
check(
json?.error?.request_id === response.headers.get("X-Request-Id"),
"Error request ID mismatch",
);
return { json, response, bytes };
}
const password = "synthetic:пароль🙂123";
async function user(suffix: string) {
const registration = {
username: prefix + suffix,
display_name: "Синтетический тест",
password,
};
const { json } = await call(
"POST",
"/api/v1/users",
201,
undefined,
registration,
);
const login = await call(
"POST",
"/api/v1/auth/sessions",
201,
undefined,
undefined,
{
Authorization:
"Basic " +
Buffer.from(registration.username + ":" + password).toString("base64"),
},
);
check(!JSON.stringify(json).includes("password"), "Password leaked in User");
check(
typeof login.json.token === "string" && login.json.token.length >= 43,
"Token entropy/shape",
);
return { id: json.id, token: login.json.token, registration };
}
async function cleanup() {
// No API delete exists. Scope every statement to this run's random username prefix.
const sql = `BEGIN;
CREATE TEMP TABLE own_users AS SELECT id FROM users WHERE left(username,${prefix.length})='${prefix}';
DO $fixture$ BEGIN IF EXISTS(SELECT 1 FROM chat_members mine JOIN chat_members other ON other.chat_id=mine.chat_id WHERE mine.user_id IN(SELECT id FROM own_users) AND other.user_id NOT IN(SELECT id FROM own_users)) THEN RAISE EXCEPTION 'fixture has foreign memberships';END IF;END $fixture$;
CREATE TEMP TABLE own_chats AS SELECT DISTINCT mine.chat_id AS id FROM chat_members mine WHERE mine.user_id IN (SELECT id FROM own_users) AND NOT EXISTS(SELECT 1 FROM chat_members other WHERE other.chat_id=mine.chat_id AND other.user_id NOT IN(SELECT id FROM own_users));
${lab >= 3 ? "DELETE FROM idempotency WHERE user_id IN (SELECT id FROM own_users);" : ""}
DELETE FROM messages WHERE sender_id IN (SELECT id FROM own_users);
DELETE FROM sessions WHERE user_id IN (SELECT id FROM own_users);
DELETE FROM chat_members WHERE chat_id IN (SELECT id FROM own_chats);
DELETE FROM chats WHERE id IN (SELECT id FROM own_chats);
DELETE FROM users WHERE id IN (SELECT id FROM own_users);
COMMIT;
SELECT count(*) FROM users WHERE left(username,${prefix.length})='${prefix}';`;
const p = Bun.spawn(
kubernetes
? [
resolve(root, "scripts/kube.sh"),
"exec",
"-i",
"deployment/postgres",
"--",
"psql",
"-X",
"-qAt",
"-U",
"messenger",
"-d",
"messenger",
"-v",
"ON_ERROR_STOP=1",
]
: [
resolve(root, "scripts/compose.sh"),
"exec",
"-T",
"postgres",
"psql",
"-X",
"-qAt",
"-U",
"messenger",
"-d",
"messenger",
"-v",
"ON_ERROR_STOP=1",
],
{ cwd: root, stdin: "pipe", stdout: "pipe", stderr: "pipe" },
);
p.stdin.write(sql);
p.stdin.end();
const out = await new Response(p.stdout).text();
const err = await new Response(p.stderr).text();
if ((await p.exited) !== 0)
throw new Error(
"Fixture cleanup failed: " +
err.replace(/password|token/gi, "[redacted]"),
);
check(
out.trim() === "0",
"Fixture users remain after cleanup or SQL stdin was not executed",
);
}
let primary: unknown;
try {
const alice = await user("a"),
bob = await user("b"),
eve = await user("e");
await call("POST", "/api/v1/users", 400, undefined, {
username: prefix + "x",
display_name: "x",
});
await call("POST", "/api/v1/users", 400, undefined, {
...alice.registration,
password: "short",
});
await call("POST", "/api/v1/users", 400, undefined, {
...alice.registration,
extra: 1,
});
const race = await Promise.all(
[0, 1].map(async () => {
const r = await fetch(base + "/api/v1/users", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
...alice.registration,
username: prefix + "race",
}),
});
await r.arrayBuffer();
return r.status;
}),
);
check(
race.sort().join(",") === "201,409",
"Registration race must create exactly one user",
);
const denied = await call(
"GET",
"/api/v1/users/me",
401,
undefined,
undefined,
{ "X-User-Id": alice.id },
);
check(
denied.response.headers.get("WWW-Authenticate") ===
'Bearer realm="messenger"',
"Bearer challenge",
);
const wrong = await call(
"POST",
"/api/v1/auth/sessions",
401,
undefined,
undefined,
{
Authorization:
"Basic " +
Buffer.from(alice.registration.username + ":wrong-password").toString(
"base64",
),
},
);
check(
wrong.response.headers.get("WWW-Authenticate") ===
'Basic realm="messenger", charset="UTF-8"',
"Basic challenge",
);
const invalidChat = {
title: "rollback",
member_ids: [alice.id, crypto.randomUUID()],
};
await call("POST", "/api/v1/chats", 400, alice.token, invalidChat);
let page = (await call("GET", "/api/v1/chats", 200, alice.token)).json;
check(
page.items.length === 0 && page.next_cursor === null,
"Failed composite create left a chat",
);
const chat = (
await call("POST", "/api/v1/chats", 201, alice.token, {
title: "Пагинация",
member_ids: [bob.id, alice.id],
})
).json;
const path = "/api/v1/chats/" + chat.id + "/messages";
check(
(await call("GET", path, 200, alice.token)).json.items.length === 0,
"Empty page",
);
for (const limit of ["0", "-1", "101", "1.2", "abc"])
await call("GET", path + "?limit=" + limit, 400, alice.token);
await call("GET", path + "?cursor=%%%", 400, alice.token);
await call("GET", path, 404, eve.token);
const sent = [];
for (let i = 0; i < 102; i++) {
const h = lab >= 3 ? { "Idempotency-Key": crypto.randomUUID() } : {};
sent.push(
(
await call(
"POST",
path,
201,
alice.token,
{ text: `Сообщение ${i}` },
h,
)
).json,
);
}
check(
(await call("GET", path, 200, bob.token)).json.items.length === 50,
"Default bound",
);
check(
(await call("GET", path + "?limit=100", 200, bob.token)).json.items
.length === 100,
"Maximum bound",
);
const seen = [];
let cursor: string | null = null;
do {
page = (
await call(
"GET",
path +
"?limit=7" +
(cursor ? "&cursor=" + encodeURIComponent(cursor) : ""),
200,
bob.token,
)
).json;
check(page.items.length <= 7, "Page bound");
seen.push(...page.items);
cursor = page.next_cursor;
} while (cursor);
check(
JSON.stringify(seen) === JSON.stringify(sent),
"Traversal must preserve every item exactly once",
);
const other = (
await call("POST", "/api/v1/chats", 201, alice.token, {
title: "Другой",
member_ids: [alice.id],
})
).json;
const first = (await call("GET", path + "?limit=1", 200, alice.token)).json;
await call(
"GET",
"/api/v1/chats/" +
other.id +
"/messages?cursor=" +
encodeURIComponent(first.next_cursor),
400,
alice.token,
);
if (lab >= 3) {
const key = crypto.randomUUID(),
headers = { "Idempotency-Key": key },
body = { text: "один конкурентный результат" };
const results = await Promise.all(
Array.from({ length: 12 }, () =>
call("POST", path, 201, alice.token, body, headers),
),
);
check(
new Set(results.map((r) => r.json.id)).size === 1,
"Concurrent retries duplicated a message",
);
await call("POST", path, 409, alice.token, { text: "другой" }, headers);
await call("POST", path, 400, alice.token, { text: "без ключа" });
const ids = new Set<string>();
for (let i = 0; i < 20; i++)
ids.add(
(
await call("GET", "/api/v1/users/me", 200, alice.token)
).response.headers.get("X-Instance-Id")!,
);
check(
ids.size >= 2 && !ids.has(null as any),
"One session must reach multiple actual replicas",
);
}
await call("DELETE", "/api/v1/auth/sessions/current", 204, alice.token);
await call("GET", "/api/v1/users/me", 401, alice.token);
if (process.env.FAILURES === "1") {
async function compose(args: string[], ttl?: string) {
const p = Bun.spawn([resolve(root, "scripts/compose.sh"), ...args], {
cwd: root,
env: { ...process.env, ...(ttl ? { SESSION_TTL_SECONDS: ttl } : {}) },
stdout: "pipe",
stderr: "pipe",
});
await Promise.all([
new Response(p.stdout).text(),
new Response(p.stderr).text(),
]);
check((await p.exited) === 0, "Compose failure action failed");
}
async function ready() {
for (let i = 0; i < 150; i++) {
try {
const r = await fetch(base + "/health/ready", {
signal: AbortSignal.timeout(1500),
});
await r.arrayBuffer();
if (r.status === 200) return;
} catch {}
await Bun.sleep(100);
}
throw new Error("Readiness did not recover");
}
try {
await compose(["stop", "valkey"]);
await call("GET", "/api/v1/users/me", 200, bob.token);
await call("GET", "/api/v1/users/me", 401, undefined, undefined, {
"X-User-Id": bob.id,
});
} finally {
await compose(["start", "valkey"]);
}
try {
await compose(["stop", "postgres"]);
await call("GET", "/api/v1/users/me", 503, bob.token);
await call("GET", "/health/ready", 503);
await call("GET", "/health/live", 200);
} finally {
await compose(["start", "postgres"]);
await ready();
}
await call("GET", "/api/v1/users/me", 200, bob.token);
if (lab === 2) {
try {
await compose(
["up", "-d", "--no-deps", "--force-recreate", "api"],
"2",
);
await ready();
const short = await user("ttl");
await call("GET", "/api/v1/users/me", 200, short.token);
await Bun.sleep(2200);
await call("GET", "/api/v1/users/me", 401, short.token);
} finally {
await compose(
["up", "-d", "--no-deps", "--force-recreate", "api"],
"3600",
);
await ready();
}
}
}
} catch (error) {
primary = new Error("Acceptance failed during " + operation, {
cause: error,
});
}
try {
await cleanup();
} catch (error) {
console.error(String(error));
if (!primary) primary = error;
}
if (primary) throw primary;
console.log(
`PASS lab${lab}: ${assertions} HTTP assertions, registration race, rollback, pagination, authentication${lab >= 3 ? ", concurrent idempotency and replica sharing" : ""}; fixture cleanup completed`,
);
+288
View File
@@ -0,0 +1,288 @@
import { test, expect } from "bun:test";
import {
settings,
assertOwned,
guardedOperator,
pinnedConfigID,
assertScopedArgs,
assertNoGame,
assertPartialClaim,
assertNoRunningContainers,
withCleanup,
assertImageBudget,
} from "../scripts/k3s-model";
test("rejects an image API budget below the verified decoder limit", () => {
expect(() => assertImageBudget(4, 512, "384MiB")).toThrow();
});
test("accepts the verified image API budget", () => {
expect(() => assertImageBudget(4, 2048, "1536MiB")).not.toThrow();
});
test("allows smaller text-only API research budgets", () => {
expect(() => assertImageBudget(3, 512, "384MiB")).not.toThrow();
});
test("cleanup failure preserves the original operation error", async () => {
const primary = new Error("primary operation");
try {
await withCleanup({
perform: async () => {
throw primary;
},
cleanup: async () => {
throw new Error("cleanup");
},
});
throw new Error("unexpected success");
} catch (error) {
expect((error as Error).cause).toBe(primary);
}
});
test("cleanup failure cannot publish a successful operation", async () => {
await expect(
withCleanup({
perform: async () => 42,
cleanup: async () => {
throw new Error("cleanup");
},
}),
).rejects.toThrow("cleanup");
});
test("accepts the canonical Docker Hub form of a pinned repository", () => {
expect(
pinnedConfigID(
{
Id: "sha256:config",
RepoDigests: ["docker.io/library/postgres@sha256:manifest"],
},
"postgres:tag@sha256:manifest",
),
).toBe("sha256:config");
});
test.each([
{ name: "platform" },
{ name: "vp-lab4-medvedev" },
{ name: "../vp-lab3" },
{ name: "vp-lab3;echo" },
])("rejects foreign or malformed cluster $name", ({ name }) => {
expect(() => settings(3, { VP_CLUSTER: name })).toThrow();
});
test.each([
{ port: "0" },
{ port: "65536" },
{ port: "NaN" },
{ port: "28203;echo" },
])("rejects invalid public port $port", ({ port }) => {
expect(() => settings(3, { PUBLIC_PORT: port })).toThrow();
});
test("accepts default and isolated experiment names", () => {
expect(settings(3).cluster).toBe("vp-lab3-medvedev");
expect(settings(3, { VP_CLUSTER: "vp-lab3-r-1234abcd" }).cluster).toBe(
"vp-lab3-r-1234abcd",
);
});
const expected = { lab: 3, cluster: "vp-lab3-medvedev" };
const receipt = {
lab: 3,
cluster: expected.cluster,
container: "owned-container",
namespaceUID: "owned-namespace",
};
test("rejects an unclaimed cluster", () => {
expect(() =>
assertOwned(undefined, { container: "owned-container" }, expected),
).toThrow();
});
test("rejects a recreated foreign container", () => {
expect(() =>
assertOwned(
receipt,
{ container: "foreign-container", namespaceUID: "owned-namespace" },
expected,
),
).toThrow();
});
test("rejects a replaced namespace", () => {
expect(() =>
assertOwned(
receipt,
{ container: "owned-container", namespaceUID: "foreign-namespace" },
expected,
),
).toThrow();
});
test("accepts the exact claimed cluster and namespace", () => {
expect(() =>
assertOwned(
receipt,
{ container: "owned-container", namespaceUID: "owned-namespace" },
expected,
),
).not.toThrow();
});
test("foreign cluster never reaches the mutation port", async () => {
let dispatched = 0;
const operator = guardedOperator(expected, {
receipt: async () => receipt,
actual: async () => ({
container: "foreign-container",
namespaceUID: "owned-namespace",
}),
dispatch: async () => {
dispatched++;
},
});
await expect(operator.run("delete")).rejects.toThrow();
expect(dispatched).toBe(0);
});
test("inventory failure never reaches the mutation port", async () => {
let dispatched = 0;
const operator = guardedOperator(expected, {
receipt: async () => receipt,
actual: async () => {
throw new Error("inventory unavailable");
},
dispatch: async () => {
dispatched++;
},
});
await expect(operator.run("delete")).rejects.toThrow("inventory unavailable");
expect(dispatched).toBe(0);
});
test("claimed cluster dispatches the requested action once", async () => {
const actions: string[] = [];
const operator = guardedOperator(expected, {
receipt: async () => receipt,
actual: async () => ({
container: receipt.container,
namespaceUID: receipt.namespaceUID,
}),
dispatch: async (action) => {
actions.push(action);
},
});
await operator.run("restart");
expect(actions).toEqual(["restart"]);
});
test("accepts pinned manifest identity when image config ID differs", () => {
expect(
pinnedConfigID(
{ Id: "sha256:config", RepoDigests: ["example/image@sha256:manifest"] },
"example/image:tag@sha256:manifest",
),
).toBe("sha256:config");
});
test("rejects an unpinned image", () => {
expect(() =>
pinnedConfigID(
{ Id: "sha256:config", RepoDigests: ["example/image@sha256:other"] },
"example/image:tag@sha256:manifest",
),
).toThrow();
});
test.each([
{ args: ["get", "pods", "-nforeign"] },
{ args: ["get", "pods", "--cluster=foreign"] },
{ args: ["get", "nodes"] },
{ args: ["get", "secrets"] },
])("rejects target or resource override $args", ({ args }) => {
expect(() => assertScopedArgs(args)).toThrow();
});
test("allows flags belonging to the executed application", () => {
expect(() =>
assertScopedArgs([
"exec",
"deployment/postgres",
"--",
"psql",
"--user",
"messenger",
]),
).not.toThrow();
});
test("allows stdin for scoped PostgreSQL execution", () => {
expect(() =>
assertScopedArgs(["exec", "-i", "deployment/postgres", "--", "psql"]),
).not.toThrow();
});
test("rejects a second resource that discloses a Secret", () => {
expect(() =>
assertScopedArgs([
"get",
"pods/existing-api",
"secrets/app-config",
"-o",
"json",
]),
).toThrow();
});
test("rejects the short server override", () => {
expect(() =>
assertScopedArgs(["get", "pods", "-shttps://foreign"]),
).toThrow();
});
test.each([{ code: 0 }, { code: 2 }, { code: -1 }])(
"refuses measurement for active or unknown game status $code",
({ code }) => {
expect(() => assertNoGame(code)).toThrow();
},
);
test("accepts measurement only for confirmed inactive game", () => {
expect(() => assertNoGame(1)).not.toThrow();
});
test("rejects extra resources after delimiter outside exec", () => {
expect(() =>
assertScopedArgs([
"get",
"pods/existing",
"-o",
"json",
"--",
"secrets/app-config",
]),
).toThrow();
});
test("partial cleanup accepts only the exclusive server owner nonce", () => {
expect(() =>
assertPartialClaim(
{ ...receipt, state: "claimed", nonce: "ours" },
{ container: receipt.container, owner: "foreign" },
expected,
),
).toThrow();
});
test("partial cleanup never weakens a ready namespace guard", () => {
expect(() =>
assertPartialClaim(
{ ...receipt, state: "ready", nonce: "ours" },
{ container: receipt.container, owner: "ours" },
expected,
),
).toThrow();
});
test("partial cleanup accepts an owned server before namespace creation", () => {
expect(() =>
assertPartialClaim(
{ lab: 3, cluster: expected.cluster, state: "claimed", nonce: "ours" },
{ container: "fresh-server", owner: "ours" },
expected,
),
).not.toThrow();
});
test("rejects a running replacement process despite stale Kubernetes status", () => {
expect(() =>
assertNoRunningContainers(
[{ id: "new-process", labels: { "io.kubernetes.pod.uid": "victim" } }],
"victim",
),
).toThrow();
});
test("accepts native absence of the victim process", () => {
expect(() =>
assertNoRunningContainers(
[{ id: "survivor", labels: { "io.kubernetes.pod.uid": "other" } }],
"victim",
),
).not.toThrow();
});
+32
View File
@@ -0,0 +1,32 @@
import { resolve } from "node:path";
const root = resolve(import.meta.dir, "..");
const p = Bun.spawn(
[
resolve(root, "scripts/kube.sh"),
"exec",
"-i",
"deployment/postgres",
"--",
"psql",
"-X",
"-qAt",
"-U",
"messenger",
"-d",
"messenger",
"-v",
"ON_ERROR_STOP=1",
],
{ cwd: root, stdin: "pipe", stdout: "pipe", stderr: "pipe" },
);
p.stdin.write("SELECT 'stdin-boundary-ok';\n");
p.stdin.end();
const [out, err] = await Promise.all([
new Response(p.stdout).text(),
new Response(p.stderr).text(),
]);
if ((await p.exited) !== 0 || out.trim() !== "stdin-boundary-ok")
throw new Error("Kubernetes wrapper did not execute the stdin query");
console.log(
"PASS: SQL stdin reaches PostgreSQL through the real scoped wrapper",
);
+74
View File
@@ -0,0 +1,74 @@
"""Plot measured coursework results; this is data analysis, not application code."""
import argparse
import json
from pathlib import Path
from statistics import mean
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser()
parser.add_argument('summary', type=Path)
parser.add_argument('--pool-summary', type=Path)
args = parser.parse_args()
data = json.loads(args.summary.read_text())
if data.get('complete') is not True:
raise SystemExit('Only a completed, cleaned-up run can be plotted')
plt.rcParams.update({'svg.fonttype': 'none', 'font.size': 10})
if 'dataset' in data:
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5), constrained_layout=True)
modes = ['chat_only', 'history']
for axis, key, title in zip(axes, ['read', 'write'], ['Deep history page (51 rows)', 'Insert 1,000 messages']):
values = [data['plans'][mode][key]['Execution Time'] for mode in modes]
axis.bar(['chat_id', 'chat_id + time + id'], values, color=['#6b7280', '#2563eb'])
axis.set_ylabel('Execution time, ms')
axis.set_title(title)
if key == 'read':
axis.set_yscale('log')
for index, value in enumerate(values):
axis.annotate(f'{value:.3f}', (index, value), xytext=(0, 4), textcoords='offset points', ha='center')
fig.suptitle('100,000 skewed messages; one EXPLAIN ANALYZE per index')
fig.savefig(args.summary.parent / 'comparison.svg')
plt.close(fig)
else:
if data.get('valid') is not True:
raise SystemExit('Invalid measurements')
rows = data['samples']
fig, axes = plt.subplots(1, 2, figsize=(10, 3.8), constrained_layout=True)
for phase, label, color in [('fixed', 'Fixed total API CPU/RAM', '#2563eb'), ('growing', 'Resources grow with replicas', '#c2410c')]:
groups = [[r for r in rows if r['phase'] == phase and r['replicas'] == count] for count in [1, 2, 4]]
if not all(groups):
continue
for axis, metric in zip(axes, ['rps', 'p95']):
values = [[r['metrics']['successful_rps'] if metric == 'rps' else r['metrics']['successful_latency_ms']['p95'] for r in group] for group in groups]
centers = [mean(value) for value in values]
errors = [[center - min(value) for center, value in zip(centers, values)], [max(value) - center for center, value in zip(centers, values)]]
axis.errorbar([1, 2, 4], centers, yerr=errors, marker='o', capsize=4, label=label, color=color)
for axis, title in zip(axes, ['Successful requests / second', 'p95 of successful requests, ms']):
axis.set_title(title)
axis.set_xlabel('API replicas')
axis.set_xticks([1, 2, 4])
axis.grid(alpha=.2)
axis.legend(fontsize=8)
fig.suptitle('Closed loop, concurrency 16, 5 seconds; mean and range of two runs')
fig.savefig(args.summary.parent / 'scaling.svg')
plt.close(fig)
pool_data = json.loads(args.pool_summary.read_text()) if args.pool_summary else data
if pool_data.get('complete') is not True:
raise SystemExit('Incomplete pool experiment')
pools = [[r for r in pool_data['samples'] if r['phase'] == 'pool' and r['pool'] == size] for size in [8, 1]]
fig, axes = plt.subplots(1, 2, figsize=(8, 3.5), constrained_layout=True)
for axis, metric in zip(axes, ['rps', 'p95']):
values = [[r['metrics']['successful_rps'] if metric == 'rps' else r['metrics']['successful_latency_ms']['p95'] for r in group] for group in pools]
centers = [mean(value) for value in values]
axis.bar(['pool = 8', 'pool = 1'], centers, color=['#6b7280', '#2563eb'])
axis.set_ylabel('Successful req/s' if metric == 'rps' else 'p95, ms')
axis.set_ylim(bottom=0)
for index, center in enumerate(centers):
axis.annotate(f'{center:.2f}', (index, center), xytext=(0, 4), textcoords='offset points', ha='center')
fig.suptitle('One hot sender; same single-replica CPU/RAM budget')
fig.savefig(args.summary.parent / 'pool.svg')
plt.close(fig)
print('Saved standalone SVG research figures')
+1
View File
@@ -0,0 +1 @@
matplotlib==3.11.2
+104
View File
@@ -0,0 +1,104 @@
import {resolve} from 'node:path';
import {mkdir,mkdtemp,writeFile} from 'node:fs/promises';
const root=resolve(import.meta.dir,'..');
if(process.argv.includes('--check')){console.log('Research script parsed without accessing the stand');process.exit(0);}
const nonce=crypto.randomUUID().slice(0,8),project='vp-lab3-research-'+nonce;
const parent=resolve(root,'evidence/research');await mkdir(parent,{recursive:true});
const evidence=await mkdtemp(resolve(parent,'run-'));
await writeFile(resolve(evidence,'run.json'),JSON.stringify({run_id:nonce,started_at:new Date().toISOString(),state:'started',project})+'\n',{flag:'wx'});
let stage='preflight',created=false,primary:unknown;
let rolling:Promise<{ok:boolean}>|undefined;let rollingFinished=false;
const cleanupErrors:string[]=[];
let configuration:Record<string,string>={PUBLIC_PORT:'28303',BASE_URL:'http://127.0.0.1:28303',SESSION_TTL_SECONDS:'3600'};
const base='http://127.0.0.1:28303';
async function command(args:string[],input?:string){
const p=Bun.spawn(args,{cwd:root,env:{...process.env,...configuration},stdin:input===undefined?'ignore':'pipe',stdout:'pipe',stderr:'pipe',signal:AbortSignal.timeout(120000)});
if(input!==undefined){p.stdin.write(input);p.stdin.end();}
const [out,err]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text()]);
if(await p.exited!==0)throw new Error(stage+': command failed ('+args[0]+')');
return out;
}
async function guard(){const p=Bun.spawn(['/home/rey/.local/bin/game-running'],{stdout:'ignore',stderr:'pipe'});await new Response(p.stderr).text();if(await p.exited!==1)throw new Error('Research requires an inactive game');}
function compose(args:string[],input?:string){return command(['docker','compose','-f',resolve(root,'compose.yaml'),'-p',project,...args],input);}
async function sql(query:string){return compose(['exec','-T','postgres','psql','-X','-qAt','-U','messenger','-d','messenger','-v','ON_ERROR_STOP=1'],query);}
const samples:any[]=[];
const poolOnly=process.argv.includes('--pool-only');
let rollingMetric:unknown;
try{
await guard();
if((await command(['ss','-H','-ltn','sport = :28303'])).trim())throw new Error('Research port is occupied');
stage='create_isolated_stand';created=true;
await compose(['up','-d','--wait','postgres','valkey']);
await compose(['run','--rm','migrate']);
const hardware=JSON.parse(await command(['lscpu','-J']));
await writeFile(resolve(evidence,'hardware.json'),JSON.stringify(hardware.lscpu.filter((x:any)=>/Model name|CPU\(s\)|Thread|Core\(s\)/.test(x.field)),null,2)+'\n');
const cases:any[]=[];
if(!poolOnly)for(const phase of ['fixed','growing'])for(const replicas of [1,2,4])for(const repeat of [1,2])cases.push({phase,replicas,repeat,pool:8});
// Pool experiment keeps the single-replica CPU/RAM budget identical.
for(const [index,pool] of [8,1,1,8].entries())cases.push({phase:'pool',replicas:1,repeat:index+1,pool});
for(const test of cases){
await guard();stage=`configure_${test.phase}_${test.replicas}_${test.repeat}_${test.pool}`;
await compose(['stop','api']);
await sql('TRUNCATE idempotency,messages,chat_members,chats,sessions,users;');
const fixed=test.phase!=='growing';
const memory=fixed?2048/test.replicas:512;
configuration={...configuration,API_REPLICAS:String(test.replicas),API_CPUS:String(fixed?2/test.replicas:1),API_MEMORY:memory+'m',GO_MEMORY_LIMIT:Math.floor(memory*.75)+'MiB',PG_MAX_CONNS:String(test.pool)};
await compose(['up','-d','--no-build','--scale','api='+test.replicas,'api','lb']);
await command([process.execPath,'--no-env-file','student-tests/wait.ts'].map(String));
const actual=await (await fetch(base+'/debug/stats')).json() as any;
if(actual.store?.pool_max!==test.pool)throw new Error('Running image did not apply the requested pool size');
const replicaIDs=(await compose(['ps','-q','api'])).trim().split(/\s+/);
if(replicaIDs.length!==test.replicas)throw new Error('Actual replica count differs');
for(const id of replicaIDs){const [cpuBytes,memoryBytes]=(await command(['docker','inspect','--format','{{.HostConfig.NanoCpus}} {{.HostConfig.Memory}}',id])).trim().split(/\s+/).map(Number);if(cpuBytes!==Number(configuration.API_CPUS)*1e9||memoryBytes!==memory*1024*1024)throw new Error('Actual API resource limits differ');}
// The wait helper needs this stand's endpoint explicitly.
stage='measure_'+test.phase;
const name=[test.phase,test.replicas,test.pool,test.repeat].join('-');
const output=resolve(evidence,name+'.json');
const ids=(await compose(['ps','-q','api','lb','postgres','valkey'])).trim().split(/\s+/);
const load=command(['python3','tests/load.py','--base-url',base,'--duration','5','--concurrency','16','--output',output]);
const snapshot=(async()=>{await Bun.sleep(2000);const text=await command(['docker','stats','--no-stream','--format','{{json .}}',...ids]);return text.trim().split('\n').filter(Boolean).map(line=>{const x=JSON.parse(line);return {name:x.Name,cpu_percent:x.CPUPerc,memory:x.MemUsage};});})();
const waits=(async()=>{await Bun.sleep(1000);const out=[];for(let i=0;i<10;i++){out.push(JSON.parse((await sql("SELECT coalesce(json_agg(t),'[]'::json) FROM (SELECT wait_event_type,wait_event,count(*) FROM pg_stat_activity WHERE datname=current_database() AND state='active' AND pid<>pg_backend_pid() GROUP BY wait_event_type,wait_event) t; ")).trim()));await Bun.sleep(200);}return out;})();
const measured=await Promise.allSettled([load,snapshot,waits]);
for(const result of measured)if(result.status==='rejected')throw result.reason;
const stats=(measured[1] as PromiseFulfilledResult<any>).value;
const postgresWaits=(measured[2] as PromiseFulfilledResult<any>).value;
await guard();
const metric=await Bun.file(output).json();
const count=Number((await sql('SELECT count(*) FROM messages;')).trim());
samples.push({...test,api_cpu_each:Number(configuration.API_CPUS),api_memory_mb_each:memory,metrics:metric,snapshot:stats,postgres_wait_samples:postgresWaits,messages:count});
await writeFile(resolve(evidence,'summary.json'),JSON.stringify({valid:true,complete:false,expected_samples:cases.length,profile:'closed-loop POST text, concurrency16,5seconds,2repetitions; fresh DB data for each run',samples},null,2)+'\n');
}
if(!poolOnly){
stage='rolling_update';
await compose(['stop','api']);await sql('TRUNCATE idempotency,messages,chat_members,chats,sessions,users;');
configuration={...configuration,API_REPLICAS:'2',API_CPUS:'1',API_MEMORY:'512m',GO_MEMORY_LIMIT:'384MiB',PG_MAX_CONNS:'8'};
await compose(['up','-d','--no-build','--scale','api=2','api','lb']);
await command([process.execPath,'--no-env-file','student-tests/wait.ts']);
const ids=(await compose(['ps','-q','api'])).trim().split(/\s+/);
rolling=command(['python3','tests/load.py','--base-url',base,'--duration','30','--concurrency','8','--output',resolve(evidence,'rolling.json')]).then(()=>({ok:true}),()=>({ok:false})).finally(()=>{rollingFinished=true;});
for(let attempt=0;attempt<100;attempt++){if(Number((await sql('SELECT count(*) FROM messages;')).trim())>10)break;await Bun.sleep(100);if(attempt===99)throw new Error('Rolling workload did not start');}
const replacements=[];
for(const id of ids){
if(rollingFinished)throw new Error('Workload ended before both replacements');
const before=Number((await sql('SELECT count(*) FROM messages;')).trim());
if((await command(['docker','inspect','--format','{{index .Config.Labels "com.docker.compose.project"}}',id])).trim()!==project)throw new Error('Replica ownership guard failed');
await command(['docker','stop','--time','8',id]);
await command(['docker','container','rm',id]);
await compose(['up','-d','--no-build','--no-deps','--scale','api=2','api']);
await command([process.execPath,'--no-env-file','student-tests/wait.ts']);
const after=Number((await sql('SELECT count(*) FROM messages;')).trim());
if(rollingFinished||after<=before)throw new Error('Replacement was not covered by successful writes');
replacements.push({old_container:id.slice(0,12),messages_before:before,messages_after:after});
}
if(!(await rolling).ok)throw new Error('Rolling load failed');await guard();
await writeFile(resolve(evidence,'replacements.json'),JSON.stringify(replacements,null,2)+'\n');
rollingMetric=await Bun.file(resolve(evidence,'rolling.json')).json();
}
}catch(error){primary=error;}
finally{
if(rolling)await rolling;
if(created)try{await compose(['down','--volumes']);}catch{cleanupErrors.push('isolated_stand');}
}
if(primary||cleanupErrors.length){await writeFile(resolve(evidence,'failure.json'),JSON.stringify({run_id:nonce,stage,primary:primary instanceof Error?primary.name:primary?'unknown':null,cleanup_errors:cleanupErrors})+'\n');throw new Error('Research failed; inspect this run failure summary');}
await writeFile(resolve(evidence,'summary.json'),JSON.stringify({run_id:nonce,valid:true,complete:true,expected_samples:poolOnly?4:16,profile:'closed-loop POST text, concurrency16,5seconds,2repetitions; fresh DB data for each run',samples,rolling:rollingMetric},null,2)+'\n');
console.log('PASS lab3 research: '+evidence);
+374
View File
@@ -0,0 +1,374 @@
import { resolve } from "node:path";
import { mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { assertNoGame } from "../scripts/k3s-model";
const root = resolve(import.meta.dir, "..");
if (process.argv.includes("--check")) {
console.log("Parsed isolated k3s/Pingap research");
process.exit(0);
}
const cluster =
"vp-lab3-r-" + crypto.randomUUID().replaceAll("-", "").slice(0, 8);
const base = "http://127.0.0.1:28303";
let env = {
...process.env,
VP_RUNTIME: "k3s",
VP_CLUSTER: cluster,
PUBLIC_PORT: "28303",
BASE_URL: base,
API_REPLICAS: "2",
API_CPUS: "1",
API_MEMORY: "512Mi",
GO_MEMORY_LIMIT: "400MiB",
PG_MAX_CONNS: "8",
};
const parent = resolve(root, "evidence/k3s/research");
await mkdir(parent, { recursive: true });
const evidence = await mkdtemp(resolve(parent, "run-"));
await writeFile(
resolve(evidence, "run.json"),
JSON.stringify({
cluster,
started_at: new Date().toISOString(),
state: "started",
}) + "\n",
{ flag: "wx" },
);
let stage = "preflight",
failureStage: string | undefined,
created = false,
primary: unknown;
const cleanupErrors: string[] = [];
let rolling: Promise<void> | undefined,
finished = false;
async function command(label: string, args: string[], input?: string) {
stage = label;
const p = Bun.spawn(args, {
cwd: root,
env,
stdin: input === undefined ? "ignore" : "pipe",
stdout: "pipe",
stderr: "pipe",
signal: AbortSignal.timeout(360000),
});
if (input !== undefined) {
p.stdin.write(input);
p.stdin.end();
}
const [out, err] = await Promise.all([
new Response(p.stdout).text(),
new Response(p.stderr).text(),
]);
if ((await p.exited) !== 0) {
await writeFile(resolve(root, ".local/research-error.txt"), out + err, {
mode: 0o600,
});
throw new Error(label + " failed");
}
return out;
}
function stand(args: string[]) {
return command("stand_" + args[0], [
process.execPath,
"--no-env-file",
"scripts/k3s.ts",
...args,
]);
}
function kube(args: string[], input?: string) {
return command(
"kubernetes_" + args[0],
[resolve(root, "scripts/kube.sh"), ...args],
input,
);
}
function sql(query: string) {
return kube(
[
"exec",
"-i",
"deployment/postgres",
"--",
"psql",
"-X",
"-qAt",
"-U",
"messenger",
"-d",
"messenger",
"-v",
"ON_ERROR_STOP=1",
],
query,
);
}
async function guard() {
const p = Bun.spawn(["game-running"], { stdout: "ignore", stderr: "pipe" });
await new Response(p.stderr).text();
assertNoGame(await p.exited);
}
const samples: any[] = [];
let rollingMetric: unknown;
const poolOnly = process.argv.includes("--pool-only");
try {
await guard();
created = true;
await stand(["up"]);
const hardware = JSON.parse(await command("hardware", ["lscpu", "-J"]));
await writeFile(
resolve(evidence, "hardware.json"),
JSON.stringify(
hardware.lscpu.filter((x: any) =>
/Model name|CPU\(s\)|Thread|Core\(s\)/.test(x.field),
),
null,
2,
) + "\n",
);
const cases: any[] = [];
if (!poolOnly)
for (const phase of ["fixed", "growing"])
for (const replicas of [1, 2, 4])
for (const repeat of [1, 2])
cases.push({ phase, replicas, repeat, pool: 8 });
for (const [index, pool] of [8, 1, 1, 8].entries())
cases.push({ phase: "pool", replicas: 1, repeat: index + 1, pool });
let previous = "";
for (const test of cases) {
await guard();
const fixed = test.phase !== "growing",
memory = fixed ? 2048 / test.replicas : 512,
cpu = fixed ? 2 / test.replicas : 1;
env = {
...env,
API_REPLICAS: String(test.replicas),
API_CPUS: String(cpu),
API_MEMORY: memory + "Mi",
GO_MEMORY_LIMIT: Math.floor(memory * 0.75) + "MiB",
PG_MAX_CONNS: String(test.pool),
};
const configuration = [test.replicas, cpu, memory, test.pool].join("-");
if (configuration !== previous) {
await stand(["configure"]);
previous = configuration;
}
// This cluster is exclusively owned by this experiment; no external clients are running.
await sql(
"TRUNCATE idempotency,messages,chat_members,chats,sessions,users;",
);
const before = JSON.parse(await stand(["stats"]));
const cpuValue = (s: string) =>
s.endsWith("m") ? Number(s.slice(0, -1)) / 1000 : Number(s);
const memoryValue = (s: string) =>
s.endsWith("Gi")
? Number(s.slice(0, -2)) * 1024
: Number(s.replace(/Mi$/, ""));
if (
before.pods.length !== test.replicas ||
before.pods.some(
(p: any) =>
cpuValue(p.limits.cpu) !== cpu ||
memoryValue(p.limits.memory) !== memory,
)
)
throw new Error("Actual API count or resource budget differs");
const response = await fetch(base + "/debug/stats", {
signal: AbortSignal.timeout(3000),
});
const actual = (await response.json()) as any;
if (response.status !== 200 || actual.store?.pool_max !== test.pool)
throw new Error("Actual SQL pool differs");
const name = [test.phase, test.replicas, test.pool, test.repeat].join("-"),
output = resolve(evidence, name + ".json");
const load = command("load_" + name, [
"python3",
"tests/load.py",
"--base-url",
base,
"--duration",
"5",
"--concurrency",
"16",
"--output",
output,
]);
const snapshot = (async () => {
await Bun.sleep(2000);
return JSON.parse(await stand(["stats"]));
})();
const waits = (async () => {
await Bun.sleep(1000);
const query =
"SELECT json_build_object('at',clock_timestamp(),'events',coalesce((SELECT json_agg(t) FROM (SELECT wait_event_type,wait_event,count(*) FROM pg_stat_activity WHERE datname=current_database() AND state='active' AND pid<>pg_backend_pid() GROUP BY wait_event_type,wait_event) t),'[]'::json))::jsonb::text;";
const text = await sql(
Array.from(
{ length: 10 },
() => query + "\nSELECT pg_sleep(0.2);",
).join("\n"),
);
return text
.split("\n")
.filter((x) => x.startsWith("{"))
.map((x) => JSON.parse(x));
})();
const results = await Promise.allSettled([load, snapshot, waits]);
for (const r of results) if (r.status === "rejected") throw r.reason;
await guard();
const metric = await Bun.file(output).json();
const snapshotValue = (results[1] as PromiseFulfilledResult<any>).value;
const messageCount = Number(
(await sql("SELECT count(*) FROM messages;")).trim(),
);
if (
!Number.isFinite(metric.successful_rps) ||
metric.successful_rps <= 0 ||
!Number.isFinite(metric.successful_latency_ms?.p95) ||
!Number.isInteger(messageCount) ||
messageCount < 1
)
throw new Error("No valid successful workload or persisted messages");
if (
snapshotValue.pods.length !== before.pods.length ||
snapshotValue.pods.some(
(p: any) => !before.pods.some((b: any) => b.uid === p.uid),
)
)
throw new Error("API pods changed during measurement");
samples.push({
...test,
api_cpu_each: cpu,
api_memory_mb_each: memory,
metrics: metric,
snapshot: snapshotValue,
postgres_wait_samples: (results[2] as PromiseFulfilledResult<any>).value,
messages: messageCount,
});
}
if (!poolOnly) {
env = {
...env,
API_REPLICAS: "2",
API_CPUS: "1",
API_MEMORY: "512Mi",
GO_MEMORY_LIMIT: "384MiB",
PG_MAX_CONNS: "8",
};
await stand(["configure"]);
await sql(
"TRUNCATE idempotency,messages,chat_members,chats,sessions,users;",
);
const before = JSON.parse(
await kube(["get", "pods", "-l", "app=api", "-o", "json"]),
).items.map((p: any) => ({ name: p.metadata.name, uid: p.metadata.uid }));
let loadFailure: unknown;
rolling = command("rolling_load", [
"python3",
"tests/load.py",
"--base-url",
base,
"--duration",
"30",
"--concurrency",
"8",
"--output",
resolve(evidence, "rolling.json"),
])
.then(
() => {},
(error) => {
loadFailure = error;
},
)
.finally(() => {
finished = true;
});
for (let i = 0; i < 60; i++) {
if (Number((await sql("SELECT count(*) FROM messages;")).trim()) > 10)
break;
if (finished) throw new Error("Rolling load ended before starting");
await Bun.sleep(100);
}
const countBefore = Number(
(await sql("SELECT count(*) FROM messages;")).trim(),
);
if (countBefore <= 10) throw new Error("Rolling load did not start");
await kube(["rollout", "restart", "deployment/api"]);
await stand(["ready"]);
const after = JSON.parse(
await kube(["get", "pods", "-l", "app=api", "-o", "json"]),
).items.map((p: any) => ({ name: p.metadata.name, uid: p.metadata.uid }));
const countAfter = Number(
(await sql("SELECT count(*) FROM messages;")).trim(),
);
if (
finished ||
countAfter <= countBefore ||
after.length !== 2 ||
after.some((p: any) => before.some((b: any) => b.uid === p.uid))
)
throw new Error("Rolling replacements not covered by continuing writes");
await writeFile(
resolve(evidence, "replacements.json"),
JSON.stringify(
{
before,
after,
messages_before: countBefore,
messages_after: countAfter,
strategy: { maxSurge: 1, maxUnavailable: 0 },
},
null,
2,
) + "\n",
);
await rolling;
if (loadFailure) throw loadFailure;
await guard();
rollingMetric = await Bun.file(resolve(evidence, "rolling.json")).json();
}
} catch (error) {
primary = error;
failureStage = stage;
} finally {
if (rolling) await rolling;
if (created)
try {
await stand(["destroy"]);
} catch {
cleanupErrors.push("isolated_cluster");
}
}
if (primary || cleanupErrors.length) {
await writeFile(
resolve(evidence, "failure.json"),
JSON.stringify({
stage: failureStage ?? stage,
primary:
primary instanceof Error ? primary.message : primary ? "unknown" : null,
cleanup_errors: cleanupErrors,
}) + "\n",
);
throw new Error("Research failed; inspect this run");
}
await writeFile(
resolve(evidence, "summary.json"),
JSON.stringify(
{
valid: true,
complete: true,
cluster,
runtime: "k3s1.37.1/Pingap0.16.0",
expected_samples: casesLength(),
profile:
"closed-loop POST text; concurrency16;5seconds;two repetitions;fresh data;single hot sender",
samples,
rolling: rollingMetric,
},
null,
2,
) + "\n",
{ flag: "wx" },
);
function casesLength() {
return poolOnly ? 4 : 16;
}
console.log("PASS k3s/Pingap research: " + evidence);
+22
View File
@@ -0,0 +1,22 @@
import { resolve } from "node:path";
const root = resolve(import.meta.dir, "..");
const before = await Bun.file(
resolve(root, "evidence/k3s/restart-before.json"),
).json();
const after = await Bun.file(
resolve(root, "evidence/k3s/restart-after.json"),
).json();
if (
!before.run_id ||
before.run_id !== after.run_id ||
!Array.isArray(before.pods) ||
!before.pods.length ||
!Array.isArray(after.pods) ||
!after.pods.length
)
throw new Error("Incomplete or mismatched restart evidence");
if (after.pods.some((p: any) => before.pods.some((b: any) => b.uid === p.uid)))
throw new Error(
"Restart returned while an original workload Pod UID still existed",
);
console.log("PASS: every recorded original workload Pod UID was replaced");
+14
View File
@@ -0,0 +1,14 @@
import {resolve} from 'node:path';
const root=resolve(import.meta.dir,'..');
const lab=(await Bun.file(resolve(root,'lab.json')).json()).number;
const base=process.env.BASE_URL??`http://127.0.0.1:${28200+lab}`;
const needed=lab>=3?Number(process.env.API_REPLICAS??2):1;
const instances=new Set<string>();
for(let attempt=0;attempt<600;attempt++){
try{
const r=await fetch(base+'/health/ready',{signal:AbortSignal.timeout(1000)});await r.arrayBuffer();
if(r.status===200){instances.add(r.headers.get('X-Instance-Id')??'single');if(instances.size>=needed){console.log(`Ready: ${instances.size} API process(es)`);process.exit(0);}}
}catch{}
await Bun.sleep(150);
}
throw new Error('Stand readiness deadline expired');