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.

fix(data-warehouse): only warn on bad keyset plans for large tables (#109090)

Tom Owersaa8b62750804
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
index 887afc7dd00a..33a98d755e08 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/postgres.py
@@ -2539,6 +2539,10 @@ def _explain_query(cursor: psycopg.Cursor, query: sql.Composed, logger: Filterin
logger.debug(f"EXPLAIN raised an exception: {e}")
+KEYSET_PLAN_WARNING_MIN_ROWS = 100_000
+_PLAN_ROWS_ESTIMATE = re.compile(r"\brows=(\d+)")
+
+
def _check_keyset_page_plan(cursor: psycopg.Cursor, query: sql.Composed, logger: FilteringBoundLogger) -> None:
"""Warn when a keyset page is not reading an index in key order.
@@ -2561,8 +2565,22 @@ def _check_keyset_page_plan(cursor: psycopg.Cursor, query: sql.Composed, logger:
# Only the outermost node matters — a sort *under* a LIMIT is the per-page cost this looks for,
# and a seq scan means the key's index was not used at all.
problems = [marker for marker in ("Seq Scan", "Sort ", "Sort\n", "Incremental Sort") if marker in plan]
- if problems:
- logger.warning(f"Keyset page not served by an index scan in key order: reason=bad_keyset_plan found={problems}")
+ if not problems:
+ return
+
+ # The largest node estimate is the rows past the seek key, which is close to the whole table on
+ # the first seeking page. Below the threshold, a seq scan or a sort is the planner's correct choice
+ # and costs nothing per page. Warning there would bury the large tables this check exists for. A
+ # plan without estimates still warns, because it cannot show that the table is small.
+ estimated_rows = max((int(rows) for rows in _PLAN_ROWS_ESTIMATE.findall(plan)), default=None)
+ if estimated_rows is not None and estimated_rows < KEYSET_PLAN_WARNING_MIN_ROWS:
+ logger.debug(f"Keyset page plan uses {problems} on a small table: estimated_rows={estimated_rows}")
+ return
+
+ logger.warning(
+ f"Keyset page not served by an index scan in key order: reason=bad_keyset_plan "
+ f"found={problems} estimated_rows={estimated_rows}"
+ )
def _get_primary_keys(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
index c79ce509f0b6..508eda1126a2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/postgres/test_postgres.py
@@ -4636,20 +4636,46 @@ class TestCheckKeysetPagePlan:
"""The signal that says whether widening the seek is safe for a table."""
@pytest.mark.parametrize(
- "plan,warns",
+ "plan,warns,estimated_rows",
[
- ("Limit (cost=0.29..8.31 rows=2)\n -> Index Scan using companies_pkey on companies", False),
- ("Limit\n -> Index Only Scan using companies_pkey on companies", False),
+ ("Limit (cost=0.29..8.31 rows=2)\n -> Index Scan using companies_pkey on companies", False, None),
+ ("Limit\n -> Index Only Scan using companies_pkey on companies", False, None),
# A row filter pulled the planner onto another index, so the page cannot read in key
# order and sorts the matched set — once per page, not once per load.
- ("Limit\n -> Sort (cost=1.0..2.0)\n -> Index Scan using idx_status", True),
- ("Limit\n -> Incremental Sort\n -> Index Scan using idx_status", True),
+ ("Limit\n -> Sort (cost=1.0..2.0)\n -> Index Scan using idx_status", True, None),
+ ("Limit\n -> Incremental Sort\n -> Index Scan using idx_status", True, None),
# The key's index was not used at all.
- ("Limit\n -> Seq Scan on companies (cost=0.00..1.00)", True),
+ ("Limit\n -> Seq Scan on companies (cost=0.00..1.00)", True, None),
+ # On a small table a seq scan and a sort are the planner's correct choice, not a trap.
+ (
+ "Limit (cost=1.1..1.1 rows=4)\n -> Sort (cost=1.1..1.1 rows=4)\n"
+ " -> Seq Scan on companies (cost=0.00..1.05 rows=4)",
+ False,
+ None,
+ ),
+ ("Limit (rows=1000)\n -> Seq Scan on companies (rows=99999)", False, None),
+ ("Limit (rows=1000)\n -> Seq Scan on companies (rows=100000)", True, 100000),
+ # The page limit sits on the outer node, so the table size has to come from the largest estimate.
+ (
+ "Limit (cost=90.0..90.1 rows=1000)\n -> Sort (cost=90.0..95.0 rows=2500000)\n"
+ " -> Seq Scan on companies (cost=0.00..40.0 rows=2500000)",
+ True,
+ 2500000,
+ ),
+ ],
+ ids=[
+ "index_scan",
+ "index_only_scan",
+ "sort",
+ "incremental_sort",
+ "seq_scan",
+ "small_table_seq_scan_and_sort",
+ "just_below_threshold",
+ "at_threshold",
+ "large_table_sort",
],
- ids=["index_scan", "index_only_scan", "sort", "incremental_sort", "seq_scan"],
)
- def test_warns_only_when_the_page_is_not_an_index_scan_in_key_order(self, plan, warns):
+ def test_warns_only_when_the_page_is_not_an_index_scan_in_key_order(self, plan, warns, estimated_rows):
cursor = mock.MagicMock()
cursor.fetchall.return_value = [(line,) for line in plan.split("\n")]
logger = mock.MagicMock()
@@ -4657,6 +4683,8 @@ class TestCheckKeysetPagePlan:
_check_keyset_page_plan(cursor, sql.SQL("SELECT 1"), logger) # type: ignore[arg-type]
assert logger.warning.called is warns
+ if warns:
+ assert f"estimated_rows={estimated_rows}" in logger.warning.call_args.args[0]
def test_swallows_an_explain_failure(self):
# Diagnostics must never fail the page that follows.