Repository navigation
fix(db): drop redundant idx_messages_chat_id index #316
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
GeiserX
merged 2 commits into
GeiserX:main
from
jordanfelle:fix/drop-redundant-messages-chat-id-index
Aug 19, 2026
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
59 changes: 59 additions & 0 deletions
59
alembic/versions/20260819_025_drop_redundant_chat_id_index.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"]) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)")) | ||
|
|
||
|
|
||
| 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() | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.