Repository navigation
Description
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:
- [Enhancement]: Current way of getting storage usage is not scalable. #11480 Current way of getting storage usage is not scalable (closed, 2023). That work moved table sizes onto MTS (
mo_table_stats). This issue is about the MTS lookup path itself, whichSHOW ACCOUNTSnow runs on every call, and which no longer scales. - fix(disttae): batch catalog ID lookups for table statistics #29983 (
b09f2c6fc5, batch catalog ID lookups for table statistics) fixes per-ID catalog lookups ingetChangedTableList, which is the alpha-task path. It does not touchQueryTableStatsByAccounts, and it is not in the hotfix branch below.
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
Other Environment Information
- A production MO cluster with 1882 accounts and about 673,600 tables (from the
table-countfield in the CN log). - The CN running the
StorageUsagecron 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
StorageUsagecron task runsSHOW 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.logline formo_table_stats_alpha - the
query.table.stats.by.accountsline
| 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:610asshow_accounts_get_storage_usage.getAccountsStorageUsageregisters adefer(:455). After the TN storage-usage RPC or cache step, on success it always callstryGetSizeFromMTS(ctx, eng, accIds)(:460) to overwritesize.tryGetSizeFromMTS(:378) passes every account id tode.QueryTableStatsByAccounts(...)(:414). For the all-accounts case,forceUpdateisfalse.
pkg/vm/engine/disttae/mo_table_stats.go
QueryTableStatsByAccounts(:1261) formatsaccumulateIdsByAccSQL(:220):It then callsselect account_id, reldatabase_id, rel_id from mo_catalog.mo_tables where account_id in (<all 1882 account ids>);
queryTableStatsByXXX(:1237). That function decodes all ~673k rows into three[]uint64slices viadecodeIdsFromMOTablesSqlRet(:2110).QueryTableStats(:1374) →normalQuery(:1156) joins those slices back into strings and runsgetTableStatsSQL(:111):The SQL text is several MB.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;
- For each of the ~673k result rows, the code does a
sort.Findover the returned ids and thenjson.Unmarshals the wholetable_statsJSON into amap[string]any(:1221). From that map it reads a single field,table_size. tryGetSizeFromMTSfinally 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 accountslatency, - periodic multi-second GC pauses on whichever CN runs the task (suspected).
Expected Behavior
- The per-account size lookup for
SHOW ACCOUNTSshould 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-countfrom 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 ofmo_tablestaking about 20 s may itself be worth a look.
Possible directions (for discussion, not prescriptive)
- Aggregate in SQL instead of in Go. For example, join
mo_tableswithmo_table_statson(account_id, database_id, table_id)andGROUP BY account_id, extractingtable_sizewith a JSON path function. This returns 1882 rows instead of 673k, and needs no IN list of table ids. - 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 ACCOUNTSO(accounts). - Short term:
- Decode only
table_sizeinstead of unmarshalling the wholetable_statsintomap[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.
- Decode only
Activity
fix(frontend): aggregate SHOW ACCOUNTS table sizes in SQL (#31437)
XuPeng-SH commentedon Oct 28, 2026
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.slyunnn commentedon Oct 29, 2026
Regression and extended verification for #31388 (2026-10-29)
Verification Environment
origin/main:7597f979e7904cf37ff077c94ffad191367d4d89—fix(plan): compare SET columns by their member values (#31633). Newly built macOS/arm64 CPU runtime, Go1.27.1; build identity and every endpoint'sgit_version()matched7597f979e7.2 CN / 1 TN / 1 Log service / 1 Proxy, one local launch process,4Go Ps and a6 GiBGo memory limit. Proxy127.0.0.1:6001, CN1127.0.0.1:16001, CN2127.0.0.1:16002were connectable and actually used forSHOW ACCOUNTS, account-isolation and fallback checks.What Was Covered
SHOW ACCOUNTSexecuted successfully at all endpoints. Checked-inshow_accounts_storage.sqlexercised same-name cross-account tables, single-account forced refresh, multi-account aggregation, tenant-only visibility, snapshot-size controls and dropped-table handling.108/108checks each round, with0failures/skips/abnormal results. Account/database teardown was checked between runs.2^53,uint64wrap 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.use_old_impl:trueTN-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.100,1,000, then5,000empty user tables across two accounts, with nonempty payload tables and statistics refreshed through the single-account path. At the largest stage, the selected accounts had5,194live catalog tables: the replayed legacy path returned5,138statistics rows and built an82,798-byte SQL statement; the new aggregate returned2rows using a446-byte SQL statement. Per-account byte totals matched.2.312,4.652,17.166 ms; currentSHOW ACCOUNTS LIKE 'qa31388_scale_%'medians were10.045,16.118,43.256 ms. These are bounded local measurements, not production latency guarantees.1,882-account/~673k-table production workload, production GC/p99 behavior, the60 scron deadline at that scale, and thev4.2.1-hotfixrelease 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.
fix: optimize SHOW ACCOUNTS and harden 4.2 CI (#32105)