Prepare verified laboratory 4 implementation and evidence

This commit is contained in:
rey
2026-11-17 17:31:17 +03:00
parent ec540a1a72
commit 4fc1f40099
172 changed files with 15646 additions and 38 deletions
+656
View File
@@ -0,0 +1,656 @@
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:28204";
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() {
const p = Bun.spawn(
kubernetes
? [
process.execPath,
"--no-env-file",
resolve(root, "scripts/k3s.ts"),
"task",
"fixture-cleanup",
prefix,
]
: [
resolve(root, "scripts/compose.sh"),
"run",
"--rm",
"--no-deps",
"fixture-cleanup",
prefix,
],
{ cwd: root, stdout: "pipe", stderr: "pipe" },
);
await Promise.all([
new Response(p.stdout).text(),
new Response(p.stderr).text(),
]);
if ((await p.exited) !== 0)
throw new Error("Fixture object/metadata cleanup failed");
}
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",
);
}
if (lab >= 4) {
const png = new Uint8Array(
await Bun.file(resolve(root, "tests/fixtures/sample.png")).arrayBuffer(),
);
async function upload(
bytes: Uint8Array,
name: string,
mime: string,
status: number,
token = alice.token,
) {
operation = "upload " + mime + " expecting " + status;
const r = await fetch(
base +
"/api/v1/chats/" +
chat.id +
"/attachments?filename=" +
encodeURIComponent(name),
{
method: "POST",
headers: { Authorization: "Bearer " + token, "Content-Type": mime },
body: bytes,
signal: AbortSignal.timeout(25000),
},
);
const json = (await r.json()) as any;
check(
r.status === status,
`upload ${mime}: expected ${status}, got ${r.status}`,
);
return json;
}
const att = await upload(png, "оригинал.png", "image/png", 201);
const sha = new Bun.CryptoHasher("sha256").update(png).digest("hex");
check(
att.sha256 === sha &&
att.size_bytes === png.length &&
att.status === "ready",
"Original metadata must match actual bytes",
);
const downloaded = await call(
"GET",
"/api/v1/attachments/" + att.id + "/content",
200,
bob.token,
);
check(
Buffer.from(downloaded.bytes).equals(Buffer.from(png)),
"Original download must be byte-exact",
);
check(
downloaded.response.headers.get("Content-Type") === "image/png",
"Original MIME",
);
for (const suffix of ["", "/content"])
await call(
"GET",
"/api/v1/attachments/" + att.id + suffix,
404,
eve.token,
);
const linked = (
await call(
"POST",
path,
201,
bob.token,
{ text: "", attachment_ids: [att.id] },
{ "Idempotency-Key": crypto.randomUUID() },
)
).json;
check(
linked.attachment_ids.length === 1 && linked.attachment_ids[0] === att.id,
"Message must retain attachment IDs",
);
await call(
"POST",
"/api/v1/chats/" + other.id + "/messages",
404,
alice.token,
{ text: "", attachment_ids: [att.id] },
{ "Idempotency-Key": crypto.randomUUID() },
);
await call(
"POST",
path,
400,
alice.token,
{ text: "", attachment_ids: [att.id, att.id] },
{ "Idempotency-Key": crypto.randomUUID() },
);
for (const body of [
{ attachment_ids: [att.id] },
{ text: null, attachment_ids: [att.id] },
{ text: "text", attachment_ids: null },
])
await call("POST", path, 400, alice.token, body, {
"Idempotency-Key": crypto.randomUUID(),
});
const semanticKey = crypto.randomUUID();
const absent = (
await call(
"POST",
path,
201,
alice.token,
{ text: "семантический повтор" },
{ "Idempotency-Key": semanticKey },
)
).json;
const empty = (
await call(
"POST",
path,
201,
alice.token,
{ attachment_ids: [], text: "семантический повтор" },
{ "Idempotency-Key": semanticKey },
)
).json;
check(
JSON.stringify(absent) === JSON.stringify(empty),
"Omitted attachments and empty array must be semantically equal",
);
await upload(png, "a.png", "image/jpeg", 415);
await upload(png.slice(0, 20), "a.png", "image/png", 415);
await upload(png, "../a.png", "image/png", 400);
await upload(png, "a.png", "image/png", 404, eve.token);
await upload(
new Uint8Array(10 * 1024 * 1024 + 1),
"huge.png",
"image/png",
413,
);
const anon = Bun.spawn(
[
...(kubernetes
? [resolve(root, "scripts/kube.sh"), "exec", "deployment/s3", "--"]
: [resolve(root, "scripts/compose.sh"), "exec", "-T", "s3"]),
"curl",
"--silent",
"--show-error",
"-o",
"/dev/null",
"-w",
"%{http_code}",
"http://127.0.0.1:9000/messenger/originals/" + att.id,
],
{ cwd: root, stdout: "pipe", stderr: "pipe" },
);
const anonCode = await new Response(anon.stdout).text();
await new Response(anon.stderr).text();
check(
(await anon.exited) === 0 && anonCode === "403",
"Bucket must deny unauthenticated direct object GET",
);
if (process.env.FAIL_S3 === "1") {
async function storageAction(action: string) {
const p = Bun.spawn(
kubernetes
? [
resolve(root, "scripts/kube.sh"),
"scale",
"deployment/s3",
"--replicas=" + (action === "stop" ? "0" : "1"),
]
: [resolve(root, "scripts/compose.sh"), action, "s3"],
{
cwd: root,
stdout: "pipe",
stderr: "pipe",
signal: AbortSignal.timeout(30000),
},
);
await Promise.all([
new Response(p.stdout).text(),
new Response(p.stderr).text(),
]);
check((await p.exited) === 0, "S3 lifecycle action failed");
if (kubernetes && action === "stop") {
const wait = Bun.spawn(
[
resolve(root, "scripts/kube.sh"),
"wait",
"--for=delete",
"pod",
"-l",
"app=s3",
"--timeout=25s",
],
{ cwd: root, stdout: "pipe", stderr: "pipe" },
);
await Promise.all([
new Response(wait.stdout).text(),
new Response(wait.stderr).text(),
]);
check((await wait.exited) === 0, "S3 pod did not stop");
}
}
try {
await storageAction("stop");
operation = "upload with S3 stopped";
const outageStarted = performance.now();
const unavailable = await fetch(
base +
"/api/v1/chats/" +
chat.id +
"/attachments?filename=unavailable.png",
{
method: "POST",
headers: {
Authorization: "Bearer " + alice.token,
"Content-Type": "image/png",
},
body: png,
// Upload has a 20-second server context; Kubernetes without S3
// endpoints can exhaust SDK retries instead of refusing immediately.
signal: AbortSignal.timeout(25000),
},
);
await unavailable.arrayBuffer();
check(
[502, 503].includes(unavailable.status),
"Unavailable S3 must produce a bounded failure",
);
console.log(
"S3 outage: HTTP " +
unavailable.status +
"; elapsed_ms=" +
Math.round(performance.now() - outageStarted),
);
} finally {
await storageAction("start");
const wait = Bun.spawn(
[process.execPath, "--no-env-file", "student-tests/wait.ts"],
{
cwd: root,
env: { ...process.env, BASE_URL: base },
stdout: "pipe",
stderr: "pipe",
},
);
await Promise.all([
new Response(wait.stdout).text(),
new Response(wait.stderr).text(),
]);
check(
(await wait.exited) === 0,
"S3 restart did not restore readiness",
);
}
const restored = await call(
"GET",
"/api/v1/attachments/" + att.id + "/content",
200,
bob.token,
);
check(
Buffer.from(restored.bytes).equals(Buffer.from(png)),
"S3 outage lost an acknowledged original",
);
}
}
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`,
);
@@ -0,0 +1,61 @@
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('Concurrent image experiment parsed without accessing the stand');process.exit(0);}
const base=process.env.BASE_URL??'http://127.0.0.1:28204';
const prefix='st_'+crypto.randomUUID().replaceAll('-','').slice(0,16);
async function command(args:string[]){const p=Bun.spawn(args,{cwd:root,stdout:'pipe',stderr:'pipe',signal:AbortSignal.timeout(60000)});const [out,err]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text()]);if(await p.exited!==0)throw new Error('Image experiment command failed');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('Close the game before the memory experiment');}
async function json(method:string,path:string,status:number,token?:string,body?:unknown,headers:Record<string,string>={}){const r=await fetch(base+path,{method,headers:{...headers,...(token?{Authorization:'Bearer '+token}:{}),...(body!==undefined?{'Content-Type':'application/json'}:{})},body:body===undefined?undefined:JSON.stringify(body),signal:AbortSignal.timeout(30000)});const out=await r.json() as any;if(r.status!==status)throw new Error('Image experiment HTTP status differs');return out;}
const parent=resolve(root,'evidence/concurrent-images');await mkdir(parent,{recursive:true});
const evidence=await mkdtemp(resolve(parent,'run-'));
await writeFile(resolve(evidence,'run.json'),JSON.stringify({run_id:prefix,started_at:new Date().toISOString(),state:'started'})+'\n',{flag:'wx'});
let finished=false,touched=false,primary:unknown,monitorError:unknown,result:unknown;
let monitor:Promise<void>|undefined;const cleanupErrors:string[]=[];const samples:any[]=[];
try{
await guard();
const published=(await command([resolve(root,'scripts/compose.sh'),'port','lb','8080'])).trim();
if(new URL(base).origin!=='http://'+published)throw new Error('API URL differs from the pinned coursework load balancer');
const raw=new Uint8Array(await Bun.file(resolve(root,'.local/concurrent.png')).arrayBuffer());
touched=true;
await command([resolve(root,'scripts/compose.sh'),'up','-d','--no-deps','--force-recreate','api']);
await command([process.execPath,'--no-env-file','student-tests/wait.ts']);
const user=await json('POST','/api/v1/users',201,undefined,{username:prefix,display_name:'Synthetic image experiment',password:'synthetic-password-123'});
const session=await json('POST','/api/v1/auth/sessions',201,undefined,undefined,{Authorization:'Basic '+Buffer.from(prefix+':synthetic-password-123').toString('base64')});
const chat=await json('POST','/api/v1/chats',201,session.token,{title:'Ten concurrent image uploads',member_ids:[user.id]});
const ids=(await command([resolve(root,'scripts/compose.sh'),'ps','-q','api'])).trim().split(/\s+/);
monitor=(async()=>{while(!finished){const out=await command(['docker','stats','--no-stream','--format','{{json .}}',...ids]);for(const line of out.trim().split('\n').filter(Boolean)){const row=JSON.parse(line);samples.push({name:row.Name,cpu_percent:row.CPUPerc,memory:row.MemUsage});}}})().catch(error=>{monitorError=error;finished=true;});
const uploads=Array.from({length:10},async(_,index)=>{
let offset=0;
const body=new ReadableStream<Uint8Array>({async pull(controller){if(offset===raw.length){controller.close();return;}await Bun.sleep(30);const next=Math.min(raw.length,offset+65536);controller.enqueue(raw.slice(offset,next));offset=next;}});
const r=await fetch(base+'/api/v1/chats/'+chat.id+'/attachments?filename=concurrent-'+index+'.png',{method:'POST',headers:{Authorization:'Bearer '+session.token,'Content-Type':'image/png'},body,signal:AbortSignal.timeout(30000)});
const payload=await r.json() as any;
if(r.status!==201&&r.status!==503)throw new Error('Unexpected concurrent upload status');
if(r.status===201){const content=await fetch(base+'/api/v1/attachments/'+payload.id+'/content',{headers:{Authorization:'Bearer '+session.token},signal:AbortSignal.timeout(10000)});const bytes=new Uint8Array(await content.arrayBuffer());if(content.status!==200||!Buffer.from(bytes).equals(Buffer.from(raw)))throw new Error('Concurrent upload original was corrupted');}
return r.status;
});
const results=await Promise.allSettled(uploads);finished=true;await monitor;if(monitorError)throw monitorError;
const statuses:number[]=[];for(const r of results){if(r.status==='rejected')throw r.reason;statuses.push(r.value);}
if(!statuses.includes(201))throw new Error('No upload succeeded');
const peaks=[];
for(const id of ids){
const pid=Number((await command(['docker','inspect','--format','{{.State.Pid}}',id])).trim());
if(!Number.isSafeInteger(pid)||pid<=0)throw new Error('Invalid owned API process ID');
const group=(await Bun.file('/proc/'+pid+'/cgroup').text()).split('\n').find(line=>line.startsWith('0::'))?.slice(3);
if(!group||!group.startsWith('/')||group.includes('..'))throw new Error('Invalid cgroup path');
const peak=Number((await Bun.file('/sys/fs/cgroup'+group+'/memory.peak').text()).trim());
if(!Number.isFinite(peak)||peak<=0||peak>=2*1024**3)throw new Error('Container memory peak exceeded budget');
peaks.push({instance:id.slice(0,12),memory_peak_bytes:peak});
}
await json('GET','/health/ready',200);
await guard();
result={attempts:10,image_bytes:raw.length,success:statuses.filter(s=>s===201).length,rejected_503:statuses.filter(s=>s===503).length,peaks,samples,originals_verified:true};
}catch(error){primary=error;}
finally{
finished=true;
if(monitor)await monitor;
if(touched)try{await command([resolve(root,'scripts/compose.sh'),'run','--rm','--no-deps','fixture-cleanup',prefix]);}catch{cleanupErrors.push('owned_fixture_cleanup');}
}
if(primary||cleanupErrors.length){await writeFile(resolve(evidence,'failure.json'),JSON.stringify({run_id:prefix,primary:primary instanceof Error?primary.name:primary?'unknown':null,cleanup_errors:cleanupErrors})+'\n');throw new Error('Concurrent image experiment failed; inspect this run');}
await writeFile(resolve(evidence,'summary.json'),JSON.stringify({run_id:prefix,complete:true,result},null,2)+'\n',{flag:'wx'});
console.log('PASS concurrent image memory: '+evidence);
+249
View File
@@ -0,0 +1,249 @@
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 Kubernetes concurrent image experiment");
process.exit(0);
}
const base = process.env.BASE_URL ?? "http://127.0.0.1:28204";
const prefix = "st_" + crypto.randomUUID().replaceAll("-", "").slice(0, 16);
async function command(args: string[]) {
const p = Bun.spawn(args, {
cwd: root,
stdout: "pipe",
stderr: "pipe",
signal: AbortSignal.timeout(90000),
});
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/concurrent-error.txt"), out + err, {
mode: 0o600,
});
throw new Error("Concurrent image operation failed");
}
return out;
}
function stand(args: string[]) {
return command([
process.execPath,
"--no-env-file",
"scripts/k3s.ts",
...args,
]);
}
async function guard() {
const p = Bun.spawn(["game-running"], { stdout: "ignore", stderr: "pipe" });
await new Response(p.stderr).text();
assertNoGame(await p.exited);
}
async function json(
method: string,
path: string,
status: number,
token?: string,
body?: unknown,
headers: Record<string, string> = {},
) {
const r = await fetch(base + path, {
method,
headers: {
...headers,
...(token ? { Authorization: "Bearer " + token } : {}),
...(body !== undefined ? { "Content-Type": "application/json" } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(30000),
});
const out = (await r.json()) as any;
if (r.status !== status)
throw new Error("Image experiment HTTP status differs");
return out;
}
const parent = resolve(root, "evidence/k3s/concurrent-images");
await mkdir(parent, { recursive: true });
const evidence = await mkdtemp(resolve(parent, "run-"));
await writeFile(
resolve(evidence, "run.json"),
JSON.stringify({
run_id: prefix,
started_at: new Date().toISOString(),
state: "started",
}) + "\n",
{ flag: "wx" },
);
let finished = false,
touched = false,
primary: unknown,
monitorError: unknown,
result: unknown,
monitor: Promise<void> | undefined;
const cleanupErrors: string[] = [],
samples: any[] = [];
try {
await guard();
const info = JSON.parse(await stand(["info"]));
if (new URL(base).origin !== "http://127.0.0.1:" + info.port)
throw new Error("API URL differs from the claimed Kubernetes endpoint");
const raw = new Uint8Array(
await Bun.file(resolve(root, ".local/concurrent.png")).arrayBuffer(),
);
touched = true;
await command([
resolve(root, "scripts/kube.sh"),
"rollout",
"restart",
"deployment/api",
]);
await stand(["ready"]);
const before = JSON.parse(await stand(["stats"]));
if (before.pods.length !== 2) throw new Error("Expected two API pods");
const user = await json("POST", "/api/v1/users", 201, undefined, {
username: prefix,
display_name: "Synthetic memory experiment",
password: "synthetic-password-123",
});
const session = await json(
"POST",
"/api/v1/auth/sessions",
201,
undefined,
undefined,
{
Authorization:
"Basic " +
Buffer.from(prefix + ":synthetic-password-123").toString("base64"),
},
);
const chat = await json("POST", "/api/v1/chats", 201, session.token, {
title: "Ten concurrent uploads",
member_ids: [user.id],
});
monitor = (async () => {
while (!finished) {
samples.push(JSON.parse(await stand(["stats"])));
await Bun.sleep(100);
}
})().catch((error) => {
monitorError = error;
finished = true;
});
const uploads = Array.from({ length: 10 }, async (_, index) => {
let offset = 0;
const body = new ReadableStream<Uint8Array>({
async pull(controller) {
if (offset === raw.length) {
controller.close();
return;
}
await Bun.sleep(30);
const next = Math.min(raw.length, offset + 65536);
controller.enqueue(raw.slice(offset, next));
offset = next;
},
});
const r = await fetch(
base +
"/api/v1/chats/" +
chat.id +
"/attachments?filename=concurrent-" +
index +
".png",
{
method: "POST",
headers: {
Authorization: "Bearer " + session.token,
"Content-Type": "image/png",
},
body,
signal: AbortSignal.timeout(30000),
},
);
const payload = (await r.json()) as any;
if (r.status !== 201 && r.status !== 503)
throw new Error("Unexpected concurrent upload status");
if (r.status === 201) {
const response = await fetch(
base + "/api/v1/attachments/" + payload.id + "/content",
{
headers: { Authorization: "Bearer " + session.token },
signal: AbortSignal.timeout(10000),
},
);
const bytes = new Uint8Array(await response.arrayBuffer());
if (
response.status !== 200 ||
!Buffer.from(bytes).equals(Buffer.from(raw))
)
throw new Error("Original bytes differ");
}
return r.status;
});
const completed = await Promise.allSettled(uploads);
finished = true;
await monitor;
if (monitorError) throw monitorError;
const statuses: number[] = [];
for (const r of completed) {
if (r.status === "rejected") throw r.reason;
statuses.push(r.value);
}
if (!statuses.includes(201)) throw new Error("No upload succeeded");
const after = JSON.parse(await stand(["stats"]));
if (
after.pods.length !== 2 ||
after.pods.some((p: any) => !before.pods.some((b: any) => b.uid === p.uid))
)
throw new Error("API pod was replaced during memory measurement");
if (
after.pods.some(
(p: any) =>
!Number.isFinite(p.memory_peak_bytes) ||
p.memory_peak_bytes <= 0 ||
p.memory_peak_bytes >= 2 * 1024 ** 3,
)
)
throw new Error("Invalid or excessive cgroup memory peak");
await json("GET", "/health/ready", 200);
await guard();
result = {
attempts: 10,
image_bytes: raw.length,
success: statuses.filter((x) => x === 201).length,
rejected_503: statuses.filter((x) => x === 503).length,
peaks: after.pods,
samples,
originals_verified: true,
};
} catch (error) {
primary = error;
} finally {
finished = true;
if (monitor) await monitor;
if (touched)
try {
await stand(["task", "fixture-cleanup", prefix]);
} catch {
cleanupErrors.push("fixture_cleanup");
}
}
if (primary || cleanupErrors.length) {
await writeFile(
resolve(evidence, "failure.json"),
JSON.stringify({
primary:
primary instanceof Error ? primary.message : primary ? "unknown" : null,
cleanup_errors: cleanupErrors,
}) + "\n",
);
throw new Error("Concurrent image experiment failed");
}
await writeFile(
resolve(evidence, "summary.json"),
JSON.stringify({ complete: true, run_id: prefix, result }, null, 2) + "\n",
{ flag: "wx" },
);
console.log("PASS concurrent Kubernetes uploads: " + evidence);
+37
View File
@@ -0,0 +1,37 @@
package main
import (
"image"
"image/png"
"os"
"path/filepath"
)
func main() {
destination := ".local/concurrent.png"
if e := os.MkdirAll(filepath.Dir(destination), 0700); e != nil {
panic(e)
}
img := image.NewNRGBA(image.Rect(0, 0, 1024, 1024))
var x uint32 = 0x12345678
for i := 0; i < len(img.Pix); i += 4 {
for channel := 0; channel < 3; channel++ {
x ^= x << 13
x ^= x >> 17
x ^= x << 5
img.Pix[i+channel] = byte(x)
}
img.Pix[i+3] = 255
}
f, e := os.Create(destination)
if e != nil {
panic(e)
}
if e = png.Encode(f, img); e != nil {
_ = f.Close()
panic(e)
}
if e = f.Close(); e != nil {
panic(e)
}
}
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
game_guard(){
local code
if game-running >/dev/null; then code=0; else code=$?; fi
if [ "$code" -ne 1 ]; then echo 'Game is active or its state is unknown; measurement stopped' >&2;exit 75;fi
}
game_guard
mkdir -p evidence/k3s
RUN=$(mktemp -d evidence/k3s/image-memory-XXXXXX)
printf '{"state":"started"}\n' >"$RUN/run.json"
sha256sum backend/internal/adapter/imagefile/image.go >"$RUN/source.sha256"
if [ "${VP_RUNTIME:-k3s}" = k3s ]; then
bun --no-env-file scripts/k3s.ts task image-memory >"$RUN/output.txt" 2>&1
else
./scripts/compose.sh run --rm --no-deps image-memory >"$RUN/output.txt" 2>&1
fi
game_guard
grep -F -- '--- PASS: TestWorstCaseImagesWithinBudget' "$RUN/output.txt"
grep -F 'peak_rss_kib=' "$RUN/output.txt"
printf '{"state":"complete"}\n' >"$RUN/run.json"
printf 'PASS image memory: %s\n' "$RUN"
+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",
);
+22
View File
@@ -0,0 +1,22 @@
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('Isolated integration runner parsed without accessing the stand');process.exit(0);}
const parent=resolve(root,'evidence/reconciliation');await mkdir(parent,{recursive:true});
const evidence=await mkdtemp(resolve(parent,'run-'));const runID=crypto.randomUUID();
const project='vp-lab4-integration-'+runID.slice(0,8);
await writeFile(resolve(evidence,'run.json'),JSON.stringify({run_id:runID,project,started_at:new Date().toISOString(),state:'started'})+'\n',{flag:'wx'});
let stage='preflight',created=false,primary:unknown;const cleanupErrors:string[]=[];
async function command(args:string[]){const p=Bun.spawn(['docker','compose','-f',resolve(root,'compose.yaml'),'-p',project,...args],{cwd:root,stdout:'pipe',stderr:'pipe',signal:AbortSignal.timeout(180000)});const [out,err]=await Promise.all([new Response(p.stdout).text(),new Response(p.stderr).text()]);await writeFile(resolve(evidence,stage+'.txt'),out+err);if(await p.exited!==0)throw new Error(stage+' failed');return out;}
try{
if((await command(['ps','-aq'])).trim())throw new Error('Fresh project unexpectedly exists');
stage='dependencies';created=true;await command(['up','-d','--wait','postgres','s3']);
stage='migrations';await command(['run','--rm','--no-deps','migrate']);
stage='bucket';await command(['run','--rm','--no-deps','bootstrap-s3']);
stage='tests';const out=await command(['run','--rm','--no-deps','integration']);
for(const name of ['TestReconciliationAgainstPostgresAndPrivateS3','TestS3InventoryAndStatReturnComparableVersionMetadata','TestFixtureCleanupRejectsForeignMembership'])if(!out.includes('--- PASS: '+name))throw new Error('Required integration test did not pass');
}catch(error){primary=error;}
finally{if(created){stage='cleanup';try{await command(['down','--volumes']);}catch{cleanupErrors.push('isolated_project');}}}
await writeFile(resolve(evidence,'result.json'),JSON.stringify({run_id:runID,complete:!primary&&!cleanupErrors.length,primary:primary instanceof Error?primary.name:primary?'unknown':null,cleanup_errors:cleanupErrors},null,2)+'\n',{flag:'wx'});
if(primary||cleanupErrors.length)throw new Error('Isolated integration failed; inspect this run');
console.log('PASS isolated S3/PostgreSQL reconciliation: '+evidence);
+94
View File
@@ -0,0 +1,94 @@
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("Parsed isolated k3s reconciliation runner");
process.exit(0);
}
const cluster =
"vp-lab4-r-" + crypto.randomUUID().replaceAll("-", "").slice(0, 8);
const env = {
...process.env,
VP_CLUSTER: cluster,
VP_RUNTIME: "k3s",
PUBLIC_PORT: "28404",
BASE_URL: "http://127.0.0.1:28404",
};
const parent = resolve(root, "evidence/k3s/reconciliation");
await mkdir(parent, { recursive: true });
const evidence = await mkdtemp(resolve(parent, "run-"));
let stage = "preflight",
created = false,
primary: unknown;
const cleanupErrors: string[] = [];
await writeFile(
resolve(evidence, "run.json"),
JSON.stringify({
cluster,
started_at: new Date().toISOString(),
state: "started",
}) + "\n",
{ flag: "wx" },
);
async function command(action: string[]) {
const p = Bun.spawn(
[process.execPath, "--no-env-file", "scripts/k3s.ts", ...action],
{
cwd: root,
env,
stdout: "pipe",
stderr: "pipe",
signal: AbortSignal.timeout(420000),
},
);
const [out, err] = await Promise.all([
new Response(p.stdout).text(),
new Response(p.stderr).text(),
]);
await writeFile(resolve(evidence, stage + ".txt"), out + err);
if ((await p.exited) !== 0) throw new Error(stage + " failed");
return out;
}
try {
stage = "create_isolated_cluster";
created = true;
await command(["up"]);
stage = "tests";
const out = await command(["task", "integration"]);
for (const name of [
"TestReconciliationAgainstPostgresAndPrivateS3",
"TestS3InventoryAndStatReturnComparableVersionMetadata",
"TestFixtureCleanupRejectsForeignMembership",
])
if (!out.includes("--- PASS: " + name))
throw new Error("Required integration test did not pass");
} catch (error) {
primary = error;
} finally {
if (created) {
stage = "cleanup";
try {
await command(["destroy"]);
} catch {
cleanupErrors.push("isolated_cluster");
}
}
}
await writeFile(
resolve(evidence, "result.json"),
JSON.stringify(
{
complete: !primary && !cleanupErrors.length,
cluster,
primary:
primary instanceof Error ? primary.message : primary ? "unknown" : null,
cleanup_errors: cleanupErrors,
},
null,
2,
) + "\n",
{ flag: "wx" },
);
if (primary || cleanupErrors.length)
throw new Error("Isolated reconciliation failed; inspect this run");
console.log("PASS isolated k3s reconciliation: " + 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');