feat: collect cache and auth storage facts with driver commands
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -40,6 +40,16 @@
|
||||
разморозка, одно сообщение в чате, строка журнала PostgreSQL;
|
||||
триггер удаляется при любом исходе, в том числе по Ctrl+C,
|
||||
SIGTERM и SIGHUP; не удалось — печатается SQL удаления
|
||||
cache-check только стенд с LB: сценарии chat-cache «Чтение из кэша»,
|
||||
«Срок записи», «Временная база» — ключ карточки после
|
||||
создания чата, TTL и настроенный срок, 50 чтений через LB
|
||||
между снимками чтений таблицы chats и keyspace_hits Valkey,
|
||||
TTL не продлевается чтениями, ключи рабочей и тестовой базы
|
||||
(перед командой — make test_isolated); код 1 и нарушенный факт
|
||||
auth-storage только стенд с LB: сценарии sessions «Токена нет в
|
||||
хранилище» и users «Хэш в БД» — префиксы Argon2id и разные
|
||||
хэши одного пароля, token_hash = SHA-256 токена, ни токена,
|
||||
ни пароля в pg_dump; секреты не печатаются
|
||||
stop-at-start [--image ТЕГ] [--delays 0.2,0.3,0.4,1.5,5]
|
||||
[--server-start 3] docker stop контейнеров образа (лимиты
|
||||
реплики, без сети) во время старта: через паузу после
|
||||
@@ -69,10 +79,12 @@ import argparse
|
||||
import base64
|
||||
import contextlib
|
||||
import csv
|
||||
import hashlib
|
||||
import http.client
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import secrets
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -1201,6 +1213,321 @@ def hang_key(port: int) -> int:
|
||||
print(f"trigger {probe} removed", flush=True)
|
||||
|
||||
|
||||
# cache-check: начало ключа карточки — копия CACHE_KEY_PREFIX из
|
||||
# src/utils/constants.py, как в student-tests/fault_hook.py
|
||||
CACHE_KEY_PREFIX = "messenger:v1"
|
||||
# простаивающий backend PostgreSQL сбрасывает счётчики таблиц не сразу, а
|
||||
# до 10 с спустя (PGSTAT_IDLE_INTERVAL): снимок — через 11 с после запросов
|
||||
PGSTAT_WAIT_S = 11
|
||||
CACHE_READS = 50
|
||||
CACHE_TTL_READS = 10
|
||||
CHAT_CARD_KEYS = {"id", "title", "member_ids", "created_at"}
|
||||
# префикс строки Argon2id без соли: алгоритм, версия и параметры
|
||||
ARGON2_PREFIX_LEN = 31
|
||||
|
||||
|
||||
def short_name(username: str) -> str:
|
||||
return username.split("_", 1)[0] + "_…"
|
||||
|
||||
|
||||
def stand_psql(sql: str) -> str:
|
||||
"""psql в контейнере PostgreSQL рабочего стенда, SQL через stdin."""
|
||||
return compose("exec", "-T", "postgres", "sh", "-c", PSQL, stdin=sql)
|
||||
|
||||
|
||||
def stand_valkey(*args: str) -> str:
|
||||
"""valkey-cli рабочего стенда: пароль — VALKEYCLI_AUTH контейнера,
|
||||
аргументы — позиционные параметры sh, без подстановки в строку."""
|
||||
return compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"valkey",
|
||||
"sh",
|
||||
"-c",
|
||||
'exec valkey-cli -p "$VALKEY_PORT" "$@"',
|
||||
"sh",
|
||||
*args,
|
||||
).strip()
|
||||
|
||||
|
||||
def valkey_stats() -> tuple[int, int]:
|
||||
"""`keyspace_hits` и `keyspace_misses` из `INFO stats`."""
|
||||
values = {}
|
||||
for line in stand_valkey("INFO", "stats").splitlines():
|
||||
name, _, value = line.strip().partition(":")
|
||||
if name in ("keyspace_hits", "keyspace_misses"):
|
||||
values[name] = int(value)
|
||||
return values["keyspace_hits"], values["keyspace_misses"]
|
||||
|
||||
|
||||
def chats_reads() -> int:
|
||||
"""Чтения таблицы chats: `seq_scan + idx_scan` (`pg_stat_user_tables`)."""
|
||||
return int(
|
||||
stand_psql(
|
||||
"SELECT coalesce(seq_scan, 0) + coalesce(idx_scan, 0) "
|
||||
"FROM pg_stat_user_tables WHERE relname = 'chats';\n",
|
||||
).strip(),
|
||||
)
|
||||
|
||||
|
||||
def synthetic_user(
|
||||
port: int,
|
||||
prefix: str,
|
||||
password: str,
|
||||
) -> tuple[dict[str, object], str] | None:
|
||||
"""Регистрация и вход по Basic; (пользователь, токен) или None."""
|
||||
username = f"{prefix}_{uuid.uuid4().hex[:8]}"
|
||||
status, _, user = call(
|
||||
port,
|
||||
"POST",
|
||||
USERS,
|
||||
body={
|
||||
"username": username,
|
||||
"display_name": prefix.capitalize(),
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
if status != 201 or not isinstance(user, dict):
|
||||
print(f"register {prefix}: {status}")
|
||||
return None
|
||||
status, _, session = call(
|
||||
port,
|
||||
"POST",
|
||||
SESSIONS,
|
||||
authorization=basic(username, password),
|
||||
)
|
||||
if status != 201 or not isinstance(session, dict):
|
||||
print(f"login {prefix}: {status}")
|
||||
return None
|
||||
return user, session["token"]
|
||||
|
||||
|
||||
def cmd_cache_check(port: int) -> int:
|
||||
"""Сценарии `chat-cache` «Чтение из кэша», «Срок записи» и «Временная
|
||||
база» на стенде с LB (решение 1 design change `fix-known-issues`).
|
||||
|
||||
Между двумя снимками счётчиков — только `CACHE_READS` чтений карточки
|
||||
через LB: к ключу драйвер в это время не обращается (`EXISTS`, `TTL`
|
||||
и `GET` Valkey тоже считает в `keyspace_hits`). Ключ перед окном
|
||||
удаляется: первое чтение — промах и одно чтение `chats`. Во время
|
||||
команды на стенде не должно идти ничего другого: счётчики — всей
|
||||
таблицы и всего Valkey. Токены и пароли не печатаются, название чата
|
||||
тоже; пользователи и чат остаются в рабочей базе."""
|
||||
if no_lb(port):
|
||||
return 1
|
||||
password = f"Pw-cache-{uuid.uuid4().hex}"
|
||||
alice = synthetic_user(port, "alice", password)
|
||||
bob = synthetic_user(port, "bob", password)
|
||||
if alice is None or bob is None:
|
||||
return 1
|
||||
(alice_user, alice_token), (bob_user, bob_token) = alice, bob
|
||||
status, _, chat = call(
|
||||
port,
|
||||
"POST",
|
||||
CHATS,
|
||||
token=alice_token,
|
||||
body={
|
||||
"title": "Cache check",
|
||||
"member_ids": [bob_user["id"], alice_user["id"]],
|
||||
},
|
||||
)
|
||||
if status != 201 or not isinstance(chat, dict):
|
||||
print(f"create chat: {status}")
|
||||
return 1
|
||||
database = compose("exec", "-T", "postgres", "printenv", "POSTGRES_DB")
|
||||
database = database.strip()
|
||||
key = f"{CACHE_KEY_PREFIX}:{database}:chat:{chat['id']}"
|
||||
exists = stand_valkey("EXISTS", key)
|
||||
ttl0 = int(stand_valkey("TTL", key))
|
||||
replica = compose("ps", "-q", "api").split()[0]
|
||||
configured = int(
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"exec",
|
||||
replica,
|
||||
"python",
|
||||
"-c",
|
||||
"from src.config import settings; "
|
||||
"print(settings.cache.chat_ttl_seconds)",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
).stdout.strip(),
|
||||
)
|
||||
try:
|
||||
card = json.loads(stand_valkey("GET", key))
|
||||
except json.JSONDecodeError:
|
||||
card = None
|
||||
card_ok = (
|
||||
isinstance(card, dict)
|
||||
and set(card) == CHAT_CARD_KEYS
|
||||
and card["member_ids"] == chat["member_ids"]
|
||||
and card["id"] == chat["id"]
|
||||
)
|
||||
print(
|
||||
f"users {short_name(alice_user['username'])} (creator) and "
|
||||
f"{short_name(bob_user['username'])} (reader), chat {chat['id']}",
|
||||
)
|
||||
print(f"key {key}")
|
||||
print(
|
||||
f"right after 201: EXISTS {exists}, TTL {ttl0} s (configured "
|
||||
f"[cache] chat_ttl_seconds {configured} s in the replica); value "
|
||||
f"keys {sorted(card) if isinstance(card, dict) else '-'}, member_ids "
|
||||
f"in creation order: {'yes' if card_ok else 'no'}",
|
||||
)
|
||||
stand_valkey("DEL", key)
|
||||
print(f"DEL key: the first read is a miss; waiting {PGSTAT_WAIT_S} s")
|
||||
time.sleep(PGSTAT_WAIT_S)
|
||||
reads_before = chats_reads()
|
||||
hits_before, misses_before = valkey_stats()
|
||||
instances: Counter[str] = Counter()
|
||||
bad = 0
|
||||
path = f"{CHATS}/{chat['id']}"
|
||||
|
||||
def read() -> None:
|
||||
nonlocal bad
|
||||
status, hdrs, payload = call(port, "GET", path, token=bob_token)
|
||||
instances[hdrs.get("x-instance-id", "LB")] += 1
|
||||
bad += status != 200 or payload != chat
|
||||
|
||||
for _ in range(CACHE_READS):
|
||||
read()
|
||||
time.sleep(PGSTAT_WAIT_S)
|
||||
reads = chats_reads() - reads_before
|
||||
hits_after, misses_after = valkey_stats()
|
||||
hits, misses = hits_after - hits_before, misses_after - misses_before
|
||||
print(
|
||||
f"{CACHE_READS} × GET {CHATS}/{{id}} by the reader through LB: "
|
||||
f"{CACHE_READS - bad} equal to the creation response; by replica "
|
||||
+ ", ".join(f"{i} {n}" for i, n in sorted(instances.items())),
|
||||
)
|
||||
print(
|
||||
f"after {PGSTAT_WAIT_S} s: reads of table chats (seq_scan + "
|
||||
f"idx_scan) +{reads}, keyspace_hits +{hits}, keyspace_misses "
|
||||
f"+{misses}",
|
||||
)
|
||||
ttl_a = int(stand_valkey("TTL", key))
|
||||
for _ in range(CACHE_TTL_READS):
|
||||
read()
|
||||
ttl_b = int(stand_valkey("TTL", key))
|
||||
print(
|
||||
f"TTL {ttl_a} s, then {CACHE_TTL_READS} more reads, TTL {ttl_b} s: "
|
||||
f"reads {'do not extend' if ttl_b <= ttl_a else 'EXTEND'} the key",
|
||||
)
|
||||
counts = {}
|
||||
for name in (database, f"test_{database}"):
|
||||
pattern = f"{CACHE_KEY_PREFIX}:{name}:chat:*"
|
||||
keys = stand_valkey("--scan", "--pattern", pattern)
|
||||
counts[name] = len(keys.split())
|
||||
print(f"keys {pattern}: {counts[name]}")
|
||||
if not counts[f"test_{database}"]:
|
||||
print(
|
||||
"no keys of the test database: run make test_isolated before "
|
||||
"this command for the scenario «Временная база»",
|
||||
)
|
||||
problems = []
|
||||
if reads > 1:
|
||||
problems.append(f"table chats read {reads} times")
|
||||
if hits < CACHE_READS - 1 or misses > 1:
|
||||
problems.append(f"cache hits +{hits}, misses +{misses}")
|
||||
if bad:
|
||||
problems.append(f"{bad} reads differ from the creation response")
|
||||
if exists != "1" or not card_ok:
|
||||
problems.append("card is not written after commit as expected")
|
||||
if not 0 < ttl0 <= configured or not ttl_b <= ttl_a < ttl0:
|
||||
problems.append(f"TTL {ttl0} / {ttl_a} / {ttl_b} s")
|
||||
if len(instances) < 2:
|
||||
problems.append(f"{len(instances)} X-Instance-Id seen")
|
||||
if problems:
|
||||
print("FAIL: " + "; ".join(problems))
|
||||
return 1
|
||||
print("PASS: one read of chats, the rest from Valkey; TTL is bounded")
|
||||
return 0
|
||||
|
||||
|
||||
def cmd_auth_storage(port: int) -> int:
|
||||
"""Сценарии `sessions` «Токена нет в хранилище» и `users` «Хэш в БД»
|
||||
(решение 1 design change `fix-known-issues`).
|
||||
|
||||
Пароль P (синтетический, с `:` и кириллицей) и токен T живут только в
|
||||
памяти процесса. Печатаются факты, счётчики и префикс строки Argon2id
|
||||
до соли; дамп базы читается в память и никуда не пишется."""
|
||||
if no_lb(port):
|
||||
return 1
|
||||
password = f"Пароль:{secrets.token_urlsafe(18)}:ключ"
|
||||
first = synthetic_user(port, "auth", password)
|
||||
second = synthetic_user(port, "auth", password)
|
||||
if first is None or second is None:
|
||||
return 1
|
||||
(user1, token), (user2, _) = first, second
|
||||
names = (user1["username"], user2["username"])
|
||||
# username — синтетические [a-z0-9_], hex — безопасны в тексте SQL
|
||||
rows = stand_psql(
|
||||
"SELECT left(password_hash, "
|
||||
f"{ARGON2_PREFIX_LEN}), length(password_hash) FROM users "
|
||||
f"WHERE username IN ('{names[0]}', '{names[1]}') ORDER BY username;\n"
|
||||
"SELECT a.password_hash <> b.password_hash FROM users a, users b "
|
||||
f"WHERE a.username = '{names[0]}' AND b.username = '{names[1]}';\n",
|
||||
).splitlines()
|
||||
hashes = [row.split("|") for row in rows[:2]]
|
||||
differ = rows[2].strip() if len(rows) > 2 else "?"
|
||||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||||
session = stand_psql(
|
||||
"SELECT count(*), coalesce(max(octet_length(token_hash)), 0) "
|
||||
f"FROM sessions WHERE token_hash = decode('{digest}', 'hex');\n",
|
||||
).strip()
|
||||
count, length = (int(x) for x in session.split("|"))
|
||||
dump = compose(
|
||||
"exec",
|
||||
"-T",
|
||||
"postgres",
|
||||
"sh",
|
||||
"-c",
|
||||
'exec pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" --data-only',
|
||||
)
|
||||
blocks = sum(1 for line in dump.splitlines() if line.startswith("COPY "))
|
||||
token_text = token in dump
|
||||
token_hex = token.encode().hex() in dump
|
||||
password_text = password in dump
|
||||
print(
|
||||
f"users {short_name(names[0])} and {short_name(names[1])}: same "
|
||||
f"password P ({len(password)} characters with ':' and Cyrillic)",
|
||||
)
|
||||
# zip(strict=) — 3.10+, драйвер работает и на 3.9
|
||||
for prefix, size in hashes:
|
||||
print(f" password_hash {prefix}… ({size} chars)")
|
||||
print(f" hashes differ: {differ}")
|
||||
print(
|
||||
f"session of the first user: token T ({len(token)} characters); rows "
|
||||
f"of sessions with token_hash = SHA-256(T): {count}, "
|
||||
f"octet_length {length}",
|
||||
)
|
||||
print(
|
||||
f"pg_dump --data-only: {blocks} COPY blocks; T as text: "
|
||||
f"{'yes' if token_text else 'no'}, T in hex: "
|
||||
f"{'yes' if token_hex else 'no'}, P as text: "
|
||||
f"{'yes' if password_text else 'no'}",
|
||||
)
|
||||
problems = []
|
||||
if len(hashes) != 2 or any(
|
||||
not p.startswith("$argon2id$") for p, _ in hashes
|
||||
):
|
||||
problems.append("password_hash is not Argon2id")
|
||||
if differ != "t":
|
||||
problems.append("hashes of the same password are equal")
|
||||
if count != 1 or length != hashlib.sha256().digest_size:
|
||||
problems.append(f"sessions rows {count}, token_hash {length} bytes")
|
||||
if token_text or token_hex or password_text:
|
||||
problems.append("T or P found in the dump")
|
||||
if problems:
|
||||
print("FAIL: " + "; ".join(problems))
|
||||
return 1
|
||||
print("PASS: only Argon2id strings and SHA-256 of the token are stored")
|
||||
return 0
|
||||
|
||||
|
||||
# stop-at-start: записи журнала, по которым видны этапы старта и остановки
|
||||
STARTED_SERVER = "Started server process"
|
||||
SERVER_RUNNING = "Uvicorn running on"
|
||||
@@ -1551,6 +1878,8 @@ def main() -> int:
|
||||
# контейнер LB, если --port ведёт не на LB стенда (вариант конфигурации)
|
||||
idle.add_argument("--lb")
|
||||
sub.add_parser("hang-key")
|
||||
sub.add_parser("cache-check")
|
||||
sub.add_parser("auth-storage")
|
||||
stop = sub.add_parser("stop-at-start")
|
||||
stop.add_argument("--image", default="mtusi-messenger:lab3")
|
||||
stop.add_argument(
|
||||
@@ -1614,6 +1943,10 @@ def main() -> int:
|
||||
)
|
||||
if args.cmd == "hang-key":
|
||||
return cmd_hang_key(port)
|
||||
if args.cmd == "cache-check":
|
||||
return cmd_cache_check(port)
|
||||
if args.cmd == "auth-storage":
|
||||
return cmd_auth_storage(port)
|
||||
if args.cmd == "stop-at-start":
|
||||
return cmd_stop_at_start(
|
||||
args.image,
|
||||
|
||||
Reference in New Issue
Block a user