Реализовать лабораторную работу 2

This commit is contained in:
2026-10-18 15:53:16 +03:00
parent 65003b6119
commit be7a90132b
48 changed files with 1921 additions and 23 deletions
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env python3
"""Seed one synthetic 10k-message chat and show the indexed keyset query plan."""
import asyncio
from datetime import datetime, timezone
from pathlib import Path
import sys
import uuid
import asyncpg
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from app.core.config import settings
async def main() -> None:
pool = await asyncpg.create_pool(
settings.resolved_database_url(),
min_size=1,
max_size=2,
command_timeout=settings.db_command_timeout_seconds,
)
user_id, chat_id = uuid.uuid4(), uuid.uuid4()
username = 'explain_' + uuid.uuid4().hex[:12]
base_time = datetime(2026, 1, 1, tzinfo=timezone.utc)
try:
async with pool.acquire() as connection:
async with connection.transaction():
await connection.execute(
'INSERT INTO users (id, username, display_name, password_hash) '
'VALUES ($1, $2, $3, $4)',
user_id, username, 'EXPLAIN fixture', 'not-a-login-hash',
)
await connection.execute(
'INSERT INTO chats (id, title) VALUES ($1, $2)',
chat_id, 'EXPLAIN 10k fixture',
)
await connection.execute(
'INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)',
chat_id, user_id,
)
await connection.execute(
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) "
"SELECT md5($1::text || ':' || n::text)::uuid, $1::uuid, $2::uuid, "
"'synthetic explain message ' || n, $3::timestamptz + n * interval '1 microsecond' "
'FROM generate_series(1, 10000) AS g(n)',
str(chat_id), str(user_id), base_time,
)
await connection.execute('ANALYZE messages')
total = await connection.fetchval(
'SELECT count(*) FROM messages WHERE chat_id = $1', chat_id
)
plan = await connection.fetch(
'EXPLAIN (ANALYZE, BUFFERS) '
'SELECT id, created_at, sender_id, text FROM messages '
'WHERE chat_id = $1 AND (created_at, id) > ($2, $3) '
'ORDER BY created_at, id LIMIT 50',
chat_id, base_time, uuid.UUID(int=0),
)
rendered = '\n'.join(row['QUERY PLAN'] for row in plan)
print(f'chat_id={chat_id}; messages_in_fixture={total}')
print(rendered)
if total < 10000:
raise RuntimeError('EXPLAIN fixture did not reach 10,000 messages')
if 'messages_history_idx' not in rendered:
raise RuntimeError('planner did not choose messages_history_idx; inspect the plan')
finally:
await pool.close()
if __name__ == '__main__':
asyncio.run(main())
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
set -eu
# Restart API and both state stores while preserving their named volumes.
cd "$(dirname "$0")/.."
docker compose restart postgres redis api
+26
View File
@@ -0,0 +1,26 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
restore_default_api() {
docker compose --env-file .env up -d --force-recreate api >/dev/null
}
trap restore_default_api EXIT INT TERM
docker compose --env-file .env -f compose.yaml -f compose.grade4.yaml up -d --build --force-recreate api
make check
python3 tests/grade4.py
restore_default_api
trap - EXIT INT TERM
for attempt in $(seq 1 30); do
if curl -fsS "http://localhost:${APP_PORT:-8080}/health/ready" >/dev/null 2>&1; then
break
fi
sleep 1
done
mkdir -p evidence
docker compose --env-file .env exec -T api python scripts/explain_history.py > evidence/explain-history.txt
cat evidence/explain-history.txt
make test
make test-persistence ACTION_SCRIPT=scripts/restart.sh