Sunday, 29 November 2026

When ORA-04036 Is Not Caused by Application SQL: Tracing PGA Growth to the Optimizer Statistics Advisor

The alert appeared during a maintenance window: ORA-04036: PGA memory used by the instance exceeds PGA_AGGREGATE_LIMIT. Application activity was low, no large reporting batch was running, and the usual PGA consumers such as parallel queries, hash joins, sorts, and PL/SQL collections did not explain the increase.

One Oracle process was still growing. Its module pointed to DBMS_SCHEDULER, and the action belonged to Oracle's automatic optimizer statistics framework. The incident trace later placed the failing allocation inside the Optimizer Statistics Advisor, around the AvoidOutOfRange rule.

This is where a routine ORA-04036 investigation can go in the wrong direction. Increasing the PGA limit may stop the immediate alert, but it can also give a runaway internal task more room to consume memory. The safer approach is to identify the process, separate SQL workarea usage from private memory, correlate the event with automatic maintenance, and preserve the trace before changing anything.


Why This Matters in Production

A quiet application workload does not mean the database is quiet. Maintenance windows often bring statistics collection, advisors, backups, segment work, and application housekeeping together. A system that has plenty of headroom during business hours can come under pressure when these activities overlap.

There is another complication. Oracle automatic tasks can execute through job queue processes. Most SYS and background processes are protected from the normal PGA_AGGREGATE_LIMIT enforcement actions, but job queue processes are an explicit exception. An Oracle-maintained activity can therefore have its call or session terminated when it becomes a major untunable PGA consumer.

The error tells us that Oracle enforced the memory boundary. It does not tell us why the memory grew.


PGA Target and PGA Limit Are Not the Same

PGA_AGGREGATE_TARGET guides automatic workarea sizing for operations such as sorts, hash joins, and bitmap processing. It is a target, not a guarantee that total PGA will remain below the configured value.

PGA_AGGREGATE_LIMIT is the instance-level guardrail. When the limit is crossed, Oracle first terminates calls from sessions using the most untunable PGA. If the instance remains above the limit, Oracle can terminate those sessions. Parallel query processes are treated as one unit for this enforcement.

This distinction changes the troubleshooting path. If SQL workareas account for most of the memory, SQL tuning, parallelism, and concurrency are likely relevant. If workarea usage is modest while one process has a large and growing private allocation, the investigation must move toward PL/SQL, Java, internal metadata structures, or an Oracle maintenance task.


Start With Process Attribution

Do not begin by changing a parameter. Capture the parameter values, the percentage of the limit already consumed, the largest Oracle processes, and active SQL workareas. On RAC, use the global views so that a consumer on another instance is not missed.

SELECT inst_id, name, display_value
FROM   gv$parameter
WHERE  name IN ('pga_aggregate_target', 'pga_aggregate_limit')
ORDER BY inst_id, name;

WITH pga AS ( SELECT inst_id, MAX(CASE WHEN name = 'total PGA allocated' THEN value END) allocated, MAX(CASE WHEN name = 'total PGA inuse' THEN value END) inuse, MAX(CASE WHEN name = 'maximum PGA allocated' THEN value END) max_allocated, MAX(CASE WHEN name = 'total PGA used for auto workareas' THEN value END) auto_workarea FROM   gv$pgastat GROUP BY inst_id
+),
+lim AS (

* SELECT inst_id, TO_NUMBER(value) limit_bytes
* FROM   gv$parameter
* WHERE  name = 'pga_aggregate_limit'
  +)
  +SELECT p.inst_id,

    ROUND(p.allocated / 1024 / 1024) allocated_mb,
    ROUND(p.inuse / 1024 / 1024) inuse_mb,
    ROUND(p.max_allocated / 1024 / 1024) max_allocated_mb,
    ROUND(p.auto_workarea / 1024 / 1024) auto_workarea_mb,
    ROUND(l.limit_bytes / 1024 / 1024) limit_mb,
    ROUND(100 * p.allocated / NULLIF(l.limit_bytes, 0), 1) limit_used_pct


FROM   pga p
JOIN   lim l ON l.inst_id = p.inst_id
ORDER BY p.inst_id;

SELECT *
FROM (

SELECT p.inst_id, p.spid, s.sid, s.serial#,
      NVL(s.username, '(background)') username,
      s.program, s.module, s.action, s.sql_id,
      ROUND(p.pga_used_mem / 1024 / 1024) used_mb,
      ROUND(p.pga_alloc_mem / 1024 / 1024) alloc_mb,
      ROUND(p.pga_freeable_mem / 1024 / 1024) freeable_mb,
      ROUND(p.pga_max_mem / 1024 / 1024) max_mb
 FROM   gv$process p
 LEFT JOIN gv$session s
      ON s.inst_id = p.inst_id
     AND s.paddr = p.addr
 ORDER BY p.pga_alloc_mem DESC
  WHERE ROWNUM <= 20;

SELECT inst_id, sid, sql_id, operation_type,

    ROUND(actual_mem_used / 1024 / 1024) actual_mb,
    ROUND(max_mem_used / 1024 / 1024) max_mb,
    ROUND(tempseg_size / 1024 / 1024) temp_mb,
    number_passes
FROM   gv$sql_workarea_active
ORDER BY actual_mem_used DESC;
+


A single snapshot is not enough. Record the same values again after one or two minutes. The growth rate often tells more than the current allocation. A large but stable process may be less urgent than a scheduler slave adding hundreds of megabytes during each sample.

A useful clue is the relationship between total PGA and auto-workarea memory. If total PGA allocated is high but total PGA used for auto workareas remains low, do not spend the first hour tuning sorts that are not responsible for the pressure.


When the Statistics Advisor Becomes the Suspect

The Optimizer Statistics Advisor does not gather a fresh set of statistics. It reviews statistics collection practices and the quality of existing statistics, then stores findings and recommendations. Oracle runs the predefined AUTO_STATS_ADVISOR_TASK once per day in a maintenance window as part of the automatic optimizer statistics collection client.


This distinction matters when choosing a workaround. Disabling the complete auto optimizer stats collection client also interrupts normal automatic statistics gathering. That can solve tonight's memory problem and create next week's plan-stability problem.


Build a timeline using the running scheduler jobs, automatic statistics executions, advisor executions, and finding volume:


+
SELECT client_name, status
FROM   dba_autotask_client
WHERE  client_name = 'auto optimizer stats collection';

SELECT owner, job_name, session_id, running_instance, elapsed_time
FROM   dba_scheduler_running_jobs
ORDER BY elapsed_time DESC;

SELECT opid, origin, status, start_time, end_time,
    completed, failed, timed_out, in_progress

FROM   dba_auto_stat_executions
ORDER BY start_time DESC
FETCH FIRST 30 ROWS ONLY;

SELECT task_name, execution_name, status,

    execution_start, execution_end, error_message


FROM   dba_advisor_executions
WHERE  task_name = 'AUTO_STATS_ADVISOR_TASK'
ORDER BY execution_start DESC
FETCH FIRST 30 ROWS ONLY;

SELECT execution_name, type, COUNT(*) finding_count
FROM   dba_advisor_findings
WHERE  task_name = 'AUTO_STATS_ADVISOR_TASK'
GROUP BY execution_name, type
ORDER BY finding_count DESC;

SELECT DBMS_STATS.REPORT_ADVISOR_TASK(
      'AUTO_STATS_ADVISOR_TASK',
      NULL,

      'TEXT',
      'ALL',
      'ALL'
    ) report

FROM dual;
+

View availability and columns vary across releases. Test the script on the database version you support. A scheduler action alone is only circumstantial evidence. A matching advisor execution, rising process PGA, and a trace from the same interval create a much stronger case.


Read the Trace Without Overclaiming


The alert log tells you that the memory boundary was crossed. The process trace shows what Oracle was doing near the failing allocation. Locate the trace directory and default trace file first:


+
SELECT name, value
FROM   v$diag_info
WHERE  name IN ('Diag Trace', 'Default Trace File');

-- Run from the relevant trace directory on the database host
grep -nE 'ORA-04036|ORA$AT_OS_OPT|qosadv|Just allocated' *.trc
+

In the production case behind this article, the trace recorded a 33,554,432-byte allocation, exactly 32 MB, immediately before Oracle prepared for a PGA limit error. The short stack included functions associated with generating an AvoidOutOfRange finding and creating an internal advisor object.


That is strong evidence for this incident, but it should not be turned into a universal rule. One captured 32 MB allocation does not prove that every heap extension was 32 MB. The conclusion becomes stronger only when repeated process samples or multiple trace entries show the same staircase pattern.


The qosadv* function names are undocumented implementation details and can change between Release Updates. Use them to support an Oracle Service Request, not as a stable interface or a shortcut to a final diagnosis.



Why AvoidOutOfRange Can Become Expensive

Column statistics store low and high values that help the optimizer estimate selectivity. After a bulk load or continuous insertion into a growing key, new values may sit outside the recorded range. For example, the stored high value may be 500000 while newly inserted rows already contain values above 700000.


The AvoidOutOfRange rule checks statistics practices that can leave the optimizer exposed to this estimation problem. The rule is useful. The risk is the amount of metadata it may need to evaluate in a large database.


The following conditions deserve review, but none of them should be declared the cause until evidence confirms it:


  • Large numbers of tables, partitions, and subpartitions.

  • Heavy DML or bulk loads after the last statistics collection.

  • Many objects with stale or missing statistics.

  • A large volume of advisor findings or retained advisor history.

  • A release-specific defect fixed by a later RU or one-off patch.


Gathering statistics more frequently across the entire database is not automatically the answer. It can increase CPU, I/O, maintenance duration, and cursor invalidation. Concentrate on volatile schemas, range-growing columns, and partition strategies that have been tested against the actual workload.


Containment and Long-Term Remediation

Containment should be narrow, reversible, and based on a confirmed consumer. If the Statistics Advisor task is currently executing, preserve the evidence and cancel that execution before disabling a broader automatic maintenance client.


+
-- Use only after confirming that AUTO_STATS_ADVISOR_TASK is executing
EXEC DBMS_STATS.CANCEL_ADVISOR_TASK('AUTO_STATS_ADVISOR_TASK');

+-- Confirm the exact rule name on this database release
SELECT rule_id, name, rule_type, description
FROM   v$stats_advisor_rules
WHERE  UPPER(name) = 'AVOIDOUTOFRANGE';

+-- Targeted workaround where supported and approved
VARIABLE cfg CLOB

BEGIN

:cfg := DBMS_STATS.CONFIGURE_ADVISOR_RULE_FILTER(

         task_name          => 'AUTO_STATS_ADVISOR_TASK',

         stats_adv_opr_type => 'EXECUTE',

         rule_name          => 'AvoidOutOfRange',

         action             => 'SHOW');


END;
/
PRINT cfg

BEGIN
cfg := DBMS_STATS.CONFIGURE_ADVISOR_RULE_FILTER(
         task_name          => 'AUTO_STATS_ADVISOR_TASK',
         stats_adv_opr_type => 'EXECUTE',
         rule_name          => 'AvoidOutOfRange',
         action             => 'DISABLE');

END;
/
PRINT cfg

+-- Re-enable after patch validation by repeating the call with action => 'ENABLE'.
+

These operations require the appropriate privileges and must be validated on the same database release and RU. Changes to the predefined SYS-owned task should follow change control and, for a suspected product defect, Oracle Support guidance.


If targeted control is unavailable, Oracle documents DBMS_AUTO_TASK_ADMIN.DISABLE for the complete automatic statistics client. Treat that as a broad emergency workaround. Define how statistics will be maintained while it is disabled and set a firm date for re-enabling it.


A sensible production sequence


  1. Preserve the alert log, process trace, PGA samples, advisor history, and exact RU details.

  2. Cancel only the confirmed running advisor execution.

  3. Use a rule-level or window-specific workaround where the release supports it.

  4. Check for a matching bug and patch recommendation through an Oracle SR.

  5. Test the fix under a representative maintenance workload.

  6. Remove the workaround, restore normal automation, and monitor several maintenance windows.


Raising PGA_AGGREGATE_LIMIT may buy time only when the host has verified memory headroom. It is not a repair for unbounded private memory growth. A larger limit can move the failure from an Oracle error to swap pressure or an operating-system kill.


Oracle and PostgreSQL Handle This Differently

PostgreSQL does not have an exact equivalent of Oracle's instance-wide PGA_AGGREGATE_LIMIT. Settings such as work_mem, maintenance_work_mem, and autovacuum_work_mem control important memory areas, but work_mem can apply to each plan operation and each parallel worker. Total memory can therefore be much larger than the parameter value suggests.


AreaOraclePostgreSQL
Private execution memoryPGA per Oracle processBackend process memory
Common tuning controlPGA_AGGREGATE_TARGETwork_mem
Database-wide hard ceilingPGA_AGGREGATE_LIMITNo exact built-in equivalent
Parallelism riskParallel query is treated as a unit during limit enforcementwork_mem can apply to the leader and each worker
Internal maintenanceScheduler and job queue tasksAutovacuum and maintenance workers
Final protectionOracle can terminate calls or sessionsOS, cgroup, container limit, or OOM killer may intervene

The shared lesson is that one memory parameter never describes the complete workload. SQL plan nodes, parallel workers, session concurrency, and maintenance activity must be sized together.


Mini Case Study: A Quiet-Window PGA Spike

Problem

Aggregate PGA increased quickly during a weekend maintenance window even though business throughput was low. ORA-04036 appeared in the alert log, and the largest process belonged to a scheduler slave running an Oracle automatic statistics action.


Investigation

Active SQL workareas did not explain the process allocation. Repeated snapshots showed staircase-like private memory growth. The Statistics Advisor execution overlapped the alert, while the trace placed a 32 MB allocation in a qosadv* path associated with AvoidOutOfRange finding generation.


Root cause and fix

The evidence supported excessive untunable PGA allocation while the Optimizer Statistics Advisor created internal finding objects. The running execution was canceled to stabilize the instance. Normal statistics gathering was retained, while a narrowly scoped rule workaround was used only after release-specific validation. The permanent path was to obtain Oracle's RU or one-off patch recommendation, test it, remove the workaround, and observe later maintenance windows.


Lessons From the Field

  • Treat ORA-04036 as the enforcement event, not the root-cause statement.

  • Capture process growth over time. One high-memory snapshot does not show whether the process is stable or still expanding.

  • Store instance ID, SPID, SID, serial number, module, action, SQL ID, allocation, and maximum allocation in the same monitoring record.

  • Monitor each RAC instance independently instead of averaging memory across the cluster.

  • Check maintenance overlap. Statistics, advisors, backups, and application batches can compete even when user traffic is low.

  • Preserve the trace before restarting the instance, purging advisor data, or terminating sessions.

  • Do not permanently solve internal PGA growth by repeatedly raising the limit.


Frequently Asked Questions

Does ORA-04036 always mean the PGA limit is too low?

No. The limit may be undersized for legitimate concurrency, but it may also be correctly stopping a runaway SQL statement, PL/SQL allocation, parallel workload, or internal task. Identify the consumer before resizing.


Can an Oracle automatic statistics task be terminated by the limit?

Yes. Job queue processes are not covered by the same enforcement exemption as most SYS and background processes. An automatic task running through a job queue process can be affected.


Should I disable automatic optimizer statistics collection?

Only as a short, approved emergency measure when narrower containment is unavailable. It disables more than the Statistics Advisor and can leave objects with stale statistics.


Does a 32 MB allocation prove an Oracle memory leak?

No. It proves that one 32 MB allocation was captured at that point. Repeated growth with the same stack and a matching advisor timeline strengthens the diagnosis, but Oracle Support should confirm the defect and patch.


Will increasing PGA_AGGREGATE_TARGET prevent ORA-04036?

Not necessarily. The target mainly guides tunable workareas. Untunable private allocations can continue growing, and hard enforcement still occurs at PGA_AGGREGATE_LIMIT.


Conclusion

ORA-04036 often receives a quick response: increase the limit and move on. That may restore service, but it does not answer the question that matters - which process consumed the untunable memory, and what was it doing?

When the consumer is the automatic Optimizer Statistics Advisor, the normal SQL-tuning workflow is incomplete. A reliable diagnosis connects four layers: instance PGA pressure, process-level growth, scheduler and advisor history, and the allocation stack in the trace. The AvoidOutOfRange and qosadv* evidence is meaningful when those layers agree. It should not be presented as the explanation for every ORA-04036.

Containment requires the same discipline. Cancel the confirmed execution before disabling the complete statistics client. Prefer a tested and reversible rule-level workaround where supported. Keep normal statistics collection working wherever possible, then use the evidence to check the RU level, open an Oracle SR, and test the recommended patch under realistic maintenance load.

Before the next maintenance window, review the monitoring. Capture the top PGA processes, their growth delta, module and action, workarea usage, and automatic task history for every RAC instance. The next ORA-04036 should start an evidence-led investigation, not another round of parameter guessing.


References


Have you encountered ORA-04036 from an Oracle maintenance task rather than application SQL? Share the database release and the evidence that helped you isolate the consumer.



No comments:

Post a Comment