Fleet-Wide Oracle Plan Stability: Detecting Regressions Without Automating an Outage
Content reflects the state as of May 2026. AI tooling and model capabilities in this area change frequently.
A slow SQL alert is not evidence that the execution plan is wrong, and a historical plan hash is not proof that the old plan is still safe; autonomous plan control must distinguish a plan regression from changed work, changed data, and system-wide contention before it mutates production.
TL;DR
- Problem: Dividing cumulative
V$SQLSTATStotals, ignoring row-volume shifts, or blindly purging the shared pool turns plan-stability automation into an outage amplifier.- Answer: Compute reset- and RAC-aware interval deltas, verify Diagnostics Pack entitlements, load candidate baselines with
fixed => 'NO'on a single canary cohort, and gate promotion on post-change deltas.- Watch out: An
ENABLED=YESbaseline does not guarantee plan reproduction—if an index or partition changed, the baseline is silently skipped unless post-changeV$SQLverification confirms it.
Production Context: 2022 | Oracle 19c Fleet Operations | Technical Review: September 2026
Situation
Oracle’s cost-based optimizer chooses a plan from estimates: object statistics, column distributions, system statistics, optimizer settings, constraints, bind information, and transformations available at parse time. That is a feature, not a defect. Data and execution environments change, so a plan that was good last quarter is not permanently correct.
Plan instability becomes operationally important when a high-volume statement changes plan and consumes materially more database time per unit of work. Bind peeking can make the first hard parse sensitive to one bind value. Adaptive cursor sharing can create multiple child cursors for different selectivity ranges. Statistics gathering can change cardinality estimates. Schema changes, invalidation, an Oracle release update, service placement, and a different optimizer environment can all produce a different plan.
A single database can be investigated manually. A fleet cannot depend on an expert noticing every plan transition, reconstructing its context, finding a reproducible alternative, and changing SQL Plan Management (SPM) during an incident. The useful automation boundary is therefore not “pin every slow query.” It is a closed control loop that detects with valid measurements, gathers evidence, applies only authorized changes, and can prove whether the intervention helped.
The Problem
Why Naive Regression Automation Is Dangerous
Four implementation errors turn a plan-stability service into an outage amplifier:
- Treating cumulative counters as interval rates.
V$SQLSTATS.EXECUTIONS,ELAPSED_TIME,CPU_TIME,BUFFER_GETS, and wait-time columns accumulate over the cursor’s retained lifetime. Dividing cumulative elapsed time by cumulative executions produces a lifetime average, not “the last minute.” Filtering onLAST_ACTIVE_TIMEdoes not change that. A collector must persist two observations and compute deltas, while detecting instance restarts, cursor aging, counter resets, and RAC instance boundaries. - Equating latency with plan quality. A statement can slow while its plan hash remains unchanged because storage is saturated, rows returned per execution increased, a blocking transaction appeared, CPU entitlement changed, or a remote dependency degraded. Conversely, a plan hash can change without user impact. Remediation requires a plan transition plus a stable unit-of-work comparison and enough samples to reject noise.
- Assuming SPM “forces” an arbitrary plan. A SQL plan baseline contains accepted plans for matching SQL text. The optimizer selects among enabled, accepted, reproducible plans; fixed plans receive preference over nonfixed plans, but a referenced object or access path can disappear and make a plan non-reproducible. SQL profiles, patches, outlines, hints, parameters, and adaptive behavior are distinct mechanisms. A baseline is a governed optimizer input, not a byte-for-byte execution guarantee.
- Ignoring licensing and privilege boundaries. AWR, ASH, and direct access to their underlying data are Diagnostics Pack features under Oracle’s licensing guide. Some SQL tuning facilities require Tuning Pack. A design that silently queries
DBA_HIST_*orV$ACTIVE_SESSION_HISTORYeverywhere can create compliance exposure. The control plane must select an entitled data path per database and use a narrowly scoped executor for changes.
The engineering question is: How can a fleet control plane identify a real plan regression, select a reproducible candidate, roll it out with bounded blast radius, and reverse it without trusting fabricated precision or granting broad DBA access to every collector?
Options Considered
Four approaches define the design space for fleet-wide Oracle plan stability.
| Strategy | False-Positive Risk | Parse / Blast Risk | Licensing Safety | Verdict |
|---|---|---|---|---|
| Naive Latency Alerting | Very high (totals & locks) | Manual triage only | Often queries ASH blindly | Rejected — noisy |
| Auto-Purge Shared Pool | Medium | Hard-parse storm | N/A | Rejected — dangerous |
| Global Fixed SPM Pin | High (bind-class skew) | Locks suboptimal plan | Needs STS/AWR care | Human PE approval only |
| Delta + Nonfixed Canary | Low (work-normalized) | Bounded + reversible | Per-DB entitlement check | Selected |
Naive latency alerting was rejected because raw V$SQLSTATS ratios and unnormalized elapsed times fire whenever row counts or lock waits spike. Auto-purging the shared pool (DBMS_SHARED_POOL.PURGE) triggers hard-parse storms under concurrency without guaranteeing a better plan. Global fixed SPM pinning locks a single plan across all bind selectivity classes, which breaks skewed workloads. Delta-based detection paired with a nonfixed canary baseline isolates true plan regressions and keeps every mutation reversible.
The Guarded Plan-Stability Control Loop
Separate observation, decision, mutation, and verification. A collector exports raw monotonic counters. A detector computes interval features and opens a candidate incident. A policy engine decides whether the statement is eligible for automated or approved action. A database-local executor performs one idempotent SPM change. A verifier measures new intervals and either promotes, disables, or rolls back that change.
1. Measure Counter Deltas Correctly
Poll a bounded, allowlisted workload rather than scanning every statement at high frequency. Persist a key such as (dbid, instance_number, startup_time, con_id, sql_id, plan_hash_value) with collection time and cumulative values. The SQL below returns observations; it does not claim that they are interval metrics:
SELECT con_id,
sql_id,
plan_hash_value,
executions,
elapsed_time,
cpu_time,
buffer_gets,
disk_reads,
rows_processed,
application_wait_time,
concurrency_wait_time,
user_io_wait_time,
invalidations,
last_active_time
FROM v$sqlstats
WHERE last_active_time >= SYSDATE - (5 / 1440)
AND executions > 0;
For consecutive observations with the same startup identity, calculate delta_elapsed / delta_executions, delta_cpu / delta_executions, and similar ratios only when delta_executions > 0 and all required deltas are nonnegative. Treat a missing previous row, a lower counter, a changed startup identity, or a collector gap beyond policy as a new series with no rate. Oracle documents elapsed time for parallel execution as coordinator time plus parallel-server time, so it is database work rather than end-user wall time; do not compare serial and parallel samples as if the measure were identical.
RAC requires per-instance observations before aggregation. A global average can hide one instance using a different child cursor or serving a different bind population. Multitenant fleets also need CON_ID; the same SQL can behave differently across PDBs with different data and services.
The detector should require all of the following before opening a regression candidate:
- The plan hash changed, or the same plan became non-reproducible and a different child cursor took traffic.
- The new plan has enough completed executions and database time to exceed a minimum evidence floor.
- Per-execution elapsed time, CPU time, buffer gets, or physical reads crossed a versioned threshold with a confidence band, not a single point estimate.
- Rows processed per execution and the application operation class remain comparable. A tenfold increase in requested rows is changed work, not automatically a regression.
- Wait deltas do not point primarily to application locks, cluster contention, resource-manager throttling, or an external bottleneck that a plan baseline cannot fix.
- The regression is observed independently on more than one interval, unless an explicit emergency policy applies.
ASH can add sampled session context when the database is entitled to Diagnostics Pack, but samples are not completed transactions and must not be presented as exact request counts. Where packs are unavailable, use permitted dynamic views, application latency, service metrics, and the collector’s own deltas. Store the entitlement decision beside every detector configuration.
2. Build a Reproducible Plan Evidence Package
Do not choose a candidate solely because its plan hash was once fast. Capture:
- exact and force-matching SQL signatures, normalized SQL identity, parsing schema, PDB, and optimizer environment;
- current and candidate plan operations, predicates, object owners, object IDs, index visibility and status, and partition assumptions;
- statistics timestamps, histogram metadata, bind-sensitivity indicators, child-cursor reasons, and relevant parameter differences;
- interval evidence for elapsed time, CPU, logical I/O, physical I/O, rows processed, and wait composition;
- the source of the candidate: current cursor cache, a licensed AWR interval, a governed SQL tuning set, or a transported baseline;
- license entitlement, approval class, expiry, owner, ticket, and rollback command.
DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE accepts both sql_id and plan_hash_value, so it is the simplest exact load path when the known-good plan is still present. After the executor has verified that an equivalent baseline is not already present, a safe initial load is enabled and nonfixed:
DECLARE
l_loaded PLS_INTEGER;
BEGIN
l_loaded := DBMS_SPM.LOAD_PLANS_FROM_CURSOR_CACHE(
sql_id => :sql_id,
plan_hash_value => :good_plan_hash,
fixed => 'NO',
enabled => 'YES'
);
IF l_loaded <> 1 THEN
RAISE_APPLICATION_ERROR(-20001, 'Expected exactly one plan to be loaded');
END IF;
END;
/
Historical recovery needs more care. Oracle’s LOAD_PLANS_FROM_AWR basic_filter is applied to SQL text; it is not a documented plan-hash selector. A narrow snapshot range may still contain multiple plans. If exact historical selection matters, build and inspect a SQL tuning set through the licensed, documented workflow, then load the selected plan from that set. Never concatenate untrusted SQL IDs into a dynamic filter, and never query Oracle’s internal WRH$_ tables as an automation contract.
The executor should not search DBA_SQL_PLAN_BASELINES for the first row with origin MANUAL-LOAD: concurrent work or an existing baseline can make that the wrong plan. Record baseline inventory before and after the load, match the expected SQL handle and plan attributes, and require a single unambiguous new or existing candidate. DBMS_SQLTUNE.SQLTEXT_TO_SIGNATURE is the documented signature function; there is no DBMS_SPM.SQL_TEXT_TO_SIGNATURE API.
3. Make Mutation Bounded and Reversible
Plan changes are production changes. Give the read-only collector no execute privilege on DBMS_SPM. Route mutations through a database-local package that validates an allowlisted PDB, SQL signature, plan hash, request ID, and approved action. The package should reject DDL, recursive SQL, unregistered statements, stale approvals, and a second active change for the same SQL handle.
Avoid broad shared-pool purges. DBMS_SHARED_POOL.PURGE is not an atomic switch and can create hard-parse load; finding an address with a scalar subquery also does not prove every relevant child cursor is gone. Prefer a controlled service or session canary where possible. If cursor invalidation is required, treat it as a separate, rate-limited change with a measured parse-capacity budget and a tested rollback.
How It Rolls Out
Start on one database or one service cohort rather than mutating the entire fleet. Verification compares multiple post-change intervals using the same unit-of-work checks as detection: confirm the intended baseline is active in V$SQL, verify database work per execution improves, and confirm no new parse or concurrency pressure appears. A fixed execution count such as “50 executions” is not universally sufficient; sample size depends on variance, execution frequency, and business risk.
Rollback normally means disabling the newly introduced plan baseline (DBMS_SPM.ALTER_SQL_PLAN_BASELINE(..., attribute_name => 'ENABLED', attribute_value => 'NO')) or restoring its prior attributes, then allowing a controlled reparse. Dropping evidence immediately destroys the forensic record. Mark uncertain outcomes as VERIFYING_UNKNOWN, stop further rollout, and require observation before another mutation.
In Practice
The documented Oracle behavior supports a conservative operating pattern rather than an unqualified autonomous fixer. SPM can load plans from the cursor cache, AWR, or SQL tuning sets. Loaded plans can be enabled, accepted, and fixed or nonfixed. Oracle’s plan-selection rules prefer reproducible fixed plans over nonfixed plans, but among the eligible set the optimizer still costs plans. Oracle also provides evolve tasks to test nonaccepted plans before acceptance. These mechanisms justify a lifecycle with explicit evidence and approval; they do not justify inventing fleet success rates or recovery times.
A useful qualification exercise uses a representative staging clone and two known plans for an allowlisted statement:
- Capture a minimum of two stable counter intervals for each plan under the same bind class, service, data snapshot, and concurrency envelope.
- Load the candidate as nonfixed and verify its
SQL_HANDLE,PLAN_NAME,ENABLED,ACCEPTED,FIXED, origin, and reproduction status through documented views. - Execute through the application service, not only a privileged SQL session. Confirm the observed plan through
V$SQLor the licensed historical path and compare application latency with database-work deltas. - Disable the candidate and force only the minimum controlled reparse required by the test. Verify that the prior eligible plan returns.
- Restart the executor and redeliver the same request ID. It must report the existing mutation, not load another baseline or alter unrelated plans.
- Make a test index unusable in the disposable staging clone. The workflow must detect that the plan is not safely reproducible and stop, not declare SPM broken or apply a hidden optimizer parameter.
The evidence from this exercise becomes the admission contract for automation. Low-risk, pre-authorized statements may progress from detect-only to canary automation. Revenue-critical DML, statements with unstable bind classes, and changes requiring fixed plans should retain human approval until repeated tests demonstrate safe boundaries.
Where It Breaks
| Operational scenario | Physical failure mechanism | Consequence | Mitigation protocol |
|---|---|---|---|
| Collector treats totals as rates | Cumulative V$SQLSTATS values are divided without a prior observation or across a restart. | Lifetime history or a reset appears as a sudden regression. | Persist raw observations, key by startup and instance identity, reject negative deltas, and suppress decisions until a second valid interval exists. |
| Bind populations change | The new interval serves a more expensive selectivity class even though SQL text is identical. | Automation pins a plan optimized for a different bind class and harms valid traffic. | Segment evidence by service or bind class where permitted, inspect adaptive cursor behavior, and exclude statements whose workload cannot be classified safely. |
| Plan is no longer reproducible | An index, partition, object, privilege, or optimizer capability used by the stored outline changed. | The baseline is unused or another eligible plan is selected. | Validate dependencies before mutation and verify actual plan use afterward; never equate ENABLED=YES with successful reproduction. |
| AWR or ASH is used without entitlement | A collector queries licensed views or APIs on a database without the required management pack. | The monitoring design creates licensing and audit exposure. | Maintain a per-database entitlement registry, enforce alternate collectors, and review current Oracle licensing terms with the contract owner. |
| Concurrent remediators race | Two incidents load, fix, disable, or purge plans for the same SQL handle. | Final baseline attributes are order-dependent and rollback can target the wrong plan. | Serialize by database, PDB, and SQL handle; use immutable request IDs, before-and-after inventory, and compare-and-set state transitions. |
| Shared-pool purge creates a parse storm | Many active cursors are invalidated while foreground sessions reconnect or reparse. | Library-cache and CPU pressure compound the original incident. | Separate invalidation approval, rate-limit it, canary by service, and maintain headroom plus an immediate stop condition. |
| Historical plan fits old data only | Data volume, clustering, partitions, or rows returned per execution changed materially. | The “known-good” plan consumes more work than the current plan. | Reproduce against current representative data, compare work per execution, use nonfixed admission first, and expire emergency baselines. |
| RAC or PDB context is lost | Telemetry is aggregated across instances or the executor connects to CDB$ROOT instead of the target PDB. | The detector hides a localized regression or the baseline is created in the wrong container. | Carry DBID, instance, service, and CON_ID end to end; assert session container and database identity inside the mutation package. |
September 2026 Update
The review date changes the implementation options, not the safety model. Current Oracle 19c documentation remains the authority for a 19c fleet, including the exact Release Update installed. Newer Oracle releases and services may add automatic SPM evolution, quarantine, or managed performance features, but adoption must be based on the target release’s documentation and license terms. Do not project a newer feature backward onto 19c.
OpenTelemetry’s database semantic conventions provide common database client attributes and spans, but they do not establish db.plan_hash_value as a universal standard attribute. A plan hash can be attached as a reviewed custom attribute or event when cardinality and sensitivity controls are understood. It should not be placed on every trace if doing so creates excessive cardinality or exposes SQL identity.
The strongest modernization is operational: version the detector, entitlement policy, mutation package, and baseline expiry rules together. Replay historical observations through a new detector before deployment, shadow its decisions without executing them, and compare candidate volume and false-positive causes. An “AI” classifier can rank incidents, but the enforcement path still needs deterministic gates, explainable evidence, and a bounded rollback.
Key Takeaways
- Never treat
V$SQLSTATStotals as rates: Key observations by(dbid, instance_number, startup_time, con_id, sql_id, plan_hash_value)and compute deltas across two valid intervals. - Normalize for work and waits before blaming the plan: A 10x increase in
ROWS_PROCESSEDper execution or a spike in application lock waits is not a plan regression. - Enforce Diagnostics Pack entitlements in code: Route non-licensed databases away from
DBA_HIST_*andV$ACTIVE_SESSION_HISTORYautomatically. - Load nonfixed canary baselines first: Verify actual reproduction in
V$SQLon one cohort before expanding; never equateENABLED=YESwith plan reproduction. - Disable rather than drop on rollback: Preserving the disabled baseline retains the forensic trail and prevents another worker from re-proposing the same bad plan.
What to Do Next
- Problem: Audit whether fleet alerts derive interval deltas correctly, preserve RAC and PDB identity, distinguish changed work from a changed plan, and respect Diagnostics and Tuning Pack entitlements.
- Solution: Separate read-only observation from a serialized, database-local SPM executor governed by immutable request IDs, explicit candidate evidence, canary scope, and expiry.
- Proof: Reproduce two plans in staging, inject restart, duplicate-delivery, dependency-loss, and parse-pressure failures, then demonstrate both successful verification and a reversible uncertain outcome.
- Action: Deploy the detector in shadow mode first; authorize mutation only for allowlisted SQL after thresholds, privileges, license paths, rollback, and ownership have passed review.
Sources
- Oracle Database 19c Reference — V$SQLSTATS
- Oracle Database 19c SQL Tuning Guide — managing SQL plan baselines
- Oracle Database 19c SQL Tuning Guide — SQL plan management
- Oracle Database 19c PL/SQL Packages Reference — DBMS_SPM
- Oracle Database 19c PL/SQL Packages Reference — DBMS_SQLTUNE
- Oracle Database 19c Reference — DBA_SQL_PLAN_BASELINES
- Oracle Database 19c Licensing Information — management pack features
- OpenTelemetry semantic conventions — database spans
Interactive tools for this topic