fix: require test database keys and tidy stop-at-start in the driver
cache-check gains --require-test-keys: without keys of the test database it fails instead of passing, and a plain PASS now says the temporary database was not checked. The coverage exclusion names the flag. auth-storage logs in only the first user, as the design says. stop-at-start installs its signal handlers right before the try that restores them and kills docker logs -f when reading is interrupted. The student-tests rule warns that copied evidence keeps the check green. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -40,12 +40,15 @@
|
||||
разморозка, одно сообщение в чате, строка журнала PostgreSQL;
|
||||
триггер удаляется при любом исходе, в том числе по Ctrl+C,
|
||||
SIGTERM и SIGHUP; не удалось — печатается SQL удаления
|
||||
cache-check только стенд с LB: сценарии chat-cache «Чтение из кэша»,
|
||||
«Срок записи», «Временная база» — ключ карточки после
|
||||
создания чата, TTL и настроенный срок, 50 чтений через LB
|
||||
между снимками чтений таблицы chats и keyspace_hits Valkey,
|
||||
TTL не продлевается чтениями, ключи рабочей и тестовой базы
|
||||
(перед командой — make test_isolated); код 1 и нарушенный факт
|
||||
cache-check [--require-test-keys] только стенд с LB: сценарии
|
||||
chat-cache «Чтение из кэша», «Срок записи», «Временная
|
||||
база» — ключ карточки после создания чата, TTL и настроенный
|
||||
срок, 50 чтений через LB между снимками чтений таблицы chats
|
||||
и keyspace_hits Valkey, TTL не продлевается чтениями, ключи
|
||||
рабочей и тестовой базы (перед командой — make
|
||||
test_isolated); код 1 и нарушенный факт. Без ключей тестовой
|
||||
базы — PASS с «temporary database: not checked», с
|
||||
--require-test-keys — код 1
|
||||
auth-storage только стенд с LB: сценарии sessions «Токена нет в
|
||||
хранилище» и users «Хэш в БД» — префиксы Argon2id и разные
|
||||
хэши одного пароля, token_hash = SHA-256 токена, ни токена,
|
||||
@@ -1270,19 +1273,18 @@ def chats_reads() -> int:
|
||||
)
|
||||
|
||||
|
||||
def synthetic_user(
|
||||
def register_user(
|
||||
port: int,
|
||||
prefix: str,
|
||||
password: str,
|
||||
) -> tuple[dict[str, object], str] | None:
|
||||
"""Регистрация и вход по Basic; (пользователь, токен) или None."""
|
||||
username = f"{prefix}_{uuid.uuid4().hex[:8]}"
|
||||
) -> dict[str, object] | None:
|
||||
"""Регистрация синтетического пользователя; тело `User` или None."""
|
||||
status, _, user = call(
|
||||
port,
|
||||
"POST",
|
||||
USERS,
|
||||
body={
|
||||
"username": username,
|
||||
"username": f"{prefix}_{uuid.uuid4().hex[:8]}",
|
||||
"display_name": prefix.capitalize(),
|
||||
"password": password,
|
||||
},
|
||||
@@ -1290,11 +1292,23 @@ def synthetic_user(
|
||||
if status != 201 or not isinstance(user, dict):
|
||||
print(f"register {prefix}: {status}")
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
def synthetic_user(
|
||||
port: int,
|
||||
prefix: str,
|
||||
password: str,
|
||||
) -> tuple[dict[str, object], str] | None:
|
||||
"""Регистрация и вход по Basic; (пользователь, токен) или None."""
|
||||
user = register_user(port, prefix, password)
|
||||
if user is None:
|
||||
return None
|
||||
status, _, session = call(
|
||||
port,
|
||||
"POST",
|
||||
SESSIONS,
|
||||
authorization=basic(username, password),
|
||||
authorization=basic(str(user["username"]), password),
|
||||
)
|
||||
if status != 201 or not isinstance(session, dict):
|
||||
print(f"login {prefix}: {status}")
|
||||
@@ -1302,10 +1316,15 @@ def synthetic_user(
|
||||
return user, session["token"]
|
||||
|
||||
|
||||
def cmd_cache_check(port: int) -> int:
|
||||
def cmd_cache_check(port: int, *, require_test_keys: bool) -> int:
|
||||
"""Сценарии `chat-cache` «Чтение из кэша», «Срок записи» и «Временная
|
||||
база» на стенде с LB (решение 1 design change `fix-known-issues`).
|
||||
|
||||
«Временная база» проверяется только при ключах `test_<db>` (перед
|
||||
командой — `make test_isolated`). С `require_test_keys` их отсутствие
|
||||
— FAIL, без него — PASS с пометкой «not checked»: доказательство
|
||||
сценария снимается с флагом.
|
||||
|
||||
Между двумя снимками счётчиков — только `CACHE_READS` чтений карточки
|
||||
через LB: к ключу драйвер в это время не обращается (`EXISTS`, `TTL`
|
||||
и `GET` Valkey тоже считает в `keyspace_hits`). Ключ перед окном
|
||||
@@ -1422,12 +1441,15 @@ def cmd_cache_check(port: int) -> int:
|
||||
keys = stand_valkey("--scan", "--pattern", pattern)
|
||||
counts[name] = len(keys.split())
|
||||
print(f"keys {pattern}: {counts[name]}")
|
||||
if not counts[f"test_{database}"]:
|
||||
test_keys = counts[f"test_{database}"]
|
||||
if not test_keys:
|
||||
print(
|
||||
"no keys of the test database: run make test_isolated before "
|
||||
"this command for the scenario «Временная база»",
|
||||
)
|
||||
problems = []
|
||||
if require_test_keys and not test_keys:
|
||||
problems.append("no keys of the test database (--require-test-keys)")
|
||||
if reads > 1:
|
||||
problems.append(f"table chats read {reads} times")
|
||||
if hits < CACHE_READS - 1 or misses > 1:
|
||||
@@ -1443,7 +1465,15 @@ def cmd_cache_check(port: int) -> int:
|
||||
if problems:
|
||||
print("FAIL: " + "; ".join(problems))
|
||||
return 1
|
||||
print("PASS: one read of chats, the rest from Valkey; TTL is bounded")
|
||||
temporary = (
|
||||
f"temporary database: {test_keys} keys under its own prefix"
|
||||
if test_keys
|
||||
else "temporary database: not checked, run make test_isolated first"
|
||||
)
|
||||
print(
|
||||
"PASS: one read of chats, the rest from Valkey; TTL is bounded; "
|
||||
+ temporary,
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
@@ -1457,11 +1487,12 @@ def cmd_auth_storage(port: int) -> int:
|
||||
if no_lb(port):
|
||||
return 1
|
||||
password = f"Пароль:{secrets.token_urlsafe(18)}:ключ"
|
||||
# вход только первого: второй нужен лишь для второго хэша того же P
|
||||
first = synthetic_user(port, "auth", password)
|
||||
second = synthetic_user(port, "auth", password)
|
||||
if first is None or second is None:
|
||||
user2 = register_user(port, "auth", password)
|
||||
if first is None or user2 is None:
|
||||
return 1
|
||||
(user1, token), (user2, _) = first, second
|
||||
user1, token = first
|
||||
names = (user1["username"], user2["username"])
|
||||
# username — синтетические [a-z0-9_], hex — безопасны в тексте SQL
|
||||
rows = stand_psql(
|
||||
@@ -1588,10 +1619,6 @@ def cmd_stop_at_start(image: str, delays: list[float], server: int) -> int:
|
||||
def interrupted(signum: int, _frame: object) -> None:
|
||||
raise KeyboardInterrupt(signal.Signals(signum).name)
|
||||
|
||||
previous = {
|
||||
signum: signal.signal(signum, interrupted)
|
||||
for signum in (signal.SIGTERM, signal.SIGHUP)
|
||||
}
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
label = f"{STOP_LABEL}={tag}"
|
||||
events_path = Path(f"/tmp/mtusi-stop-at-start-{tag}.events")
|
||||
@@ -1628,6 +1655,11 @@ def cmd_stop_at_start(image: str, delays: list[float], server: int) -> int:
|
||||
stdout=out,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
# обработчики ставятся прямо перед try: вернуть их может только finally
|
||||
previous = {
|
||||
signum: signal.signal(signum, interrupted)
|
||||
for signum in (signal.SIGTERM, signal.SIGHUP)
|
||||
}
|
||||
try:
|
||||
# CLI подключается к демону до первого контейнера
|
||||
time.sleep(1)
|
||||
@@ -1714,6 +1746,12 @@ def stop_attempt(
|
||||
for line in follow.stdout or []:
|
||||
if STARTED_SERVER in line:
|
||||
break
|
||||
except BaseException:
|
||||
# Ctrl+C или SIGTERM посреди чтения: docker logs -f не ждёт
|
||||
# уборки контейнера по метке
|
||||
follow.kill()
|
||||
follow.wait()
|
||||
raise
|
||||
finally:
|
||||
timer.cancel()
|
||||
began = time.monotonic()
|
||||
@@ -1878,7 +1916,12 @@ def main() -> int:
|
||||
# контейнер LB, если --port ведёт не на LB стенда (вариант конфигурации)
|
||||
idle.add_argument("--lb")
|
||||
sub.add_parser("hang-key")
|
||||
sub.add_parser("cache-check")
|
||||
cache = sub.add_parser("cache-check")
|
||||
cache.add_argument(
|
||||
"--require-test-keys",
|
||||
action="store_true",
|
||||
help="код 1 без ключей тестовой базы (сценарий «Временная база»)",
|
||||
)
|
||||
sub.add_parser("auth-storage")
|
||||
stop = sub.add_parser("stop-at-start")
|
||||
stop.add_argument("--image", default="mtusi-messenger:lab3")
|
||||
@@ -1944,7 +1987,10 @@ def main() -> int:
|
||||
if args.cmd == "hang-key":
|
||||
return cmd_hang_key(port)
|
||||
if args.cmd == "cache-check":
|
||||
return cmd_cache_check(port)
|
||||
return cmd_cache_check(
|
||||
port,
|
||||
require_test_keys=args.require_test_keys,
|
||||
)
|
||||
if args.cmd == "auth-storage":
|
||||
return cmd_auth_storage(port)
|
||||
if args.cmd == "stop-at-start":
|
||||
|
||||
Reference in New Issue
Block a user