Cost model and statistics

SynergyDB has a PostgreSQL-style cost model and a large statistics module in src/plan/, but the live query path uses neither to choose plans. The only statistics in use are a row count and two per-column numbers that ANALYZE stores, and the only consumers are the optimizer's join reorder and the PostgreSQL catalog views. No cardinality estimate drives access-path choice, join algorithm or memory use (source: src/plan/optimizer.rs, cost_reorder_top; src/query/engine.rs, handle_analyze).

Summary of what is live

Component File Used on the live query path?
ANALYZE statement src/query/engine.rs, handle_analyze yes
StatisticsManager via global_statistics() src/plan/statistics.rs yes: storage for ANALYZE results
Join reorder selectivity (1 / NDV, 0.2) src/plan/optimizer.rs, pred_selectivity yes, only when every joined table was analyzed
pg_class.reltuples, pg_stat_*_tables row counts src/protocol/postgres/catalog.rs, estimate_row_count yes
CostModel, CostParams src/plan/cost_model.rs Not wired
PhysicalPlanner src/plan/physical_planner.rs Not wired
EnhancedStatisticsCollector, CardinalityEstimator, ReservoirSampler src/plan/stats_collector.rs Not wired
AdaptiveOptimizer, AdaptivePlanCache, CostModelTuner, PlanInvalidator src/plan/adaptive.rs Not wired
Histograms, most-common values, correlation src/plan/statistics.rs, ColumnStatistics, Histogram Not wired: types exist, ANALYZE never fills them

"Not wired" here means no code outside src/plan/ references the item (source: src/plan/mod.rs; searches of src/query/ and src/protocol/). The module doc in src/plan/mod.rs describes rule-based and cost-based optimization, adaptive optimization and "PostgreSQL-style cost estimation with automatic tuning"; of those, only the rule-based part runs.

ANALYZE

ANALYZE is handled by a fast path before parsing (see lifecycle); there is no LogicalPlan node for it (source: src/query/engine.rs, handle_analyze).

Steps:

  1. Strip the ANALYZE keyword and an optional VERBOSE.
  2. A bare ANALYZE with no table names does nothing and returns an empty result. It does not analyze every table.
  3. Split the rest on commas and trim quotes and backticks from each name.
  4. For each table, run SELECT COUNT(*) FROM "t" through analyze_scalar. A table that does not exist is skipped without an error.
  5. If the count is greater than zero, read the column names with SELECT * FROM "t" LIMIT 0, then for each column run SELECT COUNT(DISTINCT "c") FROM "t" (stored as n_distinct) and SELECT COUNT("c") FROM "t" (used to compute null_frac).
  6. Store a TableStatistics through global_statistics().write().store_table_stats(...), which also increments STATS_GENERATION.

(source: src/query/engine.rs, handle_analyze, analyze_scalar; src/plan/statistics.rs, StatisticsManager::store_table_stats, statistics_generation)

Each column therefore costs two full scans, and the table one more. There is no sampling: DEFAULT_SAMPLE_SIZE (30000), DEFAULT_HISTOGRAM_BUCKETS (100) and DEFAULT_MCV_COUNT (100) are defined but ANALYZE does not use them (source: src/plan/statistics.rs). ANALYZE on an empty table stores nothing for columns.

Tested by analyze_collects_row_count_statistics in src/query/engine.rs (37 rows; checks row count, n_distinct 37 and null_frac 0) and by reltuples_follows_analyze_not_a_live_scan in tests/pg_class_reltuples.rs (checks that pg_class.reltuples is 0 before ANALYZE, equals the row count after it, and does not move with later inserts until the next ANALYZE).

Behaviour to be aware of

  • Process-wide, keyed by table name only. GLOBAL_STATS is a single OnceLock<Arc<RwLock<StatisticsManager>>> for the whole server. The key is table_oid_for_name, a hash of the lowercased table name turned into a Uuid. Two databases with a table of the same name share one statistics entry (source: src/plan/statistics.rs, global_statistics, table_oid_for_name).
  • Name as written. TableStatistics.table_name stores the name exactly as it appeared in the ANALYZE statement. get_table_stats_by_name is a case-sensitive linear search, so the optimizer's join reorder finds the entry only when the query spells the table the same way. The PostgreSQL catalog tries the exact name and then the lowercase name (source: src/plan/statistics.rs, get_table_stats_by_name; src/protocol/postgres/catalog.rs, estimate_row_count).
  • Never invalidated. Writes do not update or mark statistics stale; invalidate_table, remove_table, clear and mark_stale have no callers outside src/plan/; the only writer outside src/plan/ is handle_analyze. A dropped and re-created table keeps its old statistics until the next ANALYZE (source: src/plan/statistics.rs).
  • Not persisted. Statistics live in memory and are lost on restart (source: src/plan/statistics.rs, GLOBAL_STATS).

Not verified: the cross-database sharing and the case-sensitivity mismatch have no tests.

Who reads the statistics

Reader What it reads Effect
Optimizer join reorder row_count, column n_distinct order of inner joins; see optimizer
PostgreSQL catalog estimate_row_count row_count pg_class.reltuples, relpages, and row counts in pg_stat_*_tables; 0 when never analyzed
Engine pg_class cache statistics_generation() rebuilds the cached pg_class rows after an ANALYZE

(source: src/plan/optimizer.rs, row_estimate, pred_selectivity; src/protocol/postgres/catalog.rs, estimate_row_count; src/plan/statistics.rs, statistics_generation)

The pg_stats and pg_statistic relations always return no rows, even after ANALYZE has collected n_distinct and null_frac. A comment beside them in src/query/engine.rs says no column statistics are collected, which is no longer true (source: src/query/engine.rs).

Nothing reads null_frac on the live path. The executor's access-path cascade, join algorithm and EXPLAIN row estimates do not read statistics; EXPLAIN counts keys in storage instead (see EXPLAIN).

The statistics module

src/plan/statistics.rs defines (source: src/plan/statistics.rs):

Type Fields or purpose
TableStatistics table_oid, table_name, row_count, page_count, avg_row_width, columns, last_analyzed, stale
ColumnStatistics n_distinct, null_frac, avg_width, mcv, histogram, correlation, min and max; selectivity helpers selectivity_eq, selectivity_range, selectivity_between, selectivity_like, selectivity_in
Histogram equi-depth histogram (Histogram::equi_depth)
IndexStatistics per-index statistics
ExtendedStatistics, ColumnGroupStats, FunctionalDependency, JoinStatistics multi-column and join statistics
FeedbackManager, CachedPlan run-time feedback and plan caching

Only TableStatistics.row_count and ColumnStatistics.n_distinct/null_frac are filled on the live path. The module has 5 unit tests, which test the types in isolation.

The cost model

Not wired: CostModel in src/plan/cost_model.rs is a PostgreSQL-style cost model. Optimizer::new() builds one and stores it, but the only method that consults it, estimate_selectivity, has no live caller (source: src/plan/cost_model.rs, CostModel; src/plan/optimizer.rs, Optimizer::new).

Default CostParams:

Parameter Default
seq_page_cost 1.0
random_page_cost 4.0
cpu_tuple_cost 0.01
cpu_index_tuple_cost 0.005
cpu_operator_cost 0.0025
effective_cache_size 524288.0
default_tuple_width 100.0
default_selectivity 0.5
hash_mem_multiplier 1.0
sort_mem 100000

(source: src/plan/cost_model.rs, CostParams::default)

A Cost has startup, total, rows and width. Functions cover sequential scan, index scan, nested-loop, hash and merge joins, filter, project, sort, limit, hash aggregate, distinct, multi-column selectivity and expression selectivity (source: src/plan/cost_model.rs, cost_seqscan, cost_index_scan, cost_nested_loop_join, cost_hash_join, cost_merge_join, estimate_selectivity). Tested in isolation by test_seqscan_cost, test_seqscan_with_filter, test_hash_join_cost, test_selectivity_eq, test_selectivity_and, test_selectivity_or, test_sort_cost and test_topn_cost; none of these numbers reach a query.

PhysicalPlanner in src/plan/physical_planner.rs combines the cost model, statistics and an IndexManager with a PlannerConfig (enable_index_scan, enable_hash_join, enable_merge_join, index_scan_selectivity_threshold, top_n_threshold). Not wired: it has 5 unit tests and no caller outside src/plan/ (source: src/plan/physical_planner.rs, PhysicalPlanner).

src/plan/stats_collector.rs (9 tests) and src/plan/adaptive.rs (9 tests) describe sampled statistics with background refresh and persistence, and feedback-driven re-planning. Not wired: neither is referenced outside src/plan/, so none of the sampling, refresh, persistence or feedback they describe happens (source: src/plan/stats_collector.rs, src/plan/adaptive.rs).

Disagreements with other documents

The README says index choice is made "by the cost-based optimizer", and How it works and the configuration reference call the optimizer cost-based. No cost is computed on the live path; see optimizer.