Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(visual-review): let the absorbed-row read skip exact matches (#104935)

Julian Bez2468fe6c1e9f
diff --git a/posthog/migration_helpers/concurrent_index.py b/posthog/migration_helpers/concurrent_index.py
index 65a90c7058a0..538dfaaeb52a 100644
--- a/posthog/migration_helpers/concurrent_index.py
+++ b/posthog/migration_helpers/concurrent_index.py
@@ -57,7 +57,8 @@ The Migration class still needs `atomic = False`.
"""
from django.contrib.postgres.operations import AddIndexConcurrently, RemoveIndexConcurrently
-from django.db import migrations
+from django.db import migrations, router
+from django.db.backends.base.schema import BaseDatabaseSchemaEditor
import structlog
@@ -157,6 +158,11 @@ class _ConcurrentIndexOp(migrations.RunSQL):
using: str
where: str
+ def _allow_migrate(self, app_label: str, schema_editor: BaseDatabaseSchemaEditor) -> bool:
+ # The same router check `RunSQL` makes, which the overridden apply path would skip.
+ # Without it a product app routed to its own database runs this on every database.
+ return router.allow_migrate(schema_editor.connection.alias, app_label, **self.hints)
+
def deconstruct(self) -> tuple[str, list[object], dict[str, str | bool]]:
# RunSQL.deconstruct() emits sql=/reverse_sql= kwargs, which this op's
# keyword-only __init__ rejects — so squashmigrations / the migration
@@ -222,12 +228,16 @@ class CreateIndexConcurrently(_ConcurrentIndexOp):
)
def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ if not self._allow_migrate(app_label, schema_editor):
+ return
_disable_timeouts(schema_editor)
if _index_validity(schema_editor, self.index_name) == "invalid":
_log_and_drop_invalid_index(schema_editor, self.index_name, type(self).__name__)
schema_editor.execute(self.sql) # CREATE ... IF NOT EXISTS
def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ if not self._allow_migrate(app_label, schema_editor):
+ return
_disable_timeouts(schema_editor)
schema_editor.execute(self.reverse_sql)
@@ -286,10 +296,14 @@ class DropIndexConcurrently(_ConcurrentIndexOp):
)
def database_forwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ if not self._allow_migrate(app_label, schema_editor):
+ return
_disable_timeouts(schema_editor)
schema_editor.execute(self.sql)
def database_backwards(self, app_label, schema_editor, from_state, to_state) -> None:
+ if not self._allow_migrate(app_label, schema_editor):
+ return
_disable_timeouts(schema_editor)
if _index_validity(schema_editor, self.index_name) == "invalid":
_log_and_drop_invalid_index(schema_editor, self.index_name, type(self).__name__)
diff --git a/posthog/migration_helpers/test_concurrent_index.py b/posthog/migration_helpers/test_concurrent_index.py
index cbee9db77f58..d01e232352c1 100644
--- a/posthog/migration_helpers/test_concurrent_index.py
+++ b/posthog/migration_helpers/test_concurrent_index.py
@@ -9,8 +9,9 @@ with anything else in the schema.
import uuid
import pytest
+from unittest.mock import patch
-from django.db import connection, migrations, models
+from django.db import connection, migrations, models, router
from django.db.migrations.state import ModelState, ProjectState
from posthog.migration_helpers import (
@@ -189,6 +190,21 @@ def test_drop_index_concurrently_is_idempotent(temp_table):
assert not _index_exists(idx_name)
[email protected]_db(transaction=True)
[email protected]("op_cls,index_present", [(CreateIndexConcurrently, False), (DropIndexConcurrently, True)])
+def test_raw_ops_skip_a_database_the_router_excludes(temp_table, op_cls, index_present):
+ idx_name = f"{temp_table}_col_idx"
+ if index_present:
+ with connection.cursor() as cursor:
+ cursor.execute(f'CREATE INDEX "{idx_name}" ON "{temp_table}" (col)')
+ op = op_cls(index_name=idx_name, table_name=temp_table, columns="(col)")
+
+ with patch.object(router, "allow_migrate", return_value=False):
+ _apply(op)
+
+ assert _index_exists(idx_name) == index_present
+
+
@pytest.mark.django_db(transaction=True)
def test_subclasses_runsql_for_introspection_compatibility():
"""Subclasses must remain RunSQL so makemigrations / sqlmigrate continue to work."""
diff --git a/products/visual_review/backend/logic/baseline_overview.py b/products/visual_review/backend/logic/baseline_overview.py
index 49ed77389bbb..c2086a8430e5 100644
--- a/products/visual_review/backend/logic/baseline_overview.py
+++ b/products/visual_review/backend/logic/baseline_overview.py
@@ -252,7 +252,7 @@ def _baseline_change_counts_by_key(repo_id: UUID) -> dict[SnapshotKey, int]:
the new YAML baseline), so this count IS the number of times the YAML moved.
"Ever" reaches back as far as retention keeps default-branch runs, which is
`retention.DEFAULT_BRANCH_RUN_RETENTION_DAYS`. Postgres uses the
- `snapshot_run_result` index on (run_id, result) to bitmap-scan straight to
+ `snapshot_run_result_reason` index on (run_id, result) to bitmap-scan straight to
the rare event rows (~1k of millions). No window function, no per-row LAG
comparison.
"""
diff --git a/products/visual_review/backend/logic/flakiness.py b/products/visual_review/backend/logic/flakiness.py
index 03ecd5eaef0b..5d848fc534c4 100644
--- a/products/visual_review/backend/logic/flakiness.py
+++ b/products/visual_review/backend/logic/flakiness.py
@@ -65,7 +65,14 @@ _HARD = Q(result__in=(SnapshotResult.CHANGED, SnapshotResult.NEW, SnapshotResult
# would drive `headroom` to zero and label a snapshot somebody already signed
# off on as `at_risk`. `BELOW_THRESHOLD` needs no such filter: only the
# threshold path writes it.
-_SOFT = Q(result=SnapshotResult.UNCHANGED) & (
+#
+# The `__in` repeats what the OR below already implies. Postgres only uses a
+# column to bound an index scan from a plain equality or IN, so without it the
+# read walks every exact match in the run to reach the absorbed rows.
+_SOFT = Q(
+ result=SnapshotResult.UNCHANGED,
+ classification_reason__in=(ClassificationReason.BELOW_THRESHOLD, ClassificationReason.TOLERATED_HASH),
+) & (
Q(classification_reason=ClassificationReason.BELOW_THRESHOLD)
| Q(
classification_reason=ClassificationReason.TOLERATED_HASH,
@@ -147,7 +154,7 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:
- 1 values-only query for the current baseline hash per identifier
- 1 grouped query for the rate span's run count per run type
- 1 grouped query for hard activity per identity and day, which the
- `snapshot_run_result` index serves because non-unchanged rows are rare
+ `snapshot_run_result_reason` index serves because non-unchanged rows are rare
- 1 grouped query for variant count and mean diff
- 1 grouped query for soft activity per identity and day, bounded to the
identifiers that can produce a row
@@ -218,7 +225,7 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:
# to the activity reads as a list of run ids. A join on the run instead lets
# the planner scan the whole snapshot table, which holds every repo's
# history; anchored on run ids, the reads are index-only scans of
- # `snapshot_run_result_covering`, one range per run.
+ # `snapshot_run_result_reason`, one range per run.
strip_start = today - timedelta(days=FLAKINESS_WINDOW_DAYS - 1)
rate_start = today - timedelta(days=FLAKINESS_RATE_DAYS - 1)
window_run_ids = list(
@@ -317,7 +324,7 @@ def get_flakiness_overview(repo_id: UUID) -> _FlakinessRaw:
# Grouping the whole history by `baseline_hash` instead would read more
# precisely, but it admits every historical row rather than the rare event
# rows, which is the shape `baseline_overview` documents as ~7s and an OOM
- # on the web pod. This uses the `snapshot_run_result` index the same way its
+ # on the web pod. This uses the `snapshot_run_result_reason` index the same way its
# neighbour does. The history it reads reaches back only as far as retention
# keeps default-branch runs, which is
# `retention.DEFAULT_BRANCH_RUN_RETENTION_DAYS`.
diff --git a/products/visual_review/backend/migrations/0019_runsnapshot_snapshot_run_result_reason.py b/products/visual_review/backend/migrations/0019_runsnapshot_snapshot_run_result_reason.py
new file mode 100644
index 000000000000..b70af51ef5c9
--- /dev/null
+++ b/products/visual_review/backend/migrations/0019_runsnapshot_snapshot_run_result_reason.py
@@ -0,0 +1,52 @@
+import django.db.models.deletion
+from django.db import migrations, models
+
+from posthog.migration_helpers import DropIndexConcurrently, SafeAddIndexConcurrently, SafeRemoveIndexConcurrently
+
+
+class Migration(migrations.Migration):
+ atomic = False
+
+ dependencies = [
+ ("visual_review", "0018_runsnapshot_snapshot_run_result_covering"),
+ ]
+
+ # The new index starts with the same (run, result) key as the one it replaces, so every query
+ # that used the old one can use the new one. It is built before the old one is dropped.
+ operations = [
+ SafeAddIndexConcurrently(
+ model_name="runsnapshot",
+ index=models.Index(
+ fields=["run", "result", "classification_reason"],
+ include=["review_state", "identifier", "diff_percentage", "tolerated_hash_match", "team_id"],
+ name="snapshot_run_result_reason",
+ ),
+ ),
+ SafeRemoveIndexConcurrently(
+ model_name="runsnapshot",
+ name="snapshot_run_result_covering",
+ ),
+ # The foreign key's own index duplicates the leading column of the indexes above and of
+ # the unique (run, identifier) constraint.
+ migrations.SeparateDatabaseAndState(
+ state_operations=[
+ migrations.AlterField(
+ model_name="runsnapshot",
+ name="run",
+ field=models.ForeignKey(
+ db_index=False,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="snapshots",
+ to="visual_review.run",
+ ),
+ ),
+ ],
+ database_operations=[
+ DropIndexConcurrently(
+ index_name="visual_review_runsnapshot_run_id_e4e3613d",
+ table_name="visual_review_runsnapshot",
+ columns="(run_id)",
+ ),
+ ],
+ ),
+ ]
diff --git a/products/visual_review/backend/migrations/0020_runsnapshot_autovacuum_scale_factor.py b/products/visual_review/backend/migrations/0020_runsnapshot_autovacuum_scale_factor.py
new file mode 100644
index 000000000000..d3a5a2388e53
--- /dev/null
+++ b/products/visual_review/backend/migrations/0020_runsnapshot_autovacuum_scale_factor.py
@@ -0,0 +1,34 @@
+from django.db import migrations
+
+# The table inherits the global scale factors, 0.2 for inserts and 0.1 for dead tuples. At its row
+# count autovacuum then waits days between passes, and until a pass runs the recently written pages
+# are not all-visible. Those are the pages the flakiness reads cover, so their index-only scans fall
+# back to a heap fetch per row. 0.02 matches the other tuned product tables. An insert-triggered pass
+# has no dead tuples to clean from the indexes, so it costs little more than the heap pages it visits.
+#
+# SET (...) takes SHARE UPDATE EXCLUSIVE, which does not conflict with the snapshot writes.
+TABLE = "visual_review_runsnapshot"
+SCALE_FACTOR = 0.02
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("visual_review", "0019_runsnapshot_snapshot_run_result_reason"),
+ ]
+
+ operations = [
+ migrations.RunSQL(
+ sql=[
+ # Fail fast rather than queue: this waits behind an in-progress autovacuum
+ # on the same table, and a retry is cheaper than holding the lock request.
+ "SET LOCAL lock_timeout = '5s'",
+ f"ALTER TABLE {TABLE} SET ("
+ f"autovacuum_vacuum_scale_factor = {SCALE_FACTOR}, "
+ f"autovacuum_vacuum_insert_scale_factor = {SCALE_FACTOR})",
+ ],
+ reverse_sql=[
+ "SET LOCAL lock_timeout = '5s'",
+ f"ALTER TABLE {TABLE} RESET (autovacuum_vacuum_scale_factor, autovacuum_vacuum_insert_scale_factor)",
+ ],
+ ),
+ ]
diff --git a/products/visual_review/backend/migrations/max_migration.txt b/products/visual_review/backend/migrations/max_migration.txt
index beb6ed480b2f..d03272084482 100644
--- a/products/visual_review/backend/migrations/max_migration.txt
+++ b/products/visual_review/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0018_runsnapshot_snapshot_run_result_covering
+0020_runsnapshot_autovacuum_scale_factor
diff --git a/products/visual_review/backend/models.py b/products/visual_review/backend/models.py
index 37904e8b69ba..c95e01c28312 100644
--- a/products/visual_review/backend/models.py
+++ b/products/visual_review/backend/models.py
@@ -198,7 +198,8 @@ class RunSnapshot(ProductTeamModel):
# nosemgrep: prefer-uuid7-django-pk -- TODO: migrate to uuid7 (UUIDModel)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
- run = models.ForeignKey(Run, on_delete=models.CASCADE, related_name="snapshots")
+ # No index of its own: every index on this table that starts with the run serves those lookups.
+ run = models.ForeignKey(Run, on_delete=models.CASCADE, related_name="snapshots", db_index=False)
identifier = models.CharField(max_length=512)
@@ -293,18 +294,18 @@ class RunSnapshot(ProductTeamModel):
]
indexes = [
# Covering, so the flakiness reads (a run's rows by result, filtered on reason, team and
- # identifier) are index-only scans instead of reads of the whole table.
+ # identifier) are index-only scans instead of reads of the whole table. The reason is in
+ # the key so the absorbed-row read skips the exact matches, which are most of a run.
models.Index(
- fields=["run", "result"],
+ fields=["run", "result", "classification_reason"],
include=[
- "classification_reason",
"review_state",
"identifier",
"diff_percentage",
"tolerated_hash_match",
"team_id",
],
- name="snapshot_run_result_covering",
+ name="snapshot_run_result_reason",
),
models.Index(fields=["run", "review_state"], name="snapshot_run_review_state"),
models.Index(fields=["identifier"], name="snapshot_identifier"),