Skip to content

[Performance]: planner row and column statistics become stale after DML #31993

Open

Description

@Ariznawlll

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 flush

Same 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.00

3. 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 120000

Kill 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 (blockNum in 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 manual mo_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; ANALYZE must 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

  1. added
    kind/bug
    on Nov 2, 2026
  2. added this to the MO-202611 milestone on Nov 2, 2026
  3. added theissue type on Nov 2, 2026
  4. Ariznawlll commented on Nov 2, 2026

    @Ariznawlll
    CollaboratorAuthor

    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-CN StatsCache with only a 3-second TTL (:348, time.Now().Unix()-w.GetLastVisit() < 3) plus tableDef.Version invalidation → slow path doStatsHeavyWork → 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.Stats composes getPublishedStats + partitionRowEstimate (txn_table.go:341). The latter sums obj.Rows() over objects in the logtailreplay.PartitionState and adds ApproxInMemRows(), but never subtracts tombstone rows. Row estimates are therefore monotonically non-decreasing; only ANALYZE (Engine.RefreshTableStats, engine.go:1433 — "The cache swap is the publication boundary observed by later plans") or TRUNCATE (object removal) can move them down.

    2. Unflushed inserts invisible — workspaceInsertRowEstimate (txn_table.go:370) only counts the current transaction's own txn.writes; committed-but-unflushed rows from other (already finished) transactions must come via ApproxInMemRows() in the partition state. Empirically they don't (87,654 committed rows → estimate stays the 1,000 default with blockNum=1 for minutes, until mo_ctl('DN','FLUSH',...)). Either logtail does not advertise in-mem row counts promptly, or ApproxInMemRows doesn't cover them — worth a look by whoever owns logtailreplay.

    3. ANALYZE not propagated across CNs — Engine.Stats reads e.globalStats (engine.go:1414), a per-CN-process GlobalStats. RefreshTableStats swaps 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.

  5. Ariznawlll commented on Nov 2, 2026

    @Ariznawlll
    CollaboratorAuthor

    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.

  6. changed the title [-][Bug]: planner row estimates never refresh without manual ANALYZE/FLUSH[/-] [+][Performance]: planner row estimates never refresh without manual ANALYZE/FLUSH[/+] on Nov 2, 2026
  7. Ariznawlll commented on Nov 2, 2026

    @Ariznawlll
    CollaboratorAuthor

    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:

    defect 4.0.8 build main@HEAD
    unflushed inserts invisible 30k rows in 3k batches → est. 1000 fixed — same load pattern now estimates exactly 30,000
    ANALYZE not propagated across CNs peer CN stuck at 120,000 after 6 min fixed — peer CN's first read returns the exact ANALYZE value (123,457)
    DELETEs never lower the estimate pinned 300 s+ still present — deleted 90% of a 123,457-row ANALYZEd table; estimate still 123,457 at t+2 s, t+30 s, t+60 s
    per-CN first-read pinning pinned effectively still present via the DELETE path (no DML-driven invalidation observed within 60 s)

    Suggest re-scoping this issue to the remaining defect: row estimates are monotonic — DELETE tombstones never decrement them (partitionRowEstimate sums 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.

  8. changed the title [-][Performance]: planner row estimates never refresh without manual ANALYZE/FLUSH[/-] [+][Performance]: row estimates never decrease after DELETEs[/+] on Nov 2, 2026
  9. Ariznawlll commented on Nov 2, 2026

    @Ariznawlll
    CollaboratorAuthor

    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) in txnTable.Stats (pkg/vm/engine/disttae/txn_table.go:251-296):

    rows, err := partitionRowEstimate(part, ...)
    ...
    if plan2.StatsInfoUsable(published) {
        rows = math.Max(rows, published.TableCnt)   // <- estimates can only go UP past ANALYZE
    }

    Once a table is ANALYZEd, published.TableCnt is frozen and the Max() clamps any decrease:

    scenario live rows estimate verdict
    never-ANALYZEd, churn 7× 10,000 10,000 exact
    ANALYZEd at 50,000, then DELETE 90% 5,000 50,000 pinned by Max()
    same table, +10k INSERT (live 15,000) 15,000 50,000 still pinned (below published)
    same table, +50k more (live 65,000) 65,000 60,000 exceeds published → live value wins

    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) or TRUNCATE (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.Max clamp 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).

  10. XuPeng-SH commented on Nov 9, 2026

    @XuPeng-SH
    Contributor

    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.

  11. changed the title [-][Performance]: row estimates never decrease after DELETEs[/-] [+][Performance]: planner row and column statistics become stale after DML[/+] on Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugneeds-triage

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions