Files
mtusi2026lab5/student-tests/test_history_plan.py
T

77 lines
2.7 KiB
Python

"""План запроса истории на >= 10 000 сообщений: индекс без Sort и полного скана."""
import json
from datetime import datetime
from uuid import UUID
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncEngine
from helpers import bearer, create_chat, create_user
HISTORY_QUERY = """
SELECT * FROM messages
WHERE chat_id = :chat_id AND (created_at, id) > (:after_created_at, :after_id)
ORDER BY created_at, id
LIMIT 51
"""
def walk(node: dict) -> list[dict]:
nodes = [node]
for child in node.get("Plans", []):
nodes.extend(walk(child))
return nodes
async def seed_messages(
engine: AsyncEngine, chat_id: str, sender_id: str, count: int
) -> None:
async with engine.begin() as connection:
await connection.execute(
text("""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
SELECT gen_random_uuid(), :chat_id, :sender_id, 'message ' || g,
now() - make_interval(secs => :count - g)
FROM generate_series(1, :count) AS g
"""),
{"chat_id": chat_id, "sender_id": sender_id, "count": count},
)
await connection.execute(text("ANALYZE messages"))
async def test_history_page_uses_composite_index(client, db_engine: AsyncEngine):
alice = await create_user(client)
target = await create_chat(client, alice, title="target")
noise = await create_chat(client, alice, title="noise")
await seed_messages(db_engine, target["id"], alice["id"], 10_000)
await seed_messages(db_engine, noise["id"], alice["id"], 10_000)
middle = (
await client.get(
f"/api/v1/chats/{target['id']}/messages?limit=100", headers=bearer(alice)
)
).json()["items"][-1]
async with db_engine.connect() as connection:
raw_plan = (
await connection.execute(
text(f"EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) {HISTORY_QUERY}"),
{
"chat_id": UUID(target["id"]),
"after_created_at": datetime.fromisoformat(middle["created_at"]),
"after_id": UUID(middle["id"]),
},
)
).scalar_one()
plan = (raw_plan if isinstance(raw_plan, list) else json.loads(raw_plan))[0]["Plan"]
nodes = walk(plan)
node_types = {node["Node Type"] for node in nodes}
index_names = {node.get("Index Name") for node in nodes}
assert "ix_messages_chat_id_created_at_id" in index_names
assert "Sort" not in node_types
assert "Seq Scan" not in node_types
assert all(node.get("Actual Rows", 0) <= 51 for node in nodes)