Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions alembic/versions/20260819_025_drop_redundant_chat_id_index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
"""Drop idx_messages_chat_id - a strict prefix of two later composite indexes.

``idx_messages_chat_id`` (chat_id) has existed since 001 and, unlike every
other index on this table, carries no comment explaining what it serves.
Every access path that filters ``Message.chat_id`` on its own also orders or
bounds the result (by date, by id, or by is_pinned) and so already seeks
through ``idx_messages_chat_id_id`` (chat_id, id, added 017) or
``idx_messages_chat_date_desc`` (chat_id, date DESC, added 005) - both are a
superset of this index's leading column, so the planner can use either for a
bare chat_id predicate too. Checked every ``Message.chat_id ==`` /
``Message.chat_id.__eq__`` site in src/db/adapter.py (get_messages_paginated,
get_pinned_messages, toggle_pinned, delete_chat_messages, the per-day
export branches): none of them stop at chat_id alone without also ordering
or bounding by date/id/is_pinned.

Confirmed via ``pg_stat_user_indexes`` on a live ~385k-row archive:
``idx_messages_chat_id`` sat at 0 scans while ``idx_messages_chat_id_id`` and
``idx_messages_chat_date_desc`` carried hundreds of thousands between them -
the planner was already skipping the narrower index in favor of the
composites. Dropping it removes 3.2MB of on-disk index and one write on
every message insert, with no query plan depending on it.

Named explicitly rather than reflecting models.py, matching 024's rationale:
a migration has to keep meaning what it meant when it was written.
"""

from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "025"
down_revision: str | None = "024"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


TABLE_NAME = "messages"
INDEX_NAME = "idx_messages_chat_id"


def _index_exists(inspector: sa.Inspector) -> bool:
if TABLE_NAME not in inspector.get_table_names():
return False
return INDEX_NAME in {ix["name"] for ix in inspector.get_indexes(TABLE_NAME)}


def upgrade() -> None:
conn = op.get_bind()
if _index_exists(sa.inspect(conn)):
op.drop_index(INDEX_NAME, table_name=TABLE_NAME)


def downgrade() -> None:
conn = op.get_bind()
inspector = sa.inspect(conn)
if TABLE_NAME in inspector.get_table_names() and not _index_exists(inspector):
op.create_index(INDEX_NAME, TABLE_NAME, ["chat_id"])
1 change: 0 additions & 1 deletion src/db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,6 @@ class Message(Base):
__table_args__ = (
PrimaryKeyConstraint("account_id", "chat_id", "id"),
ForeignKeyConstraint(["account_id", "chat_id"], ["chats.account_id", "chats.id"], name="fk_messages_chat"),
Index("idx_messages_chat_id", "chat_id"),
Index("idx_messages_date", "date"),
Index("idx_messages_sender_id", "sender_id"),
# Composite index for fast pagination: WHERE chat_id = ? ORDER BY date DESC
Expand Down
128 changes: 128 additions & 0 deletions tests/test_migration_025.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
"""Tests for Alembic migration 025 (drop the redundant idx_messages_chat_id).

``idx_messages_chat_id`` (chat_id) is a strict prefix of both
``idx_messages_chat_id_id`` (chat_id, id) and ``idx_messages_chat_date_desc``
(chat_id, date DESC) - every access path that filters chat_id alone also
orders or bounds by id/date/is_pinned, so nothing plans against the narrower
index. These tests build a messages table with the redundant index present
and assert the migration drops it, leaves the other indexes alone, and that
downgrade puts it back (it is a real declared index up through 024; only 025
itself removes it from models.py).
"""

import importlib.util
import unittest
from collections.abc import Callable
from pathlib import Path
from types import ModuleType

import sqlalchemy as sa
from alembic.migration import MigrationContext
from alembic.operations import Operations
from sqlalchemy.engine import Connection

from src.db.models import Message

_MIGRATION_PATH = (
Path(__file__).resolve().parent.parent / "alembic" / "versions" / "20260819_025_drop_redundant_chat_id_index.py"
)

DROPPED = "idx_messages_chat_id"


def _load_migration() -> ModuleType:
spec = importlib.util.spec_from_file_location("migration_025", _MIGRATION_PATH)
if spec is None or spec.loader is None:
raise RuntimeError("Unable to load migration 025")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module


def _run(conn: Connection, func: Callable[[], None]) -> None:
context = MigrationContext.configure(conn)
with Operations.context(context):
func()


def _create_messages_table(conn: Connection, *, with_chat_id_index: bool) -> None:
conn.execute(
sa.text(
"CREATE TABLE messages (account_id BIGINT NOT NULL, chat_id BIGINT NOT NULL, "
"id BIGINT NOT NULL, date DATETIME NOT NULL, is_pinned INTEGER)"
)
)
# Unrelated / superset indexes, present in both shapes: the migration must leave them alone.
conn.execute(sa.text("CREATE INDEX idx_messages_date ON messages (date)"))
conn.execute(sa.text("CREATE INDEX idx_messages_chat_id_id ON messages (chat_id, id)"))
conn.execute(sa.text("CREATE INDEX idx_messages_chat_date_desc ON messages (chat_id, date DESC)"))
if with_chat_id_index:
conn.execute(sa.text("CREATE INDEX idx_messages_chat_id ON messages (chat_id)"))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved


def _indexes(conn: Connection) -> set[str]:
return {index["name"] for index in sa.inspect(conn).get_indexes("messages")}


class TestMigration025(unittest.TestCase):
def test_revision_chain(self) -> None:
migration = _load_migration()
self.assertEqual(migration.revision, "025")
self.assertEqual(migration.down_revision, "024")

def test_model_no_longer_declares_the_index(self) -> None:
"""The other half of this change: models.py must agree with 025."""
declared = {ix.name for ix in Message.__table__.indexes}
self.assertNotIn(DROPPED, declared)

def test_drops_the_redundant_index(self) -> None:
migration = _load_migration()
engine = sa.create_engine("sqlite://")
with engine.connect() as conn:
_create_messages_table(conn, with_chat_id_index=True)
self.assertIn(DROPPED, _indexes(conn))

_run(conn, migration.upgrade)

self.assertNotIn(DROPPED, _indexes(conn))
self.assertIn("idx_messages_date", _indexes(conn), "unrelated index must survive")
self.assertIn("idx_messages_chat_id_id", _indexes(conn), "superset index must survive")
self.assertIn("idx_messages_chat_date_desc", _indexes(conn), "superset index must survive")

def test_a_database_already_missing_it_is_untouched(self) -> None:
"""Idempotent: some databases never had it drift-restored by 024."""
migration = _load_migration()
engine = sa.create_engine("sqlite://")
with engine.connect() as conn:
_create_messages_table(conn, with_chat_id_index=False)
self.assertNotIn(DROPPED, _indexes(conn))

_run(conn, migration.upgrade)
_run(conn, migration.upgrade)

self.assertNotIn(DROPPED, _indexes(conn))

def test_downgrade_recreates_it(self) -> None:
migration = _load_migration()
engine = sa.create_engine("sqlite://")
with engine.connect() as conn:
_create_messages_table(conn, with_chat_id_index=True)
_run(conn, migration.upgrade)
self.assertNotIn(DROPPED, _indexes(conn))

_run(conn, migration.downgrade)

self.assertIn(DROPPED, _indexes(conn))
recreated = next(ix for ix in sa.inspect(conn).get_indexes("messages") if ix["name"] == DROPPED)
self.assertEqual(recreated["column_names"], ["chat_id"])

def test_no_messages_table_is_survivable(self) -> None:
migration = _load_migration()
engine = sa.create_engine("sqlite://")
with engine.connect() as conn:
_run(conn, migration.upgrade)
_run(conn, migration.downgrade)


if __name__ == "__main__":
unittest.main()
Loading