"""The history index really bounds the work of a late page (>= 10 000 messages, generic plan).""" from __future__ import annotations import re import sys import pytest from conftest import ROOT pytestmark = pytest.mark.stack sys.path.insert(0, str(ROOT / "scripts")) import explain_history # noqa: E402 def section(text: str, number: int) -> str: parts = re.split(r"^=== ", text, flags=re.M) return next(p for p in parts if p.startswith(f"{number}.")) def buffers(plan: str) -> int: return int(re.search(r"Buffers: shared hit=(\d+)", plan).group(1)) def test_late_page_uses_index_range_not_filter(): text = explain_history.run() assert "20000" in text # the target chat holds 20 000 messages app_late = section(text, 2) assert "Index Cond: ((chat_id = $1) AND (ROW(created_at, id) > ROW($2, $3)))" in app_late assert "Rows Removed by Filter" not in app_late and "Sort" not in app_late rejected = section(text, 3) assert "Rows Removed by Filter: 19950" in rejected # The app query touches a handful of pages; the rejected variants touch the whole prefix. assert buffers(app_late) <= 10 < buffers(rejected) and buffers(app_late) <= 10 < buffers(section(text, 4))