Port final lab 5 validation, session and PNG recovery fixes

This commit is contained in:
Artyom
2026-11-07 02:35:40 +03:00
parent 97feb04b3f
commit bc1d7aa771
41 changed files with 4363 additions and 53 deletions
+59
View File
@@ -0,0 +1,59 @@
import json
import os
import platform
import subprocess
from collections import Counter
from datetime import UTC, datetime
def command(*args: str) -> str:
return subprocess.check_output(args, text=True).strip()
project = os.environ.get("COMPOSE_PROJECT_NAME", "mtusi2026lab6")
containers = [
json.loads(line)
for line in command(
"docker",
"ps",
"--format",
'{"name":"{{.Names}}","project":"{{.Label "com.docker.compose.project"}}"}',
).splitlines()
]
own = {row["name"] for row in containers if row["project"] == project}
stats = [
json.loads(line)
for line in command("docker", "stats", "--no-stream", "--format", "{{json .}}").splitlines()
]
print(
json.dumps(
{
"at": datetime.now(UTC).isoformat(),
"runtime_sha": command("git", "rev-parse", "HEAD"),
"platform": platform.system(),
"architecture": platform.machine(),
"host_cpus": os.cpu_count(),
"host_load": os.getloadavg(),
"docker": command(
"docker",
"info",
"--format",
"{{.NCPU}} CPUs; {{.MemTotal}} bytes; {{.ServerVersion}}",
),
"own_project": project,
"own": [
{key: row[key] for key in ("Name", "CPUPerc", "MemUsage", "PIDs")}
for row in stats
if row["Name"] in own
],
"other_projects": dict(
Counter(
row["project"] or "unlabelled" for row in containers if row["name"] not in own
)
),
"sampling": "Shared Docker snapshot; no throughput claim",
},
ensure_ascii=False,
indent=2,
)
)
+130
View File
@@ -0,0 +1,130 @@
import base64
import http.client
import json
import os
import uuid
from urllib.parse import urlsplit
base = urlsplit(os.environ.get("BASE_URL", "http://127.0.0.1:18086"))
seen = set()
checks = []
password = "Пароль-проверки-01"
def call(method, path, body=None, headers=None, status=200):
request_id = "validation-wire"
assert base.hostname
conn = http.client.HTTPConnection(base.hostname, base.port, timeout=12)
head = {"X-Request-Id": request_id, "Content-Type": "application/json", **(headers or {})}
conn.request(method, path, None if body is None else json.dumps(body).encode(), head)
response = conn.getresponse()
data = response.read()
instance = response.getheader("X-Instance-Id")
assert response.status == status, (method, path, response.status, status)
assert instance
assert response.getheader("X-Request-Id") == request_id
seen.add(instance)
result = json.loads(data) if data else None
if status >= 400:
assert result is not None
assert result["error"]["request_id"] == request_id
if status == 401:
assert response.getheader("WWW-Authenticate") == (
'Basic realm="messenger", charset="UTF-8"'
if path == "/api/v1/auth/sessions"
else 'Bearer realm="messenger"'
)
conn.close()
return result, instance
def basic(name, secret=password):
return {"Authorization": "Basic " + base64.b64encode(f"{name}:{secret}".encode()).decode()}
def enroll():
name = "wire_" + uuid.uuid4().hex[:15]
user, _ = call(
"POST",
"/api/v1/users",
{"username": name, "password": password, "display_name": "Алиса 👋"},
status=201,
)
login, _ = call("POST", "/api/v1/auth/sessions", headers=basic(name), status=201)
return user, {"Authorization": "Bearer " + login["token"]}
user, auth = enroll()
wrong, _ = call(
"POST", "/api/v1/auth/sessions", headers=basic(user["username"], "wrong-password"), status=401
)
for raw in [b"Basic \x80", b"Basic \xff", b"Basic \xc3\xa9", b"Basic YWxpY2U6c2VjcmV0\xff"]:
result, instance = call(
"POST", "/api/v1/auth/sessions", headers={"Authorization": raw}, status=401
)
assert result == wrong
checks.append(
{"case": "non_ascii_basic", "raw_hex": raw.hex(), "status": 401, "instance": instance}
)
for text in ["\x00", "\x00abc", "abc\x00def", "abc\x00"]:
result, instance = call("POST", "/api/v1/auth/sessions", headers=basic(text), status=401)
assert result == wrong
body = {"username": "wire_" + uuid.uuid4().hex[:15], "password": password, "display_name": text}
call("POST", "/api/v1/users", body, status=400)
call("POST", "/api/v1/users", {**body, "display_name": "Алиса 👋"}, status=201)
call("POST", "/api/v1/chats", {"title": text, "member_ids": [user["id"]]}, auth, status=400)
chats, _ = call("GET", "/api/v1/chats", headers=auth)
assert not chats["items"]
checks.append(
{
"case": "nul_basic_display_title",
"position": repr(text),
"status": [401, 400, 201, 400],
"instance": instance,
}
)
chat, _ = call(
"POST", "/api/v1/chats", {"title": "Проверка 👋", "member_ids": [user["id"]]}, auth, status=201
)
path = f"/api/v1/chats/{chat['id']}/messages"
messages = []
for text in ["\x00", "\x00abc", "abc\x00def", "abc\x00"]:
headers = {**auth, "Idempotency-Key": uuid.uuid4().hex}
call("POST", path, {"text": text}, headers, status=400)
page, _ = call("GET", path, headers=auth)
assert page["items"] == messages
first, one = call("POST", path, {"text": "Исправлено\tбез потерь\n👋"}, headers, status=201)
again, two = call("POST", path, {"text": first["text"]}, headers, status=201)
assert first == again and one != two
messages.append(first)
page, _ = call("GET", path, headers=auth)
assert page["items"] == messages
checks.append(
{
"case": "nul_message_corrected_retry",
"position": repr(text),
"instances": [one, two],
"status": [400, 201, 201],
"copies": 1,
}
)
_, outsider = enroll()
for target in [chat["id"], str(uuid.uuid4())]:
call(
"POST",
f"/api/v1/chats/{target}/messages",
{"text": "abc\x00def"},
{**outsider, "Idempotency-Key": uuid.uuid4().hex},
status=404,
)
checks.append({"case": "nul_access", "status": [404, 404]})
call("DELETE", "/api/v1/auth/sessions/current", headers=auth, status=204)
for _ in range(4):
call("GET", "/api/v1/users/me", headers=auth, status=401)
checks.append({"case": "logout_across_replicas", "status": [204, 401, 401, 401, 401]})
assert len(seen) >= 2
print(
json.dumps(
{"checks": checks, "instances": sorted(seen), "pass": True}, ensure_ascii=False, indent=2
)
)
+386
View File
@@ -0,0 +1,386 @@
import hashlib
import json
import os
import struct
import sys
import time
from io import BytesIO
from pathlib import Path
from typing import Any
from PIL import Image
from scripts import pipeline_suite as ps
from messenger.attachments.infrastructure.images import RenderLimits, render_variants
from png_trns_fixtures import boundary_png, png_with_trns
ROOT = Path(__file__).resolve().parents[2]
MODE = sys.argv.pop(1)
OUT = Path(os.environ.get("FORWARD_EVIDENCE_DIR", "evidence/forward-published")) / (MODE + ".json")
if OUT.exists():
raise SystemExit("Result exists; do not repeat completed evidence")
SUITE = ps.Suite(ps.arguments())
STACK = SUITE.stack
REPORT: dict[str, Any] = {
"mode": MODE,
"source_sha": ps.run(["git", "rev-parse", "HEAD"]).strip(),
"started_at": ps.now(),
"cases": [],
}
LIMITS = RenderLimits(10485760, 40000000)
def save():
REPORT["accepted_ids"] = SUITE.api.accepted if SUITE.api else []
OUT.write_text(json.dumps(REPORT, ensure_ascii=False, indent=2) + "\n")
def case(name, function):
row = {"name": name, "started_at": ps.now()}
REPORT["cases"].append(row)
save()
began = time.monotonic()
try:
row["observed"] = function()
row["result"] = "PASS"
except Exception as error:
row.update(result="FAIL", error=str(error))
row["elapsed_seconds"] = round(time.monotonic() - began, 3)
save()
print(name, row["result"], row.get("error", ""), flush=True)
def containers():
return STACK.dc("ps", "-a", "--format", "{{.Name}} {{.ID}} {{.State}} {{.Status}}").splitlines()
def outage():
assert SUITE.api is not None
SUITE.drained()
before_dlq = STACK.queues()[ps.DLQ]
STACK.stop("worker")
att = SUITE.api.fixture()
ident = att["id"]
ps.poll(
lambda: all(r["published"] for r in STACK.sql("outbox", id=ident)), 30, "published outbox"
)
jobs = STACK.sql("jobs", id=ident)
REPORT["outage_checkpoint"] = {
"attachment_id": ident,
"jobs_before": jobs,
"dlq_before": before_dlq,
}
save()
STACK.stop("postgres")
REPORT["outage_checkpoint"]["stopped_containers"] = containers()
save()
since = ps.now()
worker_id = STACK.dc("ps", "-aq", "worker").strip()
assert worker_id
ps.run(["docker", "start", worker_id])
def requeues():
logs = STACK.dc("logs", "--no-color", "--since", since, "worker")
rows = [
line
for line in logs.splitlines()
if "job.requeued" in line and jobs[0]["job_id"] in line
]
return rows if len(rows) >= 12 else None
try:
lines = ps.poll(requeues, 90, "12 real database failures", 1)
OUT.with_name(OUT.stem + "-worker.txt").write_text("\n".join(lines) + "\n")
during = STACK.queues()
finally:
STACK.up("postgres")
ps.poll(lambda: ps.http_ready(SUITE.args.base_url), 30, "API after PostgreSQL")
ready = SUITE.api.wait(ident)
SUITE.verify(ready)
SUITE.drained()
after = STACK.sql("jobs", id=ident)
assert (
after[0]["job_id"] == jobs[0]["job_id"] and after[0]["attempt"] == jobs[0]["attempt"] == 1
)
assert after[0]["status"] == "done"
assert STACK.queues()[ps.DLQ] == before_dlq
assert len(STACK.sql("variants", id=ident)) == 3
return {
"attachment_id": ident,
"jobs_before": jobs,
"jobs_after": after,
"requeues": len(lines),
"queues_during": during,
"queues_after": STACK.queues(),
"replay": False,
"stopped_containers": REPORT["outage_checkpoint"]["stopped_containers"],
}
def png(name, data, reference):
assert SUITE.api is not None
att = SUITE.api.upload(data, name=name + ".png")
ident = att["id"]
results = []
for version in (1, 2):
if version == 2:
STACK.admin("reprocess", "--attachment-id", ident, "--pipeline-version", "2")
ps.poll(lambda: SUITE.record(ident)["published_version"] == 2, 90, "published v2")
ready = SUITE.api.wait(ident)
SUITE.verify(ready)
assert SUITE.api.content(ident)["bytes"] == data
expected = {r.name: r for r in render_variants(reference, LIMITS, version)}
variants = []
for variant in ready["variants"]:
content = SUITE.api.content(ident, variant["name"])["bytes"]
assert content == expected[variant["name"]].data, (
variant["name"] + " differs from independent white reference"
)
with Image.open(BytesIO(content)) as image:
assert not image.getexif()
assert not any(key in image.info for key in ("icc_profile", "xmp", "transparency"))
variants.append(
{
"name": variant["name"],
"sha256": hashlib.sha256(content).hexdigest(),
"bytes": len(content),
"dimensions": [variant["width"], variant["height"]],
}
)
results.append({"version": version, "variants": variants})
before = SUITE.snapshot(ident)
STACK.publish(SUITE.payload(ident, 1))
STACK.publish(SUITE.payload(ident, 2))
SUITE.drained()
assert SUITE.snapshot(ident) == before
assert len(STACK.sql("variants", id=ident)) == 6
return {
"attachment_id": ident,
"input_sha256": hashlib.sha256(data).hexdigest(),
"input_bytes": len(data),
"versions": results,
"stale_and_duplicate_noop": True,
}
FIXTURES = ROOT / "build/forward-png"
FIXTURES.mkdir(parents=True, exist_ok=True)
for fixture_name, fixture_depth, fixture_key in (
("gray2", 2, (1,)),
("gray4", 4, (5,)),
("gray16", 16, (12345,)),
("rgb16", 16, (12345, 23456, 34567)),
):
(FIXTURES / (fixture_name + "-40mp.png")).write_bytes(boundary_png(fixture_depth, fixture_key))
ps.SQL["timed_events"] = (
"SELECT attachment_id,job_id,kind,at FROM job_events "
"WHERE attachment_id = ANY(:'ids'::uuid[]) AND kind IN ('claimed','done') ORDER BY id"
)
def without_trns(data):
result, offset = data[:8], 8
while offset < len(data):
size = struct.unpack(">I", data[offset : offset + 4])[0] + 12
if data[offset + 4 : offset + 8] != b"tRNS":
result += data[offset : offset + size]
offset += size
return result
def verify_large(ident, data, transparent):
assert SUITE.api is not None
ready = SUITE.api.wait(ident)
SUITE.verify(ready)
assert SUITE.api.content(ident)["bytes"] == data
variants = []
for variant in ready["variants"]:
content = SUITE.api.content(ident, variant["name"])["bytes"]
with Image.open(BytesIO(content)) as image:
left = image.getpixel((5, image.height // 2))
right = image.getpixel((image.width - 6, image.height // 2))
assert (left == (255, 255, 255)) == transparent
assert right != (255, 255, 255)
assert not image.getexif()
variants.append({**variant, "left_pixel": left, "right_pixel": right})
return variants
def duplicate_check(ident):
before = SUITE.snapshot(ident)
STACK.publish(SUITE.payload(ident, 1))
STACK.publish(SUITE.payload(ident, 2))
SUITE.drained()
assert SUITE.snapshot(ident) == before
assert len(STACK.sql("variants", id=ident)) == 6
def large(name, data, transparent=True):
assert SUITE.api is not None
att = SUITE.api.upload(data, name=name + ".png")
ident = att["id"]
versions = [{"version": 1, "variants": verify_large(ident, data, transparent)}]
STACK.admin("reprocess", "--attachment-id", ident, "--pipeline-version", "2")
ps.poll(lambda: SUITE.record(ident)["published_version"] == 2, 90, "v2 publication")
versions.append({"version": 2, "variants": verify_large(ident, data, transparent)})
duplicate_check(ident)
return {
"attachment_id": ident,
"input_sha256": hashlib.sha256(data).hexdigest(),
"bytes": len(data),
"versions": versions,
"memory_peak": int(STACK.cgroup("worker", "memory.peak")),
"memory_max": int(STACK.cgroup("worker", "memory.max")),
}
def concurrent():
assert SUITE.api is not None
data = (FIXTURES / "rgb16-40mp.png").read_bytes()
SUITE.drained()
STACK.stop("worker")
try:
ids = [SUITE.api.upload(data, name="concurrent-rgb16.png")["id"] for _ in range(2)]
SUITE.queued(2)
finally:
ps.run(["docker", "start", STACK.dc("ps", "-aq", "worker").strip()])
versions = []
for version in (1, 2):
if version == 2:
STACK.stop("worker")
try:
for ident in ids:
STACK.admin("reprocess", "--attachment-id", ident, "--pipeline-version", "2")
SUITE.queued(2)
finally:
ps.run(["docker", "start", STACK.dc("ps", "-aq", "worker").strip()])
for ident in ids:
ps.poll(
lambda ident=ident, version=version: (
SUITE.record(ident)["published_version"] == version
),
90,
"concurrent publication",
)
variants = {ident: verify_large(ident, data, True) for ident in ids}
events = STACK.sql("timed_events", ids="{" + ",".join(ids) + "}")
job_ids = {
row["job_id"]
for ident in ids
for row in STACK.sql("jobs", id=ident)
if row["pipeline_version"] == version
}
selected = [e for e in events if e["job_id"] in job_ids]
claims = [e["at"] for e in selected if e["kind"] == "claimed"]
done = [e["at"] for e in selected if e["kind"] == "done"]
assert len(claims) == len(done) == 2
assert max(claims) < min(done), selected
versions.append(
{
"version": version,
"events": selected,
"processing_overlapped": True,
"variants": variants,
}
)
for ident in ids:
duplicate_check(ident)
peak, limit = (int(STACK.cgroup("worker", name)) for name in ("memory.peak", "memory.max"))
assert peak < limit
return {
"attachment_ids": ids,
"versions": versions,
"memory_peak": peak,
"memory_max": limit,
"memory_events": STACK.cgroup("worker", "memory.events"),
}
def forced(**overrides):
data = (FIXTURES / "rgb16-40mp.png").read_bytes()
result = SUITE.limited(data, **overrides)
STACK.restore()
result["next_normal"] = SUITE.smoke_pipeline()
return result
try:
SUITE.detect_api()
SUITE.api = ps.Api(SUITE.args)
dead_before = STACK.queues()[ps.DLQ][0]
REPORT["conditions"] = {
"host_load": os.getloadavg(),
"containers": containers(),
"running": ps.run(["docker", "ps", "--format", "{{.Names}} {{.Status}}"]),
"worker_limits": STACK.dc(
"exec",
"-T",
"worker",
"printenv",
"RENDER_MEMORY_MB",
"RENDER_TIMEOUT_SECONDS",
"WORKER_CONCURRENCY",
),
}
save()
if MODE == "postgres-outage":
case("published_outbox_database_outage", outage)
elif MODE == "png-http":
for name, depth, color in [
("gray1", 1, (0,)),
("gray2", 2, (1,)),
("gray4", 4, (5,)),
("gray8", 8, (85,)),
("gray16", 16, (12345,)),
("rgb8", 8, (255, 0, 0)),
("rgb16", 16, (12345, 23456, 34567)),
]:
case(
name,
lambda name=name, depth=depth, color=color: png(name, *png_with_trns(depth, color)),
)
case(
"rgb16-adam7-filter4-exif6",
lambda: png(
"adam7",
*png_with_trns(
16,
(12345, 23456, 34567),
size=(65, 63),
interlace=1,
filtering=4,
orientation=6,
),
),
)
elif MODE == "png-boundary":
for name in ("gray2", "gray4", "gray16", "rgb16"):
case(
name, lambda name=name: large(name, (FIXTURES / (name + "-40mp.png")).read_bytes())
)
case(
"gray16-without-trns",
lambda: large(
"gray16-opaque", without_trns((FIXTURES / "gray16-40mp.png").read_bytes()), False
),
)
case("concurrent-rgb16", concurrent)
case("forced-timeout", lambda: forced(FAULT_RENDER_TIMEOUT_SECONDS="0.01"))
case("forced-memory", lambda: forced(FAULT_RENDER_MEMORY_MB="200"))
ids = "{" + ",".join(SUITE.api.accepted) + "}"
ps.poll(lambda: not STACK.sql("staging_left", ids=ids), 45, "staging sweep")
SUITE.drained()
REPORT["invariants"] = SUITE.invariants(dead_before)
finally:
STACK.up("postgres")
STACK.restore()
REPORT["finished_at"] = ps.now()
REPORT["result"] = (
"PASS"
if REPORT["cases"]
and all(x.get("result") == "PASS" for x in REPORT["cases"] + REPORT.get("invariants", []))
else "FAIL"
)
save()
raise SystemExit(0 if REPORT["result"] == "PASS" else 1)
+43
View File
@@ -0,0 +1,43 @@
import http.client
import json
import sys
import time
status = int(sys.argv[1])
path = {502: "/bad", 503: "/none", 504: "/slow"}[status]
if status != 503:
for _ in range(60):
conn = http.client.HTTPConnection("lb", 8080, timeout=2)
conn.request("GET", "/health/ready")
response = conn.getresponse()
response.read()
conn.close()
if response.status == 200:
break
time.sleep(1)
else:
raise RuntimeError("Backend never became ready")
else:
time.sleep(5)
for value in ['a"b', "a\\b", "a\tb", "x" * 200]:
conn = http.client.HTTPConnection("lb", 8080, timeout=20)
start = time.monotonic()
conn.request("GET", path, headers={"X-Request-Id": value})
response = conn.getresponse()
payload = json.loads(response.read())
assert response.status == status, response.status
assert response.getheader("X-Request-Id") == value
assert payload["error"]["request_id"] == value
print(
json.dumps(
{
"status": status,
"request_id": value,
"json_valid": True,
"echo_matches": True,
"seconds": round(time.monotonic() - start, 3),
}
),
flush=True,
)
conn.close()
@@ -0,0 +1,25 @@
services:
lb:
image: haproxy:3.2.26-alpine@sha256:5893840576071e6217cd52ebdcc14f454c6f7a631056fa6f4e0f40d3cac4215b
volumes: [../../../infra/haproxy/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro]
init: true
deploy:
resources:
limits: {cpus: "0.5", memory: 128m}
api:
image: ${API_IMAGE:?Set the image built by the lab6 stack}
entrypoint: [python, /fixture/server.py]
volumes: [./:/fixture:ro]
init: true
deploy:
resources:
limits: {cpus: "0.5", memory: 128m}
probe:
image: ${API_IMAGE:?Set the image built by the lab6 stack}
entrypoint: [python, /fixture/client.py]
volumes: [./:/fixture:ro]
profiles: [probe]
init: true
deploy:
resources:
limits: {cpus: "0.5", memory: 128m}
+20
View File
@@ -0,0 +1,20 @@
import socketserver
import time
class Handler(socketserver.StreamRequestHandler):
def handle(self) -> None:
request = self.rfile.readline(8192)
while self.rfile.readline(8192) not in {b"\r\n", b""}:
pass
path = request.split(b" ")[1]
if path == b"/bad":
self.wfile.write(b"NOT-HTTP\r\n\r\n")
elif path == b"/slow":
time.sleep(12)
else:
self.wfile.write(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nOK")
with socketserver.ThreadingTCPServer(("0.0.0.0", 8080), Handler) as server:
server.serve_forever()