Repository navigation
Description
Summary
On current main, the row-count estimates the planner consumes (EXPLAIN VERBOSE outcnt/cost) are never refreshed by any DML once a CN has read them. Four reinforcing defects, all reproducible on a 2-CN local cluster (etc/launch-multi-cn):
| # | Defect | Evidence |
|---|---|---|
| 1 | Unflushed inserts are invisible to the planner — a freshly bulk-loaded table estimates as the default 1000 rows regardless of true size | 87,654 rows inserted → outcnt=1000.00 blockNum=1; after mo_ctl('DN','FLUSH',...) → outcnt=87654.00 blockNum=12 (exact) |
| 2 | DELETEs never lower the estimate — tombstones don't touch block metadata | 99,000 of 100,000 rows deleted → estimate stays 100,000 for the whole 300 s watch window (and counting) |
| 3 | Estimates are pinned per-CN on first read — later DML never updates the cached value | table ANALYZEd to 1000 on CN1, then 80,000 inserted via CN2: CN1 still estimates 1000 after 30 s+ |
| 4 | ANALYZE does not propagate across CNs | table ANALYZEd on CN1 (exact 123,457); CN2 still estimates 120,000 six minutes later — i.e. permanently, for any practical purpose |
Related: #31880 (DELETE direction, reported against the older stats-table layout). This issue covers the full mechanism on current main, where mo_table_stats_alpha no longer even holds rows for user tables.
Reproduction
Setup: etc/launch-multi-cn (1 log, 1 TN, 2 CN on 127.0.0.1:16001/16002), root login, EXPLAIN VERBOSE as the estimate oracle.
1. Unflushed inserts invisible
CREATE TABLE pin_t (k INT PRIMARY KEY, v INT);
-- insert 87,654 rows in batches of 3,000
EXPLAIN VERBOSE SELECT * FROM pin_t;
-- Table Scan ... cost=1000.00 outcnt=1000.00 blockNum=1 <-- true rows: 87,654
SELECT mo_ctl('DN','FLUSH','jumpstats.pin_t');
EXPLAIN VERBOSE SELECT * FROM pin_t;
-- Table Scan ... cost=87654.00 outcnt=87654.00 blockNum=12 <-- exact after manual flushSame for a 20,000-row table inserted in 100-row batches (OLTP-style): outcnt=1000 until manual FLUSH. The natural flush did not occur within several minutes of inserting (separate watch running; even a multi-minute window is fatal for load-then-query ETL).
2. DELETEs never reflected
-- table b: 100,000 rows, ANALYZEd (estimate = 100,000)
DELETE FROM b WHERE grp >= 500; -- 99,000 rows gone, 1,000 remain
-- poll EXPLAIN VERBOSE every 5 s for 55 s, then every 20 s for 300 s:
-- estimate stays 100,000.00 for the entire window.
ANALYZE TABLE b; -- only now: outcnt=1000.003. Per-CN pinning
-- track_t ANALYZEd at 10,000 rows on CN1
-- insert 70,000 rows via CN2, delete them back via CN2
-- CN1 estimate: 10,000 at +2 s, +30 s (unchanged both ways)4. ANALYZE stays local
-- cross_t: 123,457 rows, inserted via CN1
-- CN2 first read: outcnt=120000 (block-based approximation)
-- CN1: ANALYZE TABLE cross_t; -> outcnt=123457 (exact)
-- CN2 new connection, +2 s, +10 s, +6 min: still 120000Kill quantification (wrong build side)
Table surge ANALYZEd at 1,000 rows, then bulk-loaded to 301,000 rows (unflushed/pinned). Query SELECT COUNT(*) FROM a JOIN surge ON a.k = surge.k (a = 100,000 rows):
| state | planner belief | hashmapSize | median latency |
|---|---|---|---|
| stale (est. 1,000) | surge = 1,000 | 1,000 (build side = 301k reality) | 14.6 ms |
| after ANALYZE (est. 301,000) | surge = 301,000 | 100,000 (a becomes build side) | 4.4 ms |
→ 3.3× penalty from the stale estimate, on a tiny 300k-row demo. The gap grows with the size ratio, and in a multi-CN deployment the plan you get depends on which CN the load balancer picks (defects 3+4).
Mechanism (black-box inferred)
- Estimates derive from flushed block metadata (
blockNumin EXPLAIN VERBOSE tracks it 1:1). Memtable rows are not counted; delete tombstones don't decrement. - Each CN caches the estimate on first read and never invalidates on DML. Invalidation happens only via:
ANALYZE(local CN only),TRUNCATE, or manualmo_ctl('DN','FLUSH',...). - Consequences: bulk-load-then-query gets default-1000 plans; append-mostly tables overestimate forever after any DELETE; multi-CN clusters give different plans for the same SQL depending on routing;
ANALYZEmust be run on every CN to converge.
Expected behavior
Estimates should reflect committed data within a bounded lag (single-digit seconds) cluster-wide — e.g. memtable row counts included in the estimate, DELETE deltas applied, and ANALYZE results propagated (or centrally stored) so all CNs plan from the same statistics.
Activity
Ariznawlll commentedon Nov 2, 2026
Code-level follow-up (main @ current HEAD), mapping each black-box symptom to its source:
Estimate pipeline:
compilerContext.statsWithTableDefVersion(pkg/sql/compile/sql_executor_context.go:327) → per-CNStatsCachewith only a 3-second TTL (:348,time.Now().Unix()-w.GetLastVisit() < 3) plustableDef.Versioninvalidation → slow pathdoStatsHeavyWork→txnTable.Stats(pkg/vm/engine/disttae/txn_table.go:251).So the CN cache is not the pinning layer — the 3 s TTL means every plan beyond 3 s re-reads. The staleness lives in what the re-read returns:
1. DELETEs never lower the estimate —
txnTable.StatscomposesgetPublishedStats+partitionRowEstimate(txn_table.go:341). The latter sumsobj.Rows()over objects in thelogtailreplay.PartitionStateand addsApproxInMemRows(), but never subtracts tombstone rows. Row estimates are therefore monotonically non-decreasing; onlyANALYZE(Engine.RefreshTableStats,engine.go:1433— "The cache swap is the publication boundary observed by later plans") orTRUNCATE(object removal) can move them down.2. Unflushed inserts invisible —
workspaceInsertRowEstimate(txn_table.go:370) only counts the current transaction's owntxn.writes; committed-but-unflushed rows from other (already finished) transactions must come viaApproxInMemRows()in the partition state. Empirically they don't (87,654 committed rows → estimate stays the 1,000 default withblockNum=1for minutes, untilmo_ctl('DN','FLUSH',...)). Either logtail does not advertise in-mem row counts promptly, orApproxInMemRowsdoesn't cover them — worth a look by whoever owns logtailreplay.3. ANALYZE not propagated across CNs —
Engine.Statsreadse.globalStats(engine.go:1414), a per-CN-processGlobalStats.RefreshTableStatsswaps only the local process's cache; nothing in this path broadcasts to peer CNs. Each CN converges only when its own background stats update runs — on a 6-minute observation window the peer CN still served the pre-ANALYZE value.Suggested directions: (a) subtract visible tombstone counts in
partitionRowEstimate; (b) include committed in-mem rows from logtail in the estimate; (c) publish ANALYZE results through a shared channel (logtail stats key broadcast or TN-side storage + invalidation), so all CNs plan from one statistics version.Ariznawlll commentedon Nov 2, 2026
Additional data point — natural flush timing: a fresh table loaded with 30,000 rows (500-row batches, INT columns) stayed invisible to the planner (
outcnt=1000.00 blockNum=1) until t+270 s, when the estimate jumped to the exact 30,000 (blockNum=5). So the unflushed-invisibility window on an idle local cluster is ~4.5 minutes for this row size/count. Every query optimized against that table within the window plans as if the table were ~empty — bulk-load-then-report ETL patterns hit this deterministically.[-][Bug]: planner row estimates never refresh without manual ANALYZE/FLUSH[/-][+][Performance]: planner row estimates never refresh without manual ANALYZE/FLUSH[/+]Ariznawlll commentedon Nov 2, 2026
Retest on a binary built from current main (HEAD c6683bd, built 2026-11-02) — the original report was run against a 2026-09-22 build (cluster version 4.0.8), and two of the four defects are already fixed on main:
Suggest re-scoping this issue to the remaining defect: row estimates are monotonic — DELETE tombstones never decrement them (
partitionRowEstimatesums object rows without subtracting visible tombstones, see my earlier white-box comment). The unflushed-insert and cross-CN propagation work that landed in the last weeks can be verified from the table above.[-][Performance]: planner row estimates never refresh without manual ANALYZE/FLUSH[/-][+][Performance]: row estimates never decrease after DELETEs[/+]Ariznawlll commentedon Nov 2, 2026
Mechanism correction + final model (main@HEAD c6683bd), replacing my earlier "tombstones not subtracted" inference:
The real-time estimate path already tracks DELETEs correctly. Proof: a never-ANALYZEd table churned through 7 rounds of insert-10k-then-delete-all shows estimate = live rows exactly (1.0×) at every round, and
DELETE FROM churn_t WHERE k < 700000(60k rows) drops the estimate to the exact remaining 10k within a second. Tombstones are subtracted in the real-time path — no merge/compaction wait involved.The pinning comes from
math.Max(live, published)intxnTable.Stats(pkg/vm/engine/disttae/txn_table.go:251-296):Once a table is ANALYZEd,
published.TableCntis frozen and the Max() clamps any decrease:So estimates are monotonically non-decreasing per ANALYZE snapshot: they only move up past the published value, never down. No maintenance operation changes this — verified FLUSH / incremental CHECKPOINT / GLOBALCHECKPOINT / FORCEGC, estimate untouched at 50,000 throughout. Only
ANALYZE(rewrites published) orTRUNCATE(resets objects) moves it down.Downstream damage quantified: a 5k-live-row table with 50k blocks of tombstones pays a 2.3× scan tax on COUNT (1.8 ms vs 0.8 ms for a true 5k-row table) and 1.4× on SUM — and the planner keeps sizing joins/hashmaps for 50k rows.
Suggested fix direction: replace the
math.Maxclamp with freshness-aware composition — e.g. trust the live estimate when the object set has changed since the published snapshot was taken (generation/epoch comparison), or have ANALYZE record a delta baseline that DML adjusts on both directions. The live path is already accurate enough to serve directly (churn test above).XuPeng-SH commentedon Nov 9, 2026
Consolidating #32202 here under planner-statistics freshness after DML. In addition to row-count/cache freshness and cross-CN propagation tracked here, retain #32202’s distinct contract: refresh or bound staleness of NDV, min/max, and null-count statistics after bulk DML, with ANALYZE as the control. Keep both row-count and column-statistics acceptance cases.
[-][Performance]: row estimates never decrease after DELETEs[/-][+][Performance]: planner row and column statistics become stale after DML[/+]