No plan changes on its own: the execution plan as a managed object

KDBS fixes a statement's plan the first time it is chosen and never changes it by itself. A plan is a catalog object that a DBA or an agent creates, alters and drops. What the two ideas mean, what they buy, what they cost, and why KDBS chose them.

Most databases reserve the right to change how they run your query. The SQL is the same and the schema is the same, and one morning the statement runs a different way, because the statistics moved and the optimizer changed its mind. By default, KDBS does not do that. Two ideas are behind it:

  1. No plan changes on its own. Once the engine has chosen how to run a statement, it keeps that choice until someone changes it.
  2. A plan is a managed object. It has a name and a row in the catalog, and it is created, altered, disabled and dropped by explicit statements, like an index.

This post has no measurements. It covers the background, what the two ideas mean in KDBS as of v3.4.16, what they buy, what they cost, and why KDBS chose them.

Background: the change nobody made

A SQL statement says which rows you want, not how to find them. The execution plan is the how: which table to read first, whether to use an index, how to join. For most statements, several plans return the same rows at very different costs.

A cost-based optimizer picks among them with statistics: table sizes, value distributions, how many rows a join produced. Statistics follow the data, so the optimizer’s answer follows the data too. That is the feature. A table that grew a thousandfold probably deserves another plan, and nobody had to notice.

The same mechanism has a failure with a name: the plan regression. Statistics are refreshed, or a table crosses a threshold, and a statement that took milliseconds takes seconds. What makes these incidents hard is not that the plan was bad. It is that nothing was deployed. Nobody changed the code, the schema or a setting, so there is no change to find and nothing to roll back.

The usual answers take some of the optimizer’s freedom back:

  • Hints in the SQL text (MySQL’s optimizer hints, the pg_hint_plan extension for PostgreSQL) tell the optimizer what to do for one statement.
  • Plan baselines (Oracle’s SQL Plan Management) record the accepted plans for a statement, and the optimizer may use only an accepted one.
  • Plan forcing (SQL Server’s Query Store, Aurora’s query plan management) pins a statement to a plan it ran before.

So the ideas in this post are not new. In those systems, though, implicit change is the default and stability is added afterwards, often after the first incident. KDBS starts from the other side.

An earlier post described an engine with no cost-based planner at all: joins ran in the order they were written. Since then the engine has gained a join-order search priced from statistics. This post is about the rule that was kept when the search arrived.

Idea one: no plan changes on its own

What a plan is

In KDBS a plan is three decisions:

  • the order a join’s tables are read in;
  • how each table is read: by primary key, through a named index, through a Cabin, or by walking the table;
  • whether a join reads its inner table once into memory or looks it up again for every outer row.

Which rows come back is never part of a plan. Every choice returns the same rows, so a plan can make a statement slow and can never make it wrong.

One setting says who may change it

The server setting join_order has three values:

ValueWho chooses the join orderWhen it can change
fixed (default)The engine, once per statement shapeOnly by an explicit statement
plannedThe engine, at every run, from the current statisticsWhenever the statistics move
writtenYou: the order written in the SQLWhen you edit the SQL

Under fixed, the engine runs its cost-based search the first time it has a size for every table in the join, and captures the answer for the statement’s shape: the statement with its literals removed. Every later run of that shape, with any values, uses the captured order, whatever the statistics do afterwards.

Here is a join over the sample flight tables on a v3.4.16 server. ANALYZE output is cut down to the lines about order:

kdbs> ANALYZE SELECT f.code, t.seat FROM flight.flights AS f JOIN flight.tickets AS t ON t.flight_id = f.id WHERE f.id BETWEEN 1 AND 2
planned order=planned gen=1 switch=0.662722 est=1:1,0:6 capture=first
step 1 Scan tickets AS t
step 0 Probe flights AS f key=0:0.1

kdbs> ANALYZE SELECT f.code, t.seat FROM flight.flights AS f JOIN flight.tickets AS t ON t.flight_id = f.id WHERE f.id BETWEEN 1 AND 4
planned order=captured
step 1 Scan tickets AS t
step 0 Probe flights AS f key=0:0.1

A step’s number is its table’s position in the SQL text, and the lines are in the order the steps run. The first run searched, chose to read tickets first and probe flights by key, and captured that (capture=first). The second run has different values and did not search: order=captured.

The capture is a row in the catalog:

kdbs> SELECT name, origin, state FROM sys.plans
                           name    origin    state
-------------------------------  --------  -------
captured_10564123644864913620_1  captured  enabled

A background task writes the row within about a second. The SELECT itself never writes. The row is loaded again when the server starts, so a restart does not re-plan anything.

What can still change a plan

Only explicit acts:

  • DROP PLAN on a captured row. The shape’s next run searches again, and that answer is captured.
  • CREATE PLAN and ALTER PLAN, described below.
  • DDL. A capture holds the join order, not the access path. A new index can change how a captured shape reads a table, never the order it reads tables in. Creating an index is itself an explicit act.
  • SET JOIN_ORDER, issued by an administrator, for the whole instance.

Statistics, load, time and restarts are not on the list.

Three edges are worth knowing. Until every table in a join has a published size, the engine chooses at each run and ANALYZE says capture=deferred. A join that reaches every table through its primary key is not searched and not captured. A statement with a subquery in its WHERE runs in written order under every value of the setting.

Idea two: the plan is a managed object

An administrator can attach a plan to a statement shape:

CREATE PLAN p_flight_seats FOR
  SELECT f.code, t.seat FROM flight.flights AS f JOIN flight.tickets AS t ON t.flight_id = f.id
  WHERE f.id BETWEEN 1 AND 2
VARIANT narrow WHEN ARG(2) - ARG(1) <= 1 ORDER (f, t)
VARIANT wide ELSE ORDER (t, f);

The statement is given by example, with literals. The literals are not kept: the plan belongs to the shape and applies to every later statement of that shape, whether its values are written in the text or bound.

Variants: the plan states its own rule

There is one good reason for a statement to have two plans: its values differ. A narrow key range and a wide one may want opposite join orders. A cost-based optimizer handles this by looking at the values and deciding by itself.

In KDBS the plan states the rule. ARG(k) is the statement’s k-th literal. The variants are tried in the order written, the first whose WHEN holds is used, and the last must be ELSE, so every statement gets exactly one. The rule reads the statement’s values only, never data or statistics. The same values always choose the same variant:

kdbs> ANALYZE SELECT f.code, t.seat FROM flight.flights AS f JOIN flight.tickets AS t ON t.flight_id = f.id WHERE f.id BETWEEN 1 AND 2
planned order=plan plan=p_flight_seats/narrow
step 0 Range flights AS f range=[1, 2]
step 1 Scan tickets AS t build on=col1 key=0:0.0

kdbs> ANALYZE SELECT f.code, t.seat FROM flight.flights AS f JOIN flight.tickets AS t ON t.flight_id = f.id WHERE f.id BETWEEN 1 AND 4
planned order=plan plan=p_flight_seats/wide
step 1 Scan tickets AS t
step 0 Probe flights AS f key=0:0.1

A variant can also restrict how a table is read (ACCESS t INDEX ix_name, ACCESS t SCAN, ACCESS t NOT INDEX) and how a join reads its inner table (BUILD t ON or OFF).

What makes it an object and not a hint

  • It lives in the catalog, not in the SQL. sys.plans lists each plan with its name, its origin (admin or captured), its state and its variants. The application’s SQL is not touched.
  • It has a lifecycle. ALTER PLAN ... DISABLE stops using a plan without removing it, and ENABLE uses it again. REPLACE VARIANT changes one variant. DROP PLAN removes the plan. All are administrator statements.
  • It has a rank. An administrator’s plan comes first, under every value of join_order. Then the captured plan. Then the search, or the written order. Disabling p_flight_seats puts the statement back on its captured order, not on a new search.
  • It has dependencies. A table cannot be dropped while an enabled plan names it, and neither can an index or a Cabin that a plan pins by name. Assertions hold their tables the same way.
  • It cannot make a statement wrong. A pin restricts the engine’s choice among the ways that statement can legally be read. CREATE PLAN refuses a pin that nothing can satisfy. A variant that does not fit one particular statement is skipped for that statement, which then runs in written order and is counted.

The engine advises; it does not act

The search has not gone away. ADVISE PLAN runs it on request and reports the answer. This reply came a few seconds after the capture above, before p_flight_seats existed:

kdbs> ADVISE PLAN FOR SELECT f.code, t.seat FROM flight.flights AS f JOIN flight.tickets AS t ON t.flight_id = f.id WHERE f.id BETWEEN 1 AND 2
ADVISED PLAN fetch_id=10564123644864913620 in_force=captured searched=1 cost_ratio=0.310 generation=2 order=(f, t) plan=CREATE PLAN advised_10564123644864913620 FOR SELECT f.code, t.seat FROM flight.flights AS f JOIN flight.tickets AS t ON t.flight_id = f.id WHERE f.id BETWEEN 1 AND 2 VARIANT advised ELSE ORDER (f, t)

The capture read statistics generation 1. By generation 2 the cost model priced the order (f, t) at 0.31 of the captured one. On a nine-row sample table that estimate means nothing. What matters is what the engine did next: nothing. The statement kept its captured order. Under planned, this is the moment the plan could have moved by itself. Under fixed, the engine hands over a ready CREATE PLAN statement, and a person or an agent decides whether to run it.

The whole loop is SQL. sys.statement_stats shows, for each shape, where its order last came from (plan_source). ADVISE PLAN proposes, CREATE PLAN adopts, and ANALYZE confirms. A DBA and an AI agent use the same views and the same statements.

The statistics the search reads are managed the same way. An operator can gather a table’s statistics as pending, then publish, lock or restore them (GATHER STATISTICS ON t PENDING, PUBLISH, LOCK, RESTORE ... TO VERSION n), and the engine never gathers that object by itself. A plan that is already captured does not change when the statistics do.

What it buys

  • A plan change has an author. A plan moves only because someone issued a statement. The change can be found and attributed, and ALTER PLAN ... DISABLE undoes it.
  • Yesterday’s behavior is today’s. Growing data, refreshed statistics and a restart do not re-plan a captured shape.
  • Value-dependent plans are readable. The rule that sends a narrow range one way and a wide range another is text in the catalog, not behavior inside an optimizer.
  • A shape’s statistics describe one thing. Per-shape counters in sys.statement_stats are easier to read when the shape is not switching plans underneath them.
  • Automation is bounded. An agent that tunes plans leaves named rows that a person can list, disable and drop.

What it costs

  • The first plan is an accident of history. The first run after the tables’ sizes are known decides for every later run and every later value. If that moment was unrepresentative, the plan stays that way until someone writes a better one.
  • Plans go stale quietly. This is the mirror image of the regression. Instead of a sudden change nobody made, there is a slow drift nobody corrected. A plan captured at ten thousand rows is still in force at ten million. The engine does not fix it, and it does not tell you unless you ask: ADVISE PLAN runs on request only, with no background advisor.
  • Someone has to own the plans. The work moves from the optimizer to an operator or an agent. For a team with nobody to look, planned may be the better setting.
  • There is more catalog to look after. A plan blocks dropping its table. After a table or column is renamed, an old plan matches no new statement and is still listed as enabled. A shape has at most one administrator’s plan.
  • The rule language is small. A WHEN rule is comparisons over the statement’s values joined by AND, with + and - on integers. There is no OR.
  • The scope is narrow. A plan chooses the inner-join order, the access path and the inner build. It cannot ask for a rewrite: the engine never turns a subquery into a join, and no plan option does either.
  • Row order without ORDER BY is no promise. Once the engine or a plan may choose a join order, a statement that needs an order has to ask for one.
  • The mechanism is not free. A capture reaches the catalog about a second after it is made, so a crash inside that window loses it and the shape is captured again, possibly differently. A statement that runs in an order other than its written one is compiled twice, and there is no plan cache.
  • Automation needs a plan to take effect. The Cabin controller can build a Cabin for a hot column, but a statement reads through it only when a plan names it. Turning the controller on does not speed anything up by itself.

Why KDBS chose this

It is a default, not a prohibition. Whether the database may change plans by itself is an option the operator chooses, and planned is there for those who want it. The default answers a narrower question: which failure do you prefer when nobody is watching? A regression is sudden and arrives on its own schedule. Staleness is gradual, shows up in statement statistics, and can be fixed on yours. For an OLTP engine, where a small number of statement shapes run over and over and the slowest runs matter most, KDBS takes the second.

It keeps a promise the engine already made. The earlier design let you predict a statement’s cost from its text, because the plan depended only on the statement’s shape and the catalog. When the join-order search arrived, that could have been lost. Instead the search’s knowledge was kept and its authority removed. It decides once per shape. After that it advises.

It matches the rest of the engine. In KDBS, a decision that changes what a statement does is an explicit act. Freeing a deleted row’s key is a PURGE, not a background task. The structures the engine builds by itself cannot change a result. With managed plans, they cannot change a statement’s path either.

The operator may be a program. The decision behind this design was that the plan becomes something a DBA or an AI agent manages, all the way down, like the statistics. A self-tuning optimizer leaves nothing to read. An agent that issues CREATE PLAN leaves an object with a name, an origin and a state, through the same statements a person would use. Nothing in the surface is specific to agents.

Summary

Typical cost-based engineKDBS (join_order = fixed)
Who picks the planThe optimizer, at each compileThe search, once per shape; after that an operator
When a plan changesWhen statistics moveWhen someone issues CREATE, ALTER or DROP PLAN, or DDL
Plans that depend on valuesThe optimizer looks at the valuesVariants with a WHEN rule written in the plan
Where plan control livesHints in the SQL, or an add-on featureRows in sys.plans
The cost modelDecidesDecides once, then advises
Main riskA sudden regressionA stale plan

For where this started, when joins simply ran in the order written, see No VACUUM, no query planner.

More from the blog