superset icon indicating copy to clipboard operation
superset copied to clipboard

[ccache] top_n_dashboards strategy does a full scan of `logs` on every run

Open jhorlima opened this issue 3 weeks ago • 3 comments

Bug description

Summary

The top_n_dashboards cache warm-up strategy runs a GROUP BY against the logs table on the metadata database on every execution, only to determine which dashboards are the top-N. On a large logs table this becomes the most expensive read in the instance, and it runs on a schedule.

The query

superset/tasks/cache.py, TopNDashboardsStrategy:

records = (
    db.session.query(Log.dashboard_id, func.count(Log.dashboard_id))
    .filter(and_(Log.dashboard_id.isnot(None), Log.dttm >= self.since))
    .group_by(Log.dashboard_id)
    .order_by(func.count(Log.dashboard_id).desc())
    .limit(self.top_n)
    .all()
)

Why the existing index doesn't help

logs has a composite index since 2.1.0 (migration cdcf3d64daf4):

ix_logs_user_id_dttm (user_id, dttm)

user_id is the leading column and is not part of the WHERE clause, so PostgreSQL cannot use it to satisfy dttm >= .... The planner falls back to a sequential scan.

superset/models/core.py declares no index on Log.dttm — only id as primary key.

Measured impact

Metric Value
logs rows 29.9M
Table size ~16 GB
Rows matching the 7-day window ~307k (1.0% of the table)
Blocks read the entire table

About 99% of the blocks read are discarded by the filter.

At crontab(minute='*/30') this ran 48 times per day. Reducing the schedule lowered total I/O but not the cost per execution: measured read_iops still peaks at ~3.3M/hour during a run, against ~0.5M baseline.

This also shows up as cost: the cluster runs Aurora Serverless v2, and capacity scales from ~1.5 to ~4.0 ACU during these reads.

Suggestion

Add an index that supports both the filter and the grouping:

CREATE INDEX CONCURRENTLY ix_logs_dttm_dashboard_id
    ON public.logs (dttm, dashboard_id);

(dttm) alone already solves the scan. Including dashboard_id makes it covering for this query — the column is both projected and grouped, so the planner can use an index-only scan instead of fetching ~307k heap tuples. The extra column costs almost nothing in storage.

Shipping it as a migration in the Log model would apply the fix to all deployments, not just those that notice the issue.

Workarounds available today

  • reduce warm-up frequency
  • prune the logs table with the built-in prune_logs task
  • create the index manually

Related

  • #16528 — same table, closed as unsupported version
  • #19532 — added ix_logs_user_id_dttm, which addressed recent_activity but not this query

Screenshots/recordings

No response

Superset version

master / latest-dev

Python version

I don't know

Node version

I don't know

Browser

Chrome

Additional context

No response

Checklist

  • [x] I have searched Superset docs and Slack and didn't find a solution to my problem.
  • [x] I have searched the GitHub issue tracker and didn't find a similar bug report.
  • [x] I have checked Superset's logs for errors and if I found a relevant Python stacktrace, I included it here as text in the "additional context" section.

jhorlima avatar Nov 10 '26 19:11 jhorlima

Hi @jhorlima! I'm Dosu and I'm helping the Apache Superset team.

Another related report is #46043, filed November 5: it describes the missing logs.dttm index causing expensive reads when opening the Activity Log, rather than during cache warm-up. That gives a second workload to consider when testing a shared indexing fix. [1]

There is also a workaround that avoids querying logs altogether: if a curated set of dashboards is acceptable, switch the warm-up task to dashboard_tags:

"kwargs": {
    "strategy_name": "dashboard_tags",
    "tags": ["warmup"],
},

Apply that tag to the dashboards you want warmed. DashboardTagsStrategy selects dashboards through Tag and TaggedObject, without the activity-log aggregation. This replaces popularity-based selection rather than preserving top-N behavior. [2]

To reply, just mention @dosu.


Share context across your team and agents. Try Dosu.

Leave Feedback Learn about superset with Dosu Add Dosu to your team

dosubot[bot] avatar Nov 10 '26 19:11 dosubot[bot]

Hi, I'd like to work on this. I'm planning to add a migration that creates an ix_logs_dttm_dashboard_id index on logs(dttm, dashboard_id) using the idempotent create_index helper, and declare it on the Log model, so the TopNDashboardsStrategy query and the dttm-filtered queries in LogDAO can use it.

schizophrenicmaniac avatar Nov 10 '26 20:11 schizophrenicmaniac

I measured this on Postgres 17 with master's schema (f7a0602271) and a 3M-row, 1.8 GB logs table written in time order (one year, about 63k rows in the last 7 days), running the exact statements Superset sends. #46043 has the same cause, and either open PR fixes both:

Query master #46046 (dttm) #46151 (dttm, dashboard_id)
Activity page (GET /api/v1/log/, dttm desc, 25 rows) parallel seq scan, 231k buffers, 455 ms index scan backward, 67 buffers, 0.2 ms index scan backward, 67 buffers, 0.1 ms
top_n_dashboards, 7 days bitmap scan of all of ix_logs_user_id_dttm, 19.6k buffers index scan, 5.0k buffers index-only scan, 248 buffers
same, last week not vacuumed yet index-only scan with 21.9k heap fetches, 5.1k buffers
prune select, little to delete 16.3k buffers 1.6k buffers 1.6k buffers

A few things I noticed:

  • On my box master's top-N reads the whole (user_id, dttm) index instead of the heap, but either way its cost grows with the table, not with the 7-day window.
  • dashboard_id only makes top-N index-only while last week's pages are all-visible, and in an append-only logs table they usually aren't: with the default autovacuum_vacuum_insert_scale_factor = 0.2, a 30M-row table gets an insert vacuum about every 6M rows. Until then #46151 does the same work as #46046.
  • The Activity page's count(*) stays a full index-only scan of logs_pkey (8.2k buffers) with either PR. That one's fine.
  • Both migrations upgrade and downgrade cleanly on Postgres 17, and both PRs' tests pass locally. #46151 builds the index CONCURRENTLY, like f72b6e9c104a does, so inserts into logs aren't blocked while it builds. #46046's plain CREATE INDEX blocks them, and nearly every request writes a log row.
  • Both revise b8f3a2c91d64, so only one can merge as is.

I'd merge one and close the other with a link. I lean to #46151 for the concurrent build, more than for the extra column.

Setup
INSERT INTO logs (action, user_id, dashboard_id, slice_id, json, dttm, duration_ms, referrer)
SELECT CASE WHEN r < 0.3 THEN 'log' WHEN r < 0.6 THEN 'ChartRestApi.data' ELSE 'DashboardRestApi.get' END,
       1 + g % 150,
       CASE WHEN r2 < 0.35 THEN (r3 * 200)::int END,
       CASE WHEN r < 0.6 THEN (r3 * 2000)::int END,
       '{"event_name": "x", "payload": "' || repeat(md5(g::text), 13) || '"}',
       timestamp '2025-11-17 15:00' + g * (interval '365 days' / 3000000),
       (r * 3000)::int,
       'http://superset.example/superset/dashboard/1/'
FROM (SELECT g, random() r, random() r2, random() r3 FROM generate_series(1, 3000000) g) s;
VACUUM ANALYZE logs;

Statements captured from log_min_duration_statement = 0 while calling GET /api/v1/log/?q=(order_column:dttm,order_direction:desc,page:0,page_size:25) and TopNDashboardsStrategy(top_n=5, since="7 days ago").get_urls(), then run with EXPLAIN (ANALYZE, BUFFERS). Each PR's index was added with its own superset db upgrade and removed with superset db downgrade.

bmuraykhi avatar Nov 17 '26 20:11 bmuraykhi