Skip to content

fix(frontend): aggregate SHOW ACCOUNTS table sizes in SQL - #31437

Merged
XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
ck89119:issue-31388-fix-main
Oct 28, 2026
Merged

XuPeng-SH merged 7 commits into
matrixorigin:mainfrom
ck89119:issue-31388-fix-main

Conversation

@ck89119

@ck89119 ck89119 commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

Fixes #31388

What this PR does / why we need it:

SHOW ACCOUNTS currently computes account totals through a per-table statistics API: it enumerates every live table, constructs three table-sized IN lists, and materializes/decodes per-table JSON in Go.

Add a dedicated account-size read path that joins live catalog tables to MTS by account/database/table identity and aggregates in SQL. Preserve per-table truncation and uint64 summation semantics, missing-statistics behavior, owner policy admission, single-account forced refresh, TN fallback, and snapshot sizes. Existing per-table APIs retain their contract.

Validation

  • disttae/frontend package tests, real-engine MTS tests, disttae race tests and 100 policy-race repetitions; build, vet and incremental lint passed.
  • Changed coverage blocks: 72/73 statements (98.6%).
  • mo-tester generated and verified the new result; two same-instance runs passed, and the MTS group passed 108/108 checks with clean teardown.

Real SQL performance

Created real tables across 100 test accounts plus sys, populated statistics through the existing refresh path, and ran sys SHOW ACCOUNTS against baseline baa83f4b96 and the same revision plus this fix. A–B–B–A runs restore the same snapshot, wait for the initial StorageUsage cron round to finish, then warm up and collect 14 measured executions per version/scale. All account outputs match exactly.

Actual catalog tables Before, median After, median
10,780 261 ms 88 ms
19,780 490 ms 122 ms
39,780 930 ms 227 ms
109,780 2,668 ms 334 ms

At 109,780 catalog tables (100,000 user tables), the storage-usage phase falls from 2,574 ms to 244 ms; the unchanged table-stats phase is 91/88 ms. These are end-to-end SQL measurements, not the separate mocked-result Go microbenchmark.

Limits: shared 16 GiB macOS/arm64 host, local CN/TN/LOG process, four Go Ps and a 4 GiB Go memory limit; most user tables are empty. The 2,000-account/~600k-user-table target was not completed: its setup budget was reached at 1,030 accounts. SQL scans/joins still scale with table count; no production latency, p99, or 60-second timeout guarantee is claimed. The subsequent upstream merge only changes user AUTO_INCREMENT prefetch; relevant read-path validation is reused, not represented as a new run. Remote CI is pending.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@ck89119
ck89119 requested a review from aptend as a code owner October 28, 2026 03:40
@XuPeng-SH

XuPeng-SH commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: d2046a78c6d4de76856ab164c03abd34102a7493

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mo-bot review · mo-bot-local · review

Commit: d2046a78c6d4de76856ab164c03abd34102a7493

Assessment: approve

Reviewed the complete seven-file change, consumers, linked issue and discussion. SQL aggregation preserves numeric behavior, refresh policy, tenant boundaries and TN/snapshot fallback. No actionable findings remain; both discussion entries are informational.

Model: gpt-6-astra / xhigh

Session: 01a13dcf-1586-7a01-9000-d45e20995cf8 · slot 1 · generation 1

Validation:

  • Isolation preflight and current native provenance verification passed; source remained unchanged.

  • Ten targeted tests passed across frontend, disttae and real-engine SQL, covering numeric boundaries, missing/stale statistics, cancellation, policy and fallback.

  • Four policy tests passed under the race detector, each with 100 repetitions.

  • Real-SQL comparison produced identical results: legacy/aggregate medians were 102.90/51.00 ms at 100 added tables and 107.80/47.33 ms at 1,000, with six samples per path.

  • Commands, source fingerprints, exit receipts and logs were reconciled in /home/xupeng/.local/state/mo-bot/jobs/11230e0b63d06e8ed2f48489/attempt-1/receipt-reconciliation.json; discussion-assessment.json covers every discussion key.

  • Frozen CI reports successful build, UT, SCA, coverage and proxy/pessimistic multi-CN BVT.

Limitations:

  • Local measurements cover the storage-size SQL APIs, not end-to-end SHOW ACCOUNTS or the approximately 600,000-table production target. SQL work remains table-count dependent.

  • Author large-scale artifacts and raw per-case CI logs were not supplied; those detailed claims were not independently verified.

  • The initial diagnostic performance setup failed because the minimal fixture lacked mo_database_defaults. Corrected fixture setup passed; this was not a product failure.

@mergify mergify Bot added the queued label Oct 28, 2026
@mergify

mergify Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

🚫 Left the queue

49 min in the queue, with no time running CI.

So far

  • ✅ Entered the queue Wed 28 Oct, 05:40 · rule main · triggered by rule Automatic queue on approval for main
  • ⏹️ Testing stopped · in place
  • 🚫 Left the queue 06:29 · 63d21c5

Reason

Pull request #31437 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Merge conditions: 2 of 3 met

This pull request

Condition Required by
✅ #review-threads-unresolved = 0 GitHub branch protection
✅ github-review-approved GitHub branch protection

The batch, tested in place

Condition Required by
❌ any of: check-neutral = CI Required, check-skipped = CI Required, check-success = CI Required GitHub branch protection

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

Times in UTC · dashboard · how the merge queue works

@gouhongshen gouhongshen left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex automated review

This PR fixes issue #31388 by replacing the O(total-tables) per-table SHOW ACCOUNTS storage lookup with a single SQL aggregate, and my inspection confirms it preserves the old numeric and policy semantics exactly. The prior implementation enumerated every live table via accumulateIdsByAccSQL, built three table-sized IN lists, decoded per-table JSON in Go, and summed with uint64(float64) truncation; the new normal path drives from the live catalog mo_tables and LEFT JOINs mo_table_stats_alpha on the full primary key (account_id, database_id, table_id), which is at most 1:1 because the stats table declares that composite primary key. Per-table truncation is mirrored by floor+cast to unsigned before summing; sum(uint64) returns exact decimal128(38,0) in MO and the modulo by 2^64 reproduces Go's uint64 wrap, as pinned by the new real-engine tests (truncate-before-sum, exact integer sum above 2^53, near-uint64-limit, and wrap cases). Missing or NULL statistics coalesce to 0, accounts without live catalog tables stay absent from the result map so the TN fallback is retained, and stale statistics of dropped tables are excluded because mo_tables is the driving relation. The forced path for a single non-sys account keeps the legacy per-table refresh through the extracted queryTableStatsWithPolicy, preserving owner-policy admission: configuration is read once under RLock at admission while the mo_ctl setters take the write lock, so in-flight queries are not reinterpreted, and this is covered by dedicated tests. Error handling is safe on every unhappy path I traced: query errors, column decode errors, and cancellation all return a nil map with ok=false, tryGetSizeFromMTS then falls back to TN numbers exactly as before, and a partially decoded account map is never published. The engine unwrap plus structural interface assertion in tryGetSizeFromMTS is strictly more defensive than the old hard cast and keeps the EntireEngine behavior; the removed disttae import leaves no references, pre-existing callers of QueryTableStatsByAccounts are untouched, and the merge logic in getAccountsStorageUsage (override only size, keep snapshot, never mutate the TN cache) is unchanged and pinned by new frontend tests. Concurrency, resource handling (executor pool put-back, pooled builder released only after last use), and metric observation are consistent with existing patterns. Discussion reconciliation: one approving mo-bot review by XuPeng-SH with no actionable findings, a pointer comment, a qodo paused-bot notice, and a mergify queue status were present; no reviewer raised any finding, so nothing needed to be withdrawn or deduplicated. Limitation: I could not execute the Go test suites locally because the host has only 4.4 GiB of free disk and the Go build cache for this tree exceeds that ('no space left on device' during go test/vet setup); gofmt -e passes on all changed files, and both the author and the mo-bot reviewer document completed local and CI test runs. This is an environment limitation, not evidence against the change.

@XuPeng-SH
XuPeng-SH merged commit b936222 into matrixorigin:main Oct 28, 2026
27 of 28 checks passed
@mergify mergify Bot added dequeued and removed queued labels Oct 28, 2026
@ck89119
ck89119 deleted the issue-31388-fix-main branch October 28, 2026 06:30
XuPeng-SH added a commit that referenced this pull request Nov 5, 2026
## What type of PR is this?

- [x] API-change
- [x] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [x] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Related to #31388. Backports and refines #31437 for `4.2-dev`.

## What this PR does / why we need it:

`SHOW ACCOUNTS` previously materialized every table's statistics in Go
even when it only needed a per-account total. This was expensive for
accounts with many tables.

Aggregate current sizes in SQL using the complete live
account/database/table identity and a bounded account scan. Preserve
per-table truncation, forced single-account refresh, admission policy,
TN fallback and snapshot size. The shared embedded-cluster fixture can
now use a caller-owned data directory without changing the process-wide
temporary directory or bypassing the shared port lease.

Backport the runtime-only CI Dockerfile and cgroup watcher shutdown fix
so BVT jobs can reuse the validated build artifact and write coverage on
exit. Give Compose services a 120-second shutdown grace period: the
previous default could kill TN or LOG while closing and lose coverage
counters.

## Validation

- The public MySQL integration exercises both CNs, distinct tenant
sizes, forced single-account versus aggregate results, tenant isolation,
a real snapshot and table deletion. It passed normally and twice in one
process under `-race`. A separate frontend test covers preservation of
nonzero TN snapshot sizes; the live test does not force asynchronous
snapshot accounting to become nonzero.
- With the first shared port lease and its TCP port occupied, the public
test passed twice using another lease and removed its owned directories.
Injecting a first-close failure verified that cleanup ownership is
retained and retried before replacing the process-global temporary file
service.
- The real two-CN Compose BVT passed 19/19. All five MatrixOne services
exited normally with the 120-second grace and produced coverage
counters. A wire-level fault injection confirmed that zero or grossly
inflated returned sizes fail the BVT assertions; separate
aggregate-result mutations of zero, +1 MiB and swapped tenant sizes each
fail the public comparison.
- Full `pkg/embed` race, incremental formatting, vet, molint and
golangci-lint passed for the changed embed and public-test packages.
Earlier full frontend and disttae normal/race runs, the focused
real-engine race tests and the cgroup watcher checks remain applicable
to their unchanged code.
- With a shared 4.2 catalog containing 102,400 mostly empty user tables,
interleaved baseline and patched CN queries gave median all-account
latency **2,101 ms → 111 ms** and four selected smaller accounts **49.3
ms → 40.5 ms**; account names, counts, size and snapshot size were
compared. A separate mixed-version topology also passed the earlier BVT.
These are local measurements, not a guarantee for the reported
673,618-table production deployment.
- [CI on the previous PR
head](https://github.com/matrixorigin/matrixone/actions/runs/41732405931)
passed. CI for this updated head must be checked separately. An earlier
deleted-user authorization assertion failed once and passed on rerun;
its intermittent cause remains unconfirmed.

A pre-existing 4.2 `result_scan` issue misreads saved `SHOW ACCOUNTS`
float fields on both baseline and candidate, so the public test compares
MySQL results directly. Out-of-range Go float-to-uint conversions remain
implementation-dependent.

---------

Co-authored-by: Cao Kai <[email protected]>

This branch was previously deployed

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

Labels

dequeued kind/bug Something isn't working size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

4 participants