ЛР 2: PostgreSQL, сессии, Redis и исследование
Skeleton contracts / contracts (pull_request) Failing after 30s
Skeleton contracts / contracts (pull_request) Failing after 30s
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
"""Local Compose test helpers. SQL uses only synthetic identifiers generated by tests."""
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Failure, check # noqa: E402
|
||||
|
||||
|
||||
def compose(*args, input_text=None, timeout=40):
|
||||
result = subprocess.run(["docker", "compose", *args], cwd=ROOT, input=input_text,
|
||||
text=True, capture_output=True, timeout=timeout)
|
||||
check(result.returncode == 0, "Compose operation failed (inspect the local stack)")
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def sql(statement, service="postgres", database="messenger", timeout=40):
|
||||
return compose("exec", "-T", service, "psql", "-X", "-U", "messenger",
|
||||
"-d", database, "-v", "ON_ERROR_STOP=1", "-Atq", input_text=statement, timeout=timeout)
|
||||
|
||||
|
||||
def redis(*args):
|
||||
return compose("exec", "-T", "redis", "redis-cli", "--raw", *args)
|
||||
|
||||
|
||||
def ready(client):
|
||||
deadline = time.monotonic() + 45
|
||||
while True:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, "stack did not recover within 45 seconds")
|
||||
time.sleep(0.5)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Temporarily pause Redis / stop PostgreSQL in the local stack; always restore them."""
|
||||
import argparse
|
||||
import hashlib
|
||||
|
||||
from compose_helpers import compose, ready, redis
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url, timeout=15)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
key = "messenger:session:" + hashlib.sha256(alice["token"].encode("ascii")).hexdigest()
|
||||
check(redis("EXISTS", key) == "1", "session cache was not warmed")
|
||||
cached_snapshot = redis("GET", key)
|
||||
|
||||
# Pause preserves the stale entry while all Redis commands time out.
|
||||
try:
|
||||
compose("pause", "redis")
|
||||
response = client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
check(response["json"] == alice["user"] and response["elapsed"] < 3,
|
||||
"Redis outage did not fall back within 3 seconds")
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": alice["id"]})
|
||||
client.call("GET", "/api/v1/users/me", 401, headers={"Authorization": "Bearer " + "A" * 43})
|
||||
message = client.message(bob, chat, "Redis недоступен: запись сохраняется")["json"]
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=alice)
|
||||
finally:
|
||||
compose("unpause", "redis")
|
||||
# A timed-out command may still execute after unpause. Recreate a stale entry
|
||||
# deterministically to model a concurrent cache fill completing after logout.
|
||||
redis("SET", key, cached_snapshot, "PX", "60000")
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=alice)
|
||||
print("PASS: Redis timeout fallback <3s, writes work, anonymous access denied, stale entry cannot undo logout")
|
||||
|
||||
# Redis may still hold Bob's valid entry; it cannot authorize when PostgreSQL is down.
|
||||
client.call("GET", "/api/v1/users/me", actor=bob, schema="User")
|
||||
try:
|
||||
compose("stop", "postgres")
|
||||
client.call("GET", "/health/live", schema="Health")
|
||||
unavailable = client.call("GET", "/health/ready", 503)
|
||||
check(unavailable["json"]["error"]["code"] == "unavailable", "wrong readiness failure")
|
||||
response = client.call("GET", "/api/v1/users/me", 503, actor=bob)
|
||||
check(response["elapsed"] < 12 and response["json"]["error"]["code"] == "unavailable",
|
||||
"PostgreSQL failure is unbounded or trusts cached identity")
|
||||
client.call("POST", "/api/v1/chats/" + chat["id"] + "/messages", 503,
|
||||
actor=bob, body={"text": "Не подтверждать при отказе БД"})
|
||||
client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": bob["id"]})
|
||||
finally:
|
||||
compose("start", "postgres")
|
||||
ready(client)
|
||||
client.call("GET", "/api/v1/users/me", actor=bob, schema="User")
|
||||
page = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage")["json"]
|
||||
check(message in page["items"], "confirmed write during Redis outage was lost")
|
||||
check(not any(item["text"] == "Не подтверждать при отказе БД" for item in page["items"]), "failed DB write was committed")
|
||||
print("PASS: PostgreSQL outage -> bounded 503; cache cannot authorize; data and session recover")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,81 @@
|
||||
"""Reproduce the actual keyset history query on >=10,000 synthetic messages."""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from compose_helpers import ROOT, sql
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url)
|
||||
actor = client.user("explain")
|
||||
chat = client.call("POST", "/api/v1/chats", 201, actor=actor,
|
||||
body={"title": "EXPLAIN 10000 " + uuid.uuid4().hex,
|
||||
"member_ids": [actor["id"]]}, schema="Chat")["json"]
|
||||
chat_id, user_id = chat["id"], actor["id"]
|
||||
# One fixed timeline and deterministic unique UUIDs; each run uses its own chat.
|
||||
sql(f"""
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT md5('{chat_id}:' || n::text)::uuid, '{chat_id}'::uuid, '{user_id}'::uuid,
|
||||
repeat('message-' || n::text || ' ', 8),
|
||||
'2026-01-01T00:00:00Z'::timestamptz + n * interval '1 millisecond'
|
||||
FROM generate_series(1, 10000) AS fixture(n);
|
||||
ANALYZE messages;
|
||||
""")
|
||||
count = int(sql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat_id}';"))
|
||||
check(count == 10000, "fixture must contain exactly 10000 messages")
|
||||
anchor = json.loads(sql(f"""
|
||||
SELECT json_build_object('id', id, 'created_at', to_char(created_at AT TIME ZONE 'UTC',
|
||||
'YYYY-MM-DD\"T\"HH24:MI:SS.US\"Z\"'))
|
||||
FROM messages WHERE chat_id = '{chat_id}' ORDER BY created_at, id OFFSET 8999 LIMIT 1;
|
||||
"""))
|
||||
# OFFSET is used only once to choose the benchmark anchor, never by the API query.
|
||||
first_query = f"SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = '{chat_id}' ORDER BY created_at, id LIMIT 51"
|
||||
next_query = f"SELECT id, chat_id, sender_id, text, created_at FROM messages WHERE chat_id = '{chat_id}' AND (created_at, id) > ('{anchor['created_at']}'::timestamptz, '{anchor['id']}'::uuid) ORDER BY created_at, id LIMIT 51"
|
||||
plans = {}
|
||||
for name, query in [("first_page", first_query), ("after_message_9000", next_query)]:
|
||||
plan = json.loads(sql("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " + query + ";"))[0]
|
||||
nodes = list(walk(plan["Plan"]))
|
||||
check(any(node.get("Index Name") == "messages_chat_created_id_idx" for node in nodes),
|
||||
name + " did not use the history index")
|
||||
check(not any(node["Node Type"] == "Seq Scan" for node in nodes), name + " scanned the entire message table")
|
||||
check(plan["Plan"]["Actual Rows"] == 51, "plan returned an unexpected page size")
|
||||
plans[name] = {"query": query, "explain_analyze_buffers": plan}
|
||||
|
||||
encoded = base64.urlsafe_b64encode(json.dumps({"Scope": "chat:" + chat_id,
|
||||
"CreatedAt": anchor["created_at"], "Id": anchor["id"]}).encode()).decode().rstrip("=")
|
||||
first = client.call("GET", f"/api/v1/chats/{chat_id}/messages?limit=50", actor=actor, schema="MessagePage")["json"]
|
||||
deep = client.call("GET", f"/api/v1/chats/{chat_id}/messages?limit=50&cursor={encoded}",
|
||||
actor=actor, schema="MessagePage")["json"]
|
||||
check(len(first["items"]) == len(deep["items"]) == 50 and deep["next_cursor"] is not None,
|
||||
"API did not return the expected keyset pages")
|
||||
next_page = client.call("GET", f"/api/v1/chats/{chat_id}/messages?limit=50&cursor={deep['next_cursor']}",
|
||||
actor=actor, schema="MessagePage")["json"]
|
||||
check(not set(item["id"] for item in deep["items"]) & set(item["id"] for item in next_page["items"]),
|
||||
"keyset continuation repeated messages")
|
||||
evidence = {"verified_at": datetime.now(timezone.utc).isoformat(), "message_count_in_chat": count,
|
||||
"fixture": "synthetic data; no tokens or passwords in evidence", "plans": plans,
|
||||
"api_pages": {"first": 50, "deep": 50, "continuation": len(next_page["items"]), "duplicates": 0}}
|
||||
destination = ROOT / "evidence" / "history-explain.json"
|
||||
destination.parent.mkdir(exist_ok=True)
|
||||
destination.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n")
|
||||
for name, value in plans.items():
|
||||
plan = value["explain_analyze_buffers"]
|
||||
print(f"PASS: {name}: history index, 51 SQL rows, execution {plan['Execution Time']} ms")
|
||||
print("PASS: 10000 messages, deep API pagination without repeats; evidence/history-explain.json")
|
||||
|
||||
|
||||
def walk(node):
|
||||
yield node
|
||||
for child in node.get("Plans", []):
|
||||
yield from walk(child)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Registration race, genuine transaction rollback and observable Redis cache use."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import threading
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from compose_helpers import redis, sql
|
||||
from client import Client, check, run
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url, timeout=30)
|
||||
|
||||
username = "race_" + uuid.uuid4().hex[:16]
|
||||
registration = {"username": username, "display_name": "Гонка",
|
||||
"password": "Race-password-" + uuid.uuid4().hex}
|
||||
gate = threading.Barrier(4)
|
||||
|
||||
def register(_):
|
||||
own_client = Client(args.base_url, timeout=30)
|
||||
gate.wait(timeout=10)
|
||||
return own_client.call("POST", "/api/v1/users", [201, 409], body=registration)["status"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
results = list(pool.map(register, range(4)))
|
||||
check(results.count(201) == 1 and results.count(409) == 3, "registration race was not resolved by unique username")
|
||||
check(sql(f"SELECT count(*) FROM users WHERE username = '{username}';") == "1", "duplicate user rows")
|
||||
print("PASS: 4 concurrent registrations -> one 201, three 409, one PostgreSQL row")
|
||||
|
||||
alice, bob = client.user("rollback_a"), client.user("rollback_b")
|
||||
title = "rollback_" + uuid.uuid4().hex
|
||||
suffix = uuid.uuid4().hex[:12]
|
||||
trigger = "student_rollback_" + suffix
|
||||
function = "student_fail_member_" + suffix
|
||||
before = sql(f"SELECT count(*) FROM chat_members WHERE user_id IN ('{alice['id']}', '{bob['id']}');")
|
||||
try:
|
||||
# Failure on Bob's membership happens after the chat INSERT (and Alice's membership).
|
||||
# No fault-injection API or production code branch is added.
|
||||
sql(f"""
|
||||
CREATE FUNCTION {function}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.user_id = '{bob['id']}'::uuid AND
|
||||
EXISTS (SELECT 1 FROM chats WHERE id = NEW.chat_id AND title = '{title}') THEN
|
||||
RAISE EXCEPTION 'synthetic membership failure';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER {trigger} BEFORE INSERT ON chat_members
|
||||
FOR EACH ROW EXECUTE FUNCTION {function}();
|
||||
""")
|
||||
response = client.call("POST", "/api/v1/chats", 503, actor=alice,
|
||||
body={"title": title, "member_ids": [alice["id"], bob["id"]]})
|
||||
check(response["json"]["error"]["code"] == "unavailable", "database failure leaked internals")
|
||||
check(sql(f"SELECT count(*) FROM chats WHERE title = '{title}';") == "0", "partially created chat survived")
|
||||
check(sql(f"SELECT count(*) FROM chat_members WHERE user_id IN ('{alice['id']}', '{bob['id']}');") == before,
|
||||
"partially created memberships survived")
|
||||
finally:
|
||||
sql(f"DROP TRIGGER IF EXISTS {trigger} ON chat_members; DROP FUNCTION IF EXISTS {function}();")
|
||||
client.call("POST", "/api/v1/chats", 201, actor=alice,
|
||||
body={"title": title, "member_ids": [alice["id"], bob["id"]]}, schema="Chat")
|
||||
print("PASS: injected membership failure rolled back chat and membership inserts; normal retry succeeds")
|
||||
|
||||
key = "messenger:session:" + hashlib.sha256(alice["token"].encode("ascii")).hexdigest()
|
||||
ttl_before = int(redis("PTTL", key))
|
||||
check(ttl_before > 0, "login did not populate Redis with TTL")
|
||||
check("password" not in redis("GET", key).lower(), "password material leaked into cache")
|
||||
hits_before = stats_hits()
|
||||
for _ in range(3):
|
||||
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
hits_after = stats_hits()
|
||||
check(hits_after - hits_before >= 3, "authenticated requests did not read Redis")
|
||||
check(0 < int(redis("PTTL", key)) <= ttl_before, "cache access extended session TTL")
|
||||
redis("DEL", key)
|
||||
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
check(int(redis("PTTL", key)) > 0, "cache miss did not refill from PostgreSQL")
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
check(redis("EXISTS", key) == "0", "logout did not invalidate cache")
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=alice)
|
||||
print("PASS: Redis TTL, hits, miss refill and logout invalidation")
|
||||
|
||||
|
||||
def stats_hits():
|
||||
values = dict(line.split(":", 1) for line in redis("INFO", "stats").splitlines() if ":" in line)
|
||||
return int(values["keyspace_hits"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,72 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Additional black-box checks for the Lab2 authentication boundary."""
|
||||
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, check, run # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--check-expiry", action="store_true")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url)
|
||||
|
||||
username = "student_" + uuid.uuid4().hex[:12]
|
||||
password = "Длинный пароль с двоеточием: " + uuid.uuid4().hex
|
||||
registration = {"username": username, "display_name": "Проверка Lab2", "password": password}
|
||||
user = client.call("POST", "/api/v1/users", 201, body=registration, schema="User")["json"]
|
||||
check("password" not in user and "password_hash" not in user, "password leaked in User")
|
||||
client.call("POST", "/api/v1/users", 409, body=registration)
|
||||
client.call("POST", "/api/v1/users", 400, body={**registration, "unexpected": True})
|
||||
client.call("POST", "/api/v1/users", 400, body={**registration, "username": username + "\n"})
|
||||
client.call("POST", "/api/v1/users", 400, body={**registration, "password": "short"})
|
||||
client.call("POST", "/api/v1/users", 400, raw=b'{"username":',
|
||||
headers={"Content-Type": "application/json"})
|
||||
client.call("POST", "/api/v1/users", 400, raw=b'{}',
|
||||
headers={"Content-Type": "text/plain"})
|
||||
|
||||
def basic(secret):
|
||||
encoded = base64.b64encode((username + ":" + secret).encode("utf-8")).decode("ascii")
|
||||
return {"Authorization": "Basic " + encoded}
|
||||
|
||||
client.call("POST", "/api/v1/auth/sessions", 401, headers=basic("wrong password"))
|
||||
client.call("POST", "/api/v1/auth/sessions", 400, headers=basic(password), body={})
|
||||
session = client.call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers=basic(password), schema="Session")["json"]
|
||||
token = session["token"]
|
||||
check(token != password and username not in token, "token contains credentials")
|
||||
client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": user["id"]})
|
||||
client.call("GET", "/api/v1/users/me", 401, headers=basic(password))
|
||||
|
||||
actor = {"id": user["id"], "token": token}
|
||||
me = client.call("GET", "/api/v1/users/me", actor=actor, schema="User")["json"]
|
||||
check(me == user, "Bearer session resolved to a different user")
|
||||
client.call("POST", "/api/v1/chats", 400, actor=actor,
|
||||
body={"title": "Bad members", "member_ids": [user["id"], str(uuid.uuid4())]})
|
||||
|
||||
if args.check_expiry:
|
||||
from compose_helpers import redis
|
||||
key = "messenger:session:" + hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
check(0 < int(redis("PTTL", key)) <= 2000, "short-TTL session missing cache expiry")
|
||||
time.sleep(3)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
check(redis("EXISTS", key) == "0", "expired session remained in Redis")
|
||||
print("PASS: TTL=2 expires in PostgreSQL authentication and Redis cache")
|
||||
else:
|
||||
client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
|
||||
print("PASS: Lab2 password, Basic, Bearer, input validation and session lifecycle")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,304 @@
|
||||
"""Grade 5 track 2: skewed dataset, index trade-off, independent backup recovery."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from compose_helpers import ROOT, compose, sql
|
||||
from client import Client, check, run
|
||||
|
||||
SIZES = [80000, 15000, 4000, 1000]
|
||||
VARIANTS = {"chat_only": "(chat_id)", "keyset": "(chat_id, created_at, id)"}
|
||||
|
||||
|
||||
def now():
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
|
||||
|
||||
def statement_plan(statement):
|
||||
return json.loads(sql("EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) " + statement + ";", timeout=120))[0]
|
||||
|
||||
|
||||
def benchmark(chats):
|
||||
schema = "research_" + uuid.uuid4().hex
|
||||
ids = ",".join("'" + chat["id"] + "'" for chat in chats)
|
||||
results = {name: {"index": columns, "write_samples_ms": [], "read_plans": {}}
|
||||
for name, columns in VARIANTS.items()}
|
||||
try:
|
||||
sql(f"CREATE SCHEMA {schema};")
|
||||
for name, columns in VARIANTS.items():
|
||||
sql(f"""
|
||||
CREATE TABLE {schema}.{name} (
|
||||
id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES public.chats(id),
|
||||
sender_id uuid NOT NULL REFERENCES public.users(id), text text NOT NULL,
|
||||
created_at timestamptz NOT NULL);
|
||||
CREATE INDEX {name}_history_idx ON {schema}.{name} {columns};
|
||||
""")
|
||||
# One warm-up and three measured runs; alternate order to reduce order bias.
|
||||
for iteration in range(4):
|
||||
order = list(VARIANTS) if iteration % 2 == 0 else list(reversed(VARIANTS))
|
||||
for name in order:
|
||||
sql(f"TRUNCATE {schema}.{name};")
|
||||
plan = statement_plan(f"INSERT INTO {schema}.{name} SELECT * FROM public.messages WHERE chat_id IN ({ids}) ORDER BY created_at, id")
|
||||
check(int(sql(f"SELECT count(*) FROM {schema}.{name};")) == sum(SIZES), "benchmark row count mismatch")
|
||||
if iteration:
|
||||
results[name]["write_samples_ms"].append(plan["Execution Time"])
|
||||
results[name]["last_write_plan"] = plan
|
||||
print(f"Index insert run {iteration + 1}/4 completed", flush=True)
|
||||
for name in VARIANTS:
|
||||
table = f"{schema}.{name}"
|
||||
sql(f"ANALYZE {table};")
|
||||
queries = {
|
||||
"large_first": (chats[0]["id"], None),
|
||||
"large_after_75000": (chats[0]["id"], 75000),
|
||||
"small_after_500": (chats[3]["id"], 500),
|
||||
}
|
||||
for scenario, (chat_id, anchor_number) in queries.items():
|
||||
condition = f"chat_id = '{chat_id}'::uuid"
|
||||
if anchor_number:
|
||||
anchor_id = hashlib.md5(f"{chat_id}:{anchor_number}".encode()).hexdigest()
|
||||
condition += f" AND (created_at, id) > ('2026-01-01T00:00:00Z'::timestamptz + {anchor_number} * interval '1 millisecond', '{anchor_id}'::uuid)"
|
||||
query = f"SELECT id, chat_id, sender_id, text, created_at FROM {table} WHERE {condition} ORDER BY created_at, id LIMIT 51"
|
||||
statement_plan(query) # warm-up not included in the reported samples
|
||||
plans = [statement_plan(query) for _ in range(5)]
|
||||
check(all(plan["Plan"]["Actual Rows"] == 51 for plan in plans), "read query page size mismatch")
|
||||
median = statistics.median(plan["Execution Time"] for plan in plans)
|
||||
representative = min(plans, key=lambda plan: abs(plan["Execution Time"] - median))
|
||||
results[name]["read_plans"][scenario] = {
|
||||
"query": query, "samples_ms": [plan["Execution Time"] for plan in plans],
|
||||
"median_ms": median, "explain_analyze_buffers": representative}
|
||||
results[name]["write_median_ms"] = statistics.median(results[name]["write_samples_ms"])
|
||||
results[name]["history_index_bytes"] = int(sql(f"SELECT pg_relation_size('{schema}.{name}_history_idx');"))
|
||||
results[name]["table_and_indexes_bytes"] = int(sql(f"SELECT pg_total_relation_size('{table}');"))
|
||||
print(f"{name}: INSERT median {results[name]['write_median_ms']:.3f} ms, deep page median {results[name]['read_plans']['large_after_75000']['median_ms']:.3f} ms", flush=True)
|
||||
return results
|
||||
finally:
|
||||
# Only this run's generated schema is removed; public application data is retained.
|
||||
sql(f"DROP SCHEMA IF EXISTS {schema} CASCADE;")
|
||||
|
||||
|
||||
def manifest(chats, service="postgres", database="messenger"):
|
||||
ids = ",".join("'" + chat["id"] + "'" for chat in chats)
|
||||
tables = ["users", "chats", "chat_members", "messages", "sessions", "schema_migrations"]
|
||||
counts = {table: int(sql(f"SELECT count(*) FROM public.{table};", service, database)) for table in tables}
|
||||
digest = sql(f"SELECT md5(string_agg(row_to_json(m)::text, E'\\n' ORDER BY id)) FROM public.messages m WHERE chat_id IN ({ids});", service, database, timeout=120)
|
||||
selected = []
|
||||
for chat, size in zip(chats, SIZES):
|
||||
sample_ids = [hashlib.md5(f"{chat['id']}:{number}".encode()).hexdigest() for number in (1, size // 2, size)]
|
||||
values = ",".join("'" + value + "'::uuid" for value in sample_ids)
|
||||
selected.extend(json.loads(sql(f"SELECT json_agg(row_to_json(m) ORDER BY id) FROM public.messages m WHERE id IN ({values});", service, database)))
|
||||
return {"table_counts": counts, "fixture_digest_md5": digest, "selected_messages": selected}
|
||||
|
||||
|
||||
def mounted_volume(service):
|
||||
container = compose("ps", "-q", service)
|
||||
result = subprocess.run(["docker", "inspect", container, "--format", "{{json .Mounts}}"],
|
||||
text=True, capture_output=True, check=True)
|
||||
return next(mount["Name"] for mount in json.loads(result.stdout)
|
||||
if mount["Destination"] == "/var/lib/postgresql/data")
|
||||
|
||||
|
||||
def backup_restore(client, actor, chats, run_id):
|
||||
expected = manifest(chats)
|
||||
folder = ROOT / "backups"
|
||||
folder.mkdir(mode=0o700, exist_ok=True)
|
||||
dump_path = folder / ("lab2-" + run_id + ".dump")
|
||||
backup_started_at = now()
|
||||
started = time.monotonic()
|
||||
descriptor = os.open(dump_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
||||
with os.fdopen(descriptor, "wb") as destination:
|
||||
result = subprocess.run(["docker", "compose", "exec", "-T", "postgres", "pg_dump",
|
||||
"-U", "messenger", "-d", "messenger", "-Fc", "--schema=public"],
|
||||
cwd=ROOT, stdout=destination, stderr=subprocess.PIPE, timeout=180)
|
||||
check(result.returncode == 0, "pg_dump failed; inspect local stack")
|
||||
backup_seconds = time.monotonic() - started
|
||||
backup_finished_at = now()
|
||||
check(manifest(chats) == expected, "source changed during backup; rerun without concurrent writes")
|
||||
marker = client.message(actor, chats[-1], "Подтверждённая запись после backup " + run_id)["json"]
|
||||
print(f"Backup created ({dump_path.stat().st_size} bytes); post-backup marker committed", flush=True)
|
||||
|
||||
started = time.monotonic()
|
||||
compose("--profile", "research", "up", "-d", "--wait", "--wait-timeout", "90", "postgres-restore", timeout=120)
|
||||
bootstrap_seconds = time.monotonic() - started
|
||||
source_volume, destination_volume = mounted_volume("postgres"), mounted_volume("postgres-restore")
|
||||
check(source_volume != destination_volume, "restore must use independent storage")
|
||||
database = "restored_" + run_id
|
||||
compose("exec", "-T", "postgres-restore", "createdb", "-U", "messenger", "-T", "template0", database)
|
||||
check(sql("SELECT count(*) FROM information_schema.tables WHERE table_schema = 'public';", "postgres-restore", database) == "0",
|
||||
"restore target must start empty")
|
||||
# template0 includes an empty public schema; the schema-filtered dump creates it.
|
||||
# Remove only that empty schema in the newly created restore database.
|
||||
sql("DROP SCHEMA public;", "postgres-restore", database)
|
||||
started = time.monotonic()
|
||||
with dump_path.open("rb") as source:
|
||||
result = subprocess.run(["docker", "compose", "exec", "-T", "postgres-restore", "pg_restore",
|
||||
"-U", "messenger", "-d", database, "--no-owner", "--no-privileges",
|
||||
"--exit-on-error", "--single-transaction"], cwd=ROOT, stdin=source,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, timeout=180)
|
||||
check(result.returncode == 0, "pg_restore failed; inspect the local restore database")
|
||||
restore_seconds = time.monotonic() - started
|
||||
started = time.monotonic()
|
||||
restored = manifest(chats, "postgres-restore", database)
|
||||
check(restored == expected, "restored counts, full fixture digest or selected messages differ")
|
||||
check(sql(f"SELECT count(*) FROM messages WHERE id = '{marker['id']}';", "postgres-restore", database) == "0",
|
||||
"post-backup marker unexpectedly entered the dump")
|
||||
check(sql(f"SELECT count(*) FROM messages WHERE id = '{marker['id']}';") == "1", "source marker missing")
|
||||
verification_seconds = time.monotonic() - started
|
||||
print(f"PASS: independent restore verified; pg_restore {restore_seconds:.3f} s; post-backup marker is absent as expected", flush=True)
|
||||
return {"backup_started_at": backup_started_at, "backup_finished_at": backup_finished_at,
|
||||
"backup_seconds": backup_seconds, "backup_bytes": dump_path.stat().st_size,
|
||||
"backup_file": str(dump_path.relative_to(ROOT)), "bootstrap_seconds": bootstrap_seconds,
|
||||
"pg_restore_seconds": restore_seconds, "verification_seconds": verification_seconds,
|
||||
"source_volume": source_volume, "restored_volume": destination_volume,
|
||||
"restored_database": database, "target_initial_public_table_count": 0,
|
||||
"manifest": expected, "restored_manifest_matches": True,
|
||||
"post_backup_marker": {"id": marker["id"], "created_at": marker["created_at"],
|
||||
"present_in_source": True, "present_in_restore": False},
|
||||
"snapshot_constraint": "no concurrent application writes during manifest/dump comparison; pg_dump provides its own consistent snapshot",
|
||||
"loss_boundary": "restore includes dump snapshot only; later confirmed writes require a newer backup or WAL/PITR"}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url, timeout=20)
|
||||
run_id = uuid.uuid4().hex[:16]
|
||||
actor = client.user("research")
|
||||
chats = [client.call("POST", "/api/v1/chats", 201, actor=actor,
|
||||
body={"title": f"Research {run_id}: {size}", "member_ids": [actor["id"]]}, schema="Chat")["json"]
|
||||
for size in SIZES]
|
||||
for chat, size in zip(chats, SIZES):
|
||||
sql(f"""
|
||||
INSERT INTO messages(id, chat_id, sender_id, text, created_at)
|
||||
SELECT md5('{chat['id']}:' || n::text)::uuid, '{chat['id']}'::uuid, '{actor['id']}'::uuid,
|
||||
'research ' || n::text || ' ' || repeat('message ', 4 + n % 12),
|
||||
'2026-01-01T00:00:00Z'::timestamptz + n * interval '1 millisecond'
|
||||
FROM generate_series(1, {size}) fixture(n);
|
||||
""", timeout=120)
|
||||
check(int(sql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat['id']}';")) == size, "fixture distribution mismatch")
|
||||
print("Dataset: 100000 messages in chats of 80000 / 15000 / 4000 / 1000", flush=True)
|
||||
experiments = benchmark(chats)
|
||||
environment = json.loads(sql("SELECT json_build_object('server_version', current_setting('server_version'), 'shared_buffers', current_setting('shared_buffers'), 'work_mem', current_setting('work_mem'), 'fsync', current_setting('fsync'), 'synchronous_commit', current_setting('synchronous_commit'));"))
|
||||
recovery = backup_restore(client, actor, chats, run_id)
|
||||
evidence = {"verified_at": now(), "track": 2,
|
||||
"hypothesis": "(chat_id, created_at, id) should reduce ordered keyset reads in a large chat compared to (chat_id), at a larger index size and possible insertion cost",
|
||||
"distribution": SIZES, "fixture_messages": sum(SIZES),
|
||||
"method": {"write_runs": "1 warm-up + 3 measured; alternate variant order; same PK/FK and 100000 rows",
|
||||
"read_runs": "1 warm-up + 5 measured per scenario; median PostgreSQL Execution Time",
|
||||
"timing_scope": "SQL INSERT includes index and FK work; excludes commit/HTTP latency; warm buffers, one local Docker host"},
|
||||
"environment": environment, "indexes": experiments, "recovery": recovery}
|
||||
output = ROOT / "evidence" / "research-track2.json"
|
||||
output.parent.mkdir(exist_ok=True)
|
||||
output.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n")
|
||||
write_report(evidence)
|
||||
print("PASS: grade 5 track 2 completed; evidence/research-track2.json", flush=True)
|
||||
|
||||
|
||||
def write_report(evidence):
|
||||
a, b = evidence["indexes"]["chat_only"], evidence["indexes"]["keyset"]
|
||||
recovery = evidence["recovery"]
|
||||
speedup = a["read_plans"]["large_after_75000"]["median_ms"] / b["read_plans"]["large_after_75000"]["median_ms"]
|
||||
write_change = (b["write_median_ms"] / a["write_median_ms"] - 1) * 100
|
||||
rows = []
|
||||
for scenario in a["read_plans"]:
|
||||
rows.append(f"| {scenario} | {a['read_plans'][scenario]['median_ms']:.3f} | {b['read_plans'][scenario]['median_ms']:.3f} |")
|
||||
counts = "\n".join(f"| {table} | {count} | {count} |" for table, count in recovery["manifest"]["table_counts"].items())
|
||||
text = f"""# Уровень 5 - трек 2: SQL и восстановление
|
||||
|
||||
Проверено: {evidence['verified_at']}. Полные планы, отдельные измерения и manifest: [research-track2.json](../evidence/research-track2.json). Лог всех проверок: [grade5-checks.txt](../evidence/grade5-checks.txt).
|
||||
|
||||
## Гипотеза
|
||||
|
||||
Составной индекс `(chat_id, created_at, id)` ускоряет чтение упорядоченной страницы истории, особенно после глубокого cursor в большом чате. Дополнительные ключи увеличивают размер индекса и могут увеличить стоимость вставки.
|
||||
|
||||
## Повторяемая методика
|
||||
|
||||
```sh
|
||||
make up
|
||||
make verify-grade5
|
||||
# Только исследование, если уровни 3/4 уже проверены:
|
||||
make research-grade5
|
||||
```
|
||||
|
||||
Скрипт `student-tests/research_track2.py` создаёт нового пользователя и четыре чата через API, затем вставляет SQL-командами 100 000 синтетических сообщений: 80 000 / 15 000 / 4 000 / 1 000. Тексты имеют разные размеры, время назначено на фиксированной временной шкале. Каждый запуск создаёт отдельный набор; существующие данные сохраняются.
|
||||
|
||||
В отдельной временной схеме создаются две таблицы с одинаковыми UUID PK, FK на пользователей/чаты и теми же 100 000 сообщениями. У первой индекс `(chat_id)`, у второй `(chat_id, created_at, id)`. Индексы рабочей таблицы API не меняются. Временная схема удаляется в finally.
|
||||
|
||||
Для INSERT выполняются один прогрев и три замера с чередованием порядка вариантов; перед каждым таблица очищается TRUNCATE. `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` измеряет серверное выполнение INSERT, включая обслуживание индексов и FK. COMMIT и HTTP в это время не входят. Для чтения - ANALYZE, один прогрев и пять измерений каждого запроса; приведена медиана `Execution Time`.
|
||||
|
||||
Страницы используют реальный набор колонок и keyset-условие API, ORDER BY created_at, id и LIMIT 51. Исследованы первая страница большого чата, страница после 75 000-й записи и после 500-й записи малого чата. Никакие enable_seqscan/другие настройки planner не отключаются.
|
||||
|
||||
Окружение PostgreSQL: `{evidence['environment']['server_version']}`, shared_buffers `{evidence['environment']['shared_buffers']}`, work_mem `{evidence['environment']['work_mem']}`, fsync `{evidence['environment']['fsync']}`, synchronous_commit `{evidence['environment']['synchronous_commit']}`. Один локальный Docker Desktop на macOS; buffers прогреты.
|
||||
|
||||
## Результаты
|
||||
|
||||
| Чтение, медиана ms | Индекс chat_id | Составной индекс |
|
||||
| --- | ---: | ---: |
|
||||
{chr(10).join(rows)}
|
||||
|
||||
| Запись и хранение | Индекс chat_id | Составной индекс |
|
||||
| --- | ---: | ---: |
|
||||
| INSERT 100 000, медиана ms | {a['write_median_ms']:.3f} | {b['write_median_ms']:.3f} |
|
||||
| Размер индекса, bytes | {a['history_index_bytes']} | {b['history_index_bytes']} |
|
||||
| Таблица с индексами, bytes | {a['table_and_indexes_bytes']} | {b['table_and_indexes_bytes']} |
|
||||
|
||||
Глубокая страница в этом прогоне ускорилась в **{speedup:.1f} раза**. Изменение медианного времени INSERT составило **{write_change:+.1f}%**. Полные планы показывают выбранный scan, условия индекса, сортировку, фактические строки и buffer hits; данные позволяют проверить причину результата.
|
||||
|
||||
Составной индекс соответствует запросу API: равенство по chat_id задаёт первый ключ, пара created_at/id задаёт границу cursor и порядок. Выбранный индекс оставлен в миграции API. Число и времена локального прогона не являются универсальной характеристикой сервера; повторные измерения меняются с нагрузкой и состоянием caches.
|
||||
|
||||
## Backup → новое хранилище → сверка
|
||||
|
||||
Использован pg_dump PostgreSQL 17 в custom-формате (`-Fc --schema=public`) и pg_restore (`--no-owner --no-privileges --exit-on-error --single-transaction`). Dump включает всю public-схему приложения: пользователей, чаты, членство, сообщения, сессии и версии миграций. Во время сравнения manifest и dump другие записи API должны быть остановлены; pg_dump сам получает согласованный snapshot.
|
||||
|
||||
Backup: `{recovery['backup_file']}`, {recovery['backup_bytes']} bytes. Файл имеет права 0600; папка backups/ игнорируется Git и Docker build. Его содержимое включает password/session hashes, поэтому в Git сохраняются только обезличенные результаты проверки.
|
||||
|
||||
Цель - отдельный Compose-сервис postgres-restore (profile research), PostgreSQL 17.6, volume `{recovery['restored_volume']}`; источник использует `{recovery['source_volume']}`. Каждый запуск создаёт новую пустую БД `{recovery['restored_database']}`. До восстановления public-таблиц: 0. Пустая public-схема, созданная template0, удаляется только в этой новой БД перед восстановлением schema dump.
|
||||
|
||||
| Таблица | В snapshot | После restore |
|
||||
| --- | ---: | ---: |
|
||||
{counts}
|
||||
|
||||
Также совпали {len(recovery['manifest']['selected_messages'])} выбранных сообщений (начало/середина/конец каждого чата) и MD5 канонического содержимого всех 100 000 сообщений исследуемого набора: `{recovery['manifest']['fixture_digest_md5']}`. MD5 здесь - checksum синтетического набора для сверки, password KDF остаётся Argon2id.
|
||||
|
||||
| Этап | Время, s |
|
||||
| --- | ---: |
|
||||
| pg_dump и запись файла | {recovery['backup_seconds']:.3f} |
|
||||
| Запуск/ожидание контейнера восстановления | {recovery['bootstrap_seconds']:.3f} |
|
||||
| pg_restore | {recovery['pg_restore_seconds']:.3f} |
|
||||
| Сверка manifest и границы snapshot | {recovery['verification_seconds']:.3f} |
|
||||
|
||||
Время bootstrap при повторном запуске учитывает уже существующий контейнер; отдельная восстановленная БД всё равно новая и пустая. Это измерения отдельных этапов локального восстановления. Полный production RTO дополнительно включает обнаружение отказа, доставку backup, переключение API, проверку и эксплуатационные действия.
|
||||
|
||||
## Граница потери данных
|
||||
|
||||
После завершения dump через API подтверждено ещё одно сообщение `{recovery['post_backup_marker']['id']}`. Оно есть в источнике и отсутствует в восстановленной БД. Это показывает границу snapshot: успешные записи после снимка не входят в данный backup.
|
||||
|
||||
RPO определяется возрастом последнего доступного согласованного backup. Без архивирования WAL/PITR более поздние записи этим dump не восстанавливаются. В этом эксперименте показана одна такая подтверждённая запись; число потерь при реальном отказе зависит от активности и частоты backup.
|
||||
|
||||
## Ограничения
|
||||
|
||||
Один локальный хост, фиксированный набор из четырёх чатов, прогретые buffers, три замера вставки и пять чтений. Вставка SQL-пакетом отличается от одиночных HTTP-запросов; COMMIT/HTTP/Argon2 не входят в её замер. Восстановление логического dump не моделирует повреждение диска, failover или PITR. Redis - восстанавливаемый кэш; его RAM не входит в backup. API после restore в этом эксперименте не переключается: исходный стенд продолжает работать, цель проверяется SQL-сверкой.
|
||||
|
||||
После эксперимента контейнер восстановления можно остановить: `docker compose --profile research stop postgres-restore`. Его volume и dump остаются для защиты. Основные API/Redis/PostgreSQL продолжают работу.
|
||||
|
||||
## Первичные источники
|
||||
|
||||
- [PostgreSQL: составные индексы](https://www.postgresql.org/docs/17/indexes-multicolumn.html).
|
||||
- [PostgreSQL: EXPLAIN](https://www.postgresql.org/docs/17/using-explain.html).
|
||||
- [PostgreSQL: pg_dump](https://www.postgresql.org/docs/17/app-pgdump.html).
|
||||
- [PostgreSQL: pg_restore](https://www.postgresql.org/docs/17/app-pgrestore.html).
|
||||
- [PostgreSQL: SQL dump и snapshot](https://www.postgresql.org/docs/17/backup-dump.html).
|
||||
"""
|
||||
path = ROOT / "docs" / "RESEARCH.md"
|
||||
path.parent.mkdir(exist_ok=True)
|
||||
path.write_text(text)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,50 @@
|
||||
"""UI history must page backwards while the required API keeps ascending semantics."""
|
||||
import argparse
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from compose_helpers import sql
|
||||
from client import Client, check, run, shape
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
path = "/api/ui/chats/" + chat["id"] + "/messages"
|
||||
client.call("GET", path, 401)
|
||||
client.call("GET", path, 404, actor=eve)
|
||||
members_path = "/api/ui/chats/" + chat["id"] + "/members"
|
||||
client.call("GET", members_path, 401)
|
||||
client.call("GET", members_path, 404, actor=eve)
|
||||
members = json.loads(client.call("GET", members_path, actor=bob)["bytes"])["items"]
|
||||
check({user["id"] for user in members} == {alice["id"], bob["id"]}, "wrong UI member list")
|
||||
for member in members:
|
||||
shape(member, "User") # rejects any password/hash fields in this projection
|
||||
prefix = uuid.uuid4().hex[:20]
|
||||
# Equal timestamps exercise the UUID tie-breaker in both directions.
|
||||
sql(f"""
|
||||
INSERT INTO messages(id, chat_id, sender_id, text, created_at)
|
||||
SELECT ('{prefix}' || lpad(n::text, 12, '0'))::uuid,
|
||||
'{chat['id']}'::uuid, '{alice['id']}'::uuid, 'UI pagination ' || n,
|
||||
'2026-02-01T00:00:00Z'::timestamptz
|
||||
FROM generate_series(1, 75) fixture(n);
|
||||
""")
|
||||
check(int(sql(f"SELECT count(*) FROM messages WHERE chat_id = '{chat['id']}';")) == 75, "UI fixture mismatch")
|
||||
ascending = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=50", actor=alice, schema="MessagePage")["json"]
|
||||
recent = client.call("GET", path + "?limit=50", actor=bob, schema="MessagePage")["json"]
|
||||
older = client.call("GET", path + "?limit=50&cursor=" + recent["next_cursor"], actor=bob, schema="MessagePage")["json"]
|
||||
check([item["id"] for item in ascending["items"]] == sorted(item["id"] for item in ascending["items"]), "required history changed order")
|
||||
check([item["id"] for item in recent["items"]] == sorted((item["id"] for item in recent["items"]), reverse=True), "UI history is not newest first")
|
||||
all_items = recent["items"] + older["items"]
|
||||
check(len(all_items) == 75 and len({item["id"] for item in all_items}) == 75 and older["next_cursor"] is None,
|
||||
"UI pagination lost or repeated equal-time messages")
|
||||
client.call("GET", path + "?cursor=" + ascending["next_cursor"], 400, actor=alice)
|
||||
client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?cursor=" + recent["next_cursor"], 400, actor=alice)
|
||||
print("PASS: UI authentication, privacy, newest page, backwards pagination, cursor isolation; required API stays ascending")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user