Skip to content

[Bug]: SHOW ACCOUNTS storage usage lookup is O(total tables) — QueryTableStatsByAccounts scans all mo_tables ids, 20–40s at ~673k tables #31388

Closed

Description

@loveRhythm1990

Is there an existing issue for the same bug?

  • I have checked the existing issues.

Searched for show accounts slow, show accounts storage usage, QueryTableStatsByAccounts, ShowAccountsLong, mo_table_stats show accounts. Closest related items, none of which is a duplicate:

Branch Name

v4.2.1-hotfix (tag v4.2.1-hotfix-20261026, the build running in production). The same code is present unchanged on main.

Commit ID

47e644f

Other Environment Information

  • A production MO cluster with 1882 accounts and about 673,600 tables (from the table-count field in the CN log).
  • The CN running the StorageUsage cron task has CPU limit 3.75 and memory limit about 61 GiB. The Go runtime runs with 4 Ps. The live heap after GC is about 10–17 GB.
  • The StorageUsage cron task runs SHOW ACCOUNTS; once every round (about every 5 minutes on this cluster).

Actual Behavior

SHOW ACCOUNTS (all accounts, issued as the sys account) takes 20–40 s. The cost grows linearly with the total number of tables in the cluster. Almost all of the time goes to the MTS size lookup that getAccountsStorageUsage runs unconditionally.

1. Where the time goes (metric mo_task_short_duration_seconds, per phase)

phase (type=) typical
show_accounts_get_table_stats ~0.2 s
show_accounts_get_storage_usage 20–28 s, with outliers up to 39.7 s
show_accounts_total_duration ≈ get_storage_usage

Hourly mean of get_storage_usage over 7 days: about 17 s rising to 21–23 s. The table count grew over the same period. On this cluster the platform alert ShowAccountsLong (p99 > 30 s) fired on several days in the last 30 days.

2. Per-round breakdown from the CN log

QueryTableStatsByAccounts logs its own duration:

"msg":"mo.table.stats.task","action":"query.table.stats.by.accounts","account-count":1882,"table-count":673618,"force-update":false,"reset-update-time":false,"takes":"39.679380215s","ok":true

The two SQL phases below were derived from timestamps of consecutive log lines in the same round:

  • start next round
  • the txn.table.ranges.log line for mo_table_stats_alpha
  • the query.table.stats.by.accounts line
round start (UTC) phase 1: mo_tables id scan phase 2: mo_table_stats lookup + decode total takes
03:18:08 22.5 s 5.1 s 26.4 s
03:23:36 19.4 s 3.9 s 22.7 s
03:28:59 21.6 s 3.8 s 24.8 s
03:34:25 20.3 s 4.0 s 23.6 s
03:50:43 19.9 s 4.5 s 23.6 s
03:56:08 24.9 s 3.8 s 28.0 s
04:01:36 34.8 s 5.6 s 39.7 s
04:07:17 20.8 s 4.3 s 24.2 s

The txn.table.ranges.log line itself shows the stats-table ranges step costing only 40–600 ms. That step is not the bottleneck.

3. Code path (line numbers verified at 47e644f2d7)

pkg/frontend/show_account.go

  • doShowAccounts → getAccountsStorageUsage (:444). The duration is observed at :610 as show_accounts_get_storage_usage.
  • getAccountsStorageUsage registers a defer (:455). After the TN storage-usage RPC or cache step, on success it always calls tryGetSizeFromMTS(ctx, eng, accIds) (:460) to overwrite size.
  • tryGetSizeFromMTS (:378) passes every account id to de.QueryTableStatsByAccounts(...) (:414). For the all-accounts case, forceUpdate is false.

pkg/vm/engine/disttae/mo_table_stats.go

  • QueryTableStatsByAccounts (:1261) formats accumulateIdsByAccSQL (:220):
    select account_id, reldatabase_id, rel_id from mo_catalog.mo_tables where account_id in (<all 1882 account ids>);
    It then calls queryTableStatsByXXX (:1237). That function decodes all ~673k rows into three []uint64 slices via decodeIdsFromMOTablesSqlRet (:2110).
  • QueryTableStats (:1374) → normalQuery (:1156) joins those slices back into strings and runs getTableStatsSQL (:111):
    select table_id, update_time, COALESCE(table_stats, CAST('{}' AS JSON)) from mo_catalog.mo_table_stats
    where account_id in (<1882 ids>) and database_id in (<~673k ids>) and table_id in (<~673k ids>)
    order by table_id asc;
    The SQL text is several MB.
  • For each of the ~673k result rows, the code does a sort.Find over the returned ids and then json.Unmarshals the whole table_stats JSON into a map[string]any (:1221). From that map it reads a single field, table_size.
  • tryGetSizeFromMTS finally sums those sizes per account in Go.

So, to produce 1882 numbers (one size per account), every round:

  • moves about 673k catalog rows into the CN,
  • builds two IN lists of about 673k elements each and a multi-MB SQL string,
  • unmarshals about 673k JSON documents into maps.

The work is O(total tables). It does not depend on how many tables actually changed.

4. Side effect: GC pressure, with a tail-latency outlier (strongly correlated, not proven)

The 39.7 s round (04:01:36–04:02:17) overlaps three back-to-back GC cycles on that CN (GODEBUG=gctrace):

04:01:40  0.34+6581+0.078 ms clock  19498->22859->14614 MB
04:01:54  0.23+7678+0.023 ms clock  23623->28444->17242 MB
04:02:15  0.17+3500+0.020 ms clock  27356->29765->13972 MB

Outside this window, GC mark phases are 2–4 s. Whether this query is what pushed the heap from about 19.5 GB to 29.7 GB is not verified: the CN serves other workloads too, and no heap profile was captured. A smaller heap bump also appears at the start of other rounds (for example 03:56:09–03:56:24, 19.7→22.7 GB). That is consistent with this query allocating several GB per round, but it is analysis only, not field-observed.

5. Headroom against hard limits

CalculateStorageUsage wraps the statement in context.WithTimeoutCause(ctx, time.Minute, ...) (pkg/util/metric/mometric/cron_task.go:256). At about 21–28 s typical and 39.7 s worst case today, with linear growth in table count, the task will start failing at the 60 s timeout once the cluster has somewhat more tables or a worse GC pause. When it fails, the round errors out and storage-usage metrics go stale.

Impact today: limited. Customer queries are unaffected. The visible effects are:

  • storage-usage metric staleness of up to about 40 s per round,
  • a platform alert on show accounts latency,
  • periodic multi-second GC pauses on whichever CN runs the task (suspected).

Expected Behavior

  • The per-account size lookup for SHOW ACCOUNTS should not need to move every table id in the cluster into the CN and back out as IN lists.
  • Its cost should be roughly proportional to the number of accounts, or to the number of tables changed since the last round, rather than to the total number of tables.
  • It should stay well below the 60 s task timeout as the cluster grows.

Steps to Reproduce

Analysis-level reproduction (no special fault injection needed):

1. Create a cluster with many tables spread across many accounts.
   For example, ~2,000 accounts with ~300 tables each (≈600k tables in total).
   The production cluster has 1882 accounts / ~673k tables.
2. As sys, run `SHOW ACCOUNTS;`, or wait for the `StorageUsage` cron task to run.
3. Observe:
   - `mo_task_short_duration_seconds{type="show_accounts_get_storage_usage"}`.
   - The CN log line `mo.table.stats.task ... action=query.table.stats.by.accounts ... takes=...`.
4. Increase the table count and repeat. `takes` grows roughly linearly with
   `table-count`, independent of how many tables actually changed.

Expected from code reading: almost all of the time is in
`QueryTableStatsByAccounts` (mo_tables id scan + mo_table_stats IN-list
query + per-row JSON unmarshal), not in the TN storage-usage RPC.

Additional information

Evidence strength

  • Measured: per-phase metrics; takes / account-count / table-count from the CN log; the phase-1/phase-2 split from log timestamps; the 7-day trend; the gctrace lines.
  • Strongly correlated, not proven: the 04:01 outlier coinciding with the GC storm.
  • Not verified: how the about 20 s of phase 1 splits between SQL execution, result materialization, and decodeIdsFromMOTablesSqlRet. No CPU or heap profile was captured. A 673k-row scan of mo_tables taking about 20 s may itself be worth a look.

Possible directions (for discussion, not prescriptive)

  1. Aggregate in SQL instead of in Go. For example, join mo_tables with mo_table_stats on (account_id, database_id, table_id) and GROUP BY account_id, extracting table_size with a JSON path function. This returns 1882 rows instead of 673k, and needs no IN list of table ids.
  2. Maintain per-account size incrementally. MTS already tracks changed tables through the alpha/beta tasks. Rolling the deltas into a per-account accumulator would make the all-accounts SHOW ACCOUNTS O(accounts).
  3. Short term:
    • Decode only table_size instead of unmarshalling the whole table_stats into map[string]any.
    • Avoid building multi-MB IN-list SQL. Batching or a temp table would both work.
    • Cache the MTS sizes for the all-accounts case between cron rounds.

Related: #11480, #29983.

Activity

  1. added
    kind/bug
    priority/p2
    on Oct 27, 2026
  2. removed
    priority/p2
    on Oct 27, 2026
  3. added a commit that references this issue on Oct 28, 2026
    b936222
  4. assigned and unassigned on Oct 28, 2026
  5. XuPeng-SH commented on Oct 28, 2026

    @XuPeng-SH
    Contributor

    QA status for merged main da0c931aa7a230d51c866057d6cd302d4b83d3f8 (#31437): the current environment has not run the new real-engine or SHOW ACCOUNTS tests; existing resource guard headroom is insufficient for a safe large link or current-head service. The PR reports author-run component, real SQL and paired performance evidence; those are not local results from this QA environment. Account isolation, missing statistics, refresh/fallback and original workload-scale performance remain pending independent verification here. Existing assignee is unchanged.

  6. slyunnn commented on Oct 29, 2026

    @slyunnn

    Regression and extended verification for #31388 (2026-10-29)

    Verification Environment

    • Test-start origin/main: 7597f979e7904cf37ff077c94ffad191367d4d89 — fix(plan): compare SET columns by their member values (#31633). Newly built macOS/arm64 CPU runtime, Go 1.27.1; build identity and every endpoint's git_version() matched 7597f979e7.
    • Complete local topology: 2 CN / 1 TN / 1 Log service / 1 Proxy, one local launch process, 4 Go Ps and a 6 GiB Go memory limit. Proxy 127.0.0.1:6001, CN1 127.0.0.1:16001, CN2 127.0.0.1:16002 were connectable and actually used for SHOW ACCOUNTS, account-isolation and fallback checks.
    • Clients: PyMySQL/MySQL text protocol; JDBC/mo-tester for checked-in BVT comparison through Proxy. Scale measurements and global-policy tests ran in isolated phases; original policy settings were restored.

    What Was Covered

    • OK — Original sys SHOW ACCOUNTS executed successfully at all endpoints. Checked-in show_accounts_storage.sql exercised same-name cross-account tables, single-account forced refresh, multi-account aggregation, tenant-only visibility, snapshot-size controls and dropped-table handling.
    • OK — The complete MTS BVT group passed twice on one instance: 108/108 checks each round, with 0 failures/skips/abnormal results. Account/database teardown was checked between runs.
    • OK — The exact aggregate SQL from the tested source passed real-engine controlled-input tests at all endpoints: full account/database/table join-key isolation, missing statistics/fields, SQL/JSON nulls, per-table truncation, exact integer sums beyond 2^53, uint64 wrap and exclusion of a removed catalog row's stale statistics. These were SQL-engine component tests, not direct calls to the Go account-size API.
    • OK — Live aggregate-enabled and use_old_impl:true TN-fallback behavior both returned the expected accounts through Proxy and each CN; ordinary tenants saw only themselves. Both CNs' original configuration was verified after restoration.
    • OK — A separate live catalog-scale probe created 100, 1,000, then 5,000 empty user tables across two accounts, with nonempty payload tables and statistics refreshed through the single-account path. At the largest stage, the selected accounts had 5,194 live catalog tables: the replayed legacy path returned 5,138 statistics rows and built an 82,798-byte SQL statement; the new aggregate returned 2 rows using a 446-byte SQL statement. Per-account byte totals matched.
    • OK — Six alternating measurements per scale on the same current engine recorded aggregate-query medians of 2.312, 4.652, 17.166 ms; current SHOW ACCOUNTS LIKE 'qa31388_scale_%' medians were 10.045, 16.118, 43.256 ms. These are bounded local measurements, not production latency guarantees.
    • Not covered — The original 1,882-account/~673k-table production workload, production GC/p99 behavior, the 60 s cron deadline at that scale, and the v4.2.1-hotfix release branch. No independent before/after Go-binary benchmark or TKE performance run is claimed.

    Findings

    Associated fix: PR #31437, commit b93622211cce180ea3869554d258cad90267cffb — fix(frontend): aggregate SHOW ACCOUNTS table sizes in SQL. The touched account-size implementation files are unchanged between that fix and the tested main.

    The normal path now joins live catalog identity to statistics and aggregates inside SQL, avoiding per-table IDs/JSON materialization and table-sized IN lists in Go. Missing-account/fallback semantics and the single-account refresh path remain distinct. SQL scan/join work can still scale with table count; this is not an assertion of strictly O(accounts) total database execution cost.

    The legacy comparison replayed its SQL and materialization in Python on the same current engine. Its timings must not be described as measurements of the old Go implementation or a before/after end-to-end speedup. The PR author's separately reported larger paired benchmark is not represented here as a newly executed QA result.

    MOTR / BVT Coverage

    Reused the existing test/distributed/cases/disttae/mo_table_stats/ group and checked-in results, without regenerating expectations. Maintained component tests and the materialization benchmark already exist upstream; no duplicate MOTR case or PR was added. Local probe scripts/evidence remain outside tracked product source. No MatrixOne service source or deployment configuration was modified.

    Final Conclusion

    Fixed on the tested main for the identified client-side per-table lookup/materialization bottleneck, with functional behavior and bounded catalog-scale execution independently verified. This does not certify the production hotfix release or the original workload's latency SLO.

    Catalog-scale regression is required for this issue; bounded 100/1,000/5,000-table stages were executed rather than increasing row payloads, which would miss the relevant boundary. Original production-scale validation remains unperformed and is required before making a production p99/timeout guarantee.

    All test accounts/databases were removed, both CN configurations restored, and endpoint health checked. Issue status remains unchanged for maintainer acceptance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions