Showing posts with label result cache. Show all posts
Showing posts with label result cache. Show all posts

Wednesday, January 1, 2014

Parallel Query Used for Result Cache Access

On a new deployment it was discovered that wait class Other was taking a significant portion of the wait time on a business critical SQL (denoted bqm in this case). Comparing similar deployment in the past, it was clear that wait class Other was a new addition and SQL didn't exhibit this behavior before. Below is the screenshot of the em console.

Looking at the breakdown of the wait events for the SQL it was seen that majority of waits were related to parallel query.

Beside the parallel query related wait events one other thing that stood out was the result cache contention. There has been a previous experience with result cache contention that manifested as a latch free event. However in this case latch free wasn't the only prominent wait event. Strange thing was that query was not suppose to use parallelism when executing. None of the underlying table used had degree greater than 1 (None of the reasons mentioned in 196938.1 were there). Parallel query related parameters were set at default.
NAME                                     VALUE
---------------------------------------- ----------
parallel_server                          TRUE
parallel_server_instances                3
parallel_min_percent                     0
parallel_min_servers                     0
parallel_max_servers                     960
parallel_instance_group
parallel_execution_message_size          16384
parallel_degree_policy                   MANUAL
parallel_adaptive_multi_user             TRUE
parallel_threads_per_cpu                 2
parallel_automatic_tuning                FALSE
parallel_io_cap_enabled                  FALSE
parallel_min_time_threshold              AUTO
parallel_degree_limit                    CPU
parallel_force_local                     FALSE
parallel_servers_target                  384
parallel_degree_policy was introduced on 11.2 which "specifies whether or not automatic degree of Parallelism, statement queuing, and in-memory parallel execution will be enabled". Setting this to manual disable this feature and behavior is same as 11.1. Application user session did have pq_status enabled (1289785.1) and setting parallel_max_servers to 0 disabled it (alter session disable parallel query wasn't an option in this case) but still didn't eliminate the parallel query related waits.
Another thing noticed was that only some of the session ran in parallel while others did not. In the above image session 2687 ran in parallel (indicated by QC SID column) while other session did not run in parallel. This session details show parallel query, result cache wait events.

Result cache contention was understandable since the query did employ a function on it's select clause which had result cache enabled. (eg. select myfunc(column_id), col2, col3...., result cache was enabled on "myfunc" function). But how the parallel query fit in wasn't clear and there was a clear increase of the parallel query related wait events since this deployment. 1,2 and 3 are RAC instance IDs
Latch free waits and wait times

enq: PS - contention waits and wait times

enq: RC - Result Cache: Contention waits and wait times

Reliable message waits and wait times

Although the wait time values could be considered low, when compared to the situation before where these were near 0, this is a significant increase.



Further monitoring showed that beside this particular SQL no other application SQL was using parallelism except for the following non application SQL.

Looking at the SQL, this is clearly related to result cache access. There was no information available on the oracle reference documentation on this view (it could be an internal view not for end users). Could only guess what is used for, where clause provides a good clue ,instance id and key, possible result cache key. Querying the execution plan of this shows parallel query being used
SQL>  select * from table(dbms_xplan.display_CURSOR('8sd1v66dnj4m4'));
SQL_ID  8sd1v66dnj4m4, child number 0
-------------------------------------
select inst_id, blk_num, blk_seq, blk_dat from gv$result_cache_rd where
inst_id = :1 and key = :2

Plan hash value: 238457506

--------------------------------------------------------------------------------------
| Id  | Operation                  | Name               |    TQ  |IN-OUT| PQ Distrib |
--------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT           |                    |        |      |            |
|*  1 |  PX COORDINATOR            |                    |        |      |            |
|   2 |   PX SEND QC (RANDOM)      | :TQ10000           |  Q1,00 | P->S | QC (RAND)  |
|*  3 |    VIEW                    | GV$RESULT_CACHE_RD |  Q1,00 | PCWP |            |
|*  4 |     FIXED TABLE FIXED INDEX| X$QESRCRD (ind:1)  |  Q1,00 | PCWP |            |
--------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(("KEY"=:2 AND "INST_ID"=:1))
   3 - filter(("KEY"=:2 AND "INST_ID"=:1))
   4 - filter("QESRCRD_KEY"=:2)

Note
-----
   - rule based optimizer used (consider using cbo)
So could it be that when a business SQL result in a cache hit, the results are searched in the cache using parallel SQL? Hard to say without exact information on what gv$result_cache_rd is used for. But it's clear that parallel query related waits were caused by this SQL. To test this result cache was removed from the function used in the select clause. This resulted in drop in the parallel query related wait events (20 Dec mark).
latch free waits and wait times

enq: PS - contention waits and wait times

enq: RC - Result Cache: Contention waits and wait times

Reliable message waits and wait times

This confirms that parallel query related waits were due to the result cache access. Removing the result cache from the function also made the average elapsed time for the SQL stable compared to when having result cache.

Update 02 January 2014
Further test has shown the V$RESULT_CACHE_RD comes into in RAC system when a instance request missing result from a result cache of a remote node. Following test case could used to confirm this.
create table x (a number, b number);

create table y (c number, d number);


begin
    for i in 1 .. 10
    loop
    insert into x values(i,round(dbms_random.value(1,10)));
    end loop;
end;
/
begin
    for i in 25 .. 45
    loop
    insert into y values(i,mod(i,10));
    end loop;
end;
/

 
create or replace function myfunc(inum in number) return number
result_cache
as retnum number;
begin
  select b into retnum from x where a=inum;
  return retnum;
end;
/
It is best if the database could be restarted if not shared pool cleared (as such not good to test on a production system). Assuming this is a two node RAC run the following on both nodes
SQL> set line 180
SQL> set pagesize 0
SQL> select * from table(dbms_xplan.display_CURSOR('8sd1v66dnj4m4'));
SQL_ID: 8sd1v66dnj4m4, child number: 0 cannot be found
Since the sql text is Oracle provided it could be assumed that SQL ID (which was identified earlier) will remain the same. This shows that SQL does not exits in the library cache (if DB was restarted, this means it never got executed, assuming not been paged out)
Now on node 1 run the following SQL (output has been truncated)
SQL> select c,myfunc(d) from y;
        25          3
        26          4
        27          1
        28          2
Run the first SQL again and it still gives a negative results
SQL> select * from table(dbms_xplan.display_CURSOR('8sd1v66dnj4m4'));
SQL_ID: 8sd1v66dnj4m4, child number: 0 cannot be found
Parallel result cache access hasn't occurred yet. On the same instance the application SQL could be run many times and SQL (8sd1v66dnj4m4) will not get executed.
Now run the application SQL on the node 2.
SQL> select c,myfunc(d) from y;
        25          3
        26          4
        27          1
        28          2
This time the parallel result cache access query has been executed
SQL> select * from table(dbms_xplan.display_CURSOR('8sd1v66dnj4m4'));
SQL_ID  8sd1v66dnj4m4, child number 0
-------------------------------------
select inst_id, blk_num, blk_seq, blk_dat from gv$result_cache_rd where
inst_id = :1 and key = :2

Plan hash value: 238457506

--------------------------------------------------------------------------------------
| Id  | Operation                  | Name               |    TQ  |IN-OUT| PQ Distrib |
--------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT           |                    |        |      |            |
|*  1 |  PX COORDINATOR            |                    |        |      |            |
|   2 |   PX SEND QC (RANDOM)      | :TQ10000           |  Q1,00 | P->S | QC (RAND)  |
|*  3 |    VIEW                    | GV$RESULT_CACHE_RD |  Q1,00 | PCWP |            |
|*  4 |     FIXED TABLE FIXED INDEX| X$QESRCRD (ind:1)  |  Q1,00 | PCWP |            |
--------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - filter(("KEY"=:2 AND "INST_ID"=:1))
   3 - filter(("KEY"=:2 AND "INST_ID"=:1))
   4 - filter("QESRCRD_KEY"=:2)

Note
-----
   - rule based optimizer used (consider using cbo)


28 rows selected.
This will now be present on the library cache of both instances. This confirms inter instance result cache access is done using parallel query even though database is configured not to use parallel query.
Read Method 3 on this article for explanation on how result cache behave in a 11.2 RAC environment.

Wednesday, September 15, 2010

Closing ResultSet early invalidates result cache

When using the result cache (/*+ result_cache */) in a SQL during the query execution phase all the dependent objects will be identified for the query and will have the status PUBLISHED in result cache object view. But it is during the result fetch phase that the actual result will be cached. Status of the result set in the aforementioned view will be NEW when the first result is fetched and then on will be ByPass for subsequent row fetches for the same result set in the same session, once all the rows are fetched without an error status will be PUBLISHED.

If for some reason result set was closed half way through (or an error happens, which is not considered in this post) the result will have a status of invalid. Subsequent running of the sql will try to create a new result set to cache but will also end of invalid if result set is closed without being traversed the full length.

However if one session traverse the entire result set and subsequent sessions only traverse few rows of the result set, these latter sessions will be using the result cache.

Test case is give below.

1. Create the tables and functions needed

SQL> create table x (a number, b varchar2(100), c as (mod(a,4)));

Table created.

SQL> begin
2 for i in 1 .. 1000
3 loop
4 insert into x (a,b) values (i,i||'abcdefg');
5 end loop;
6 end;
7 /

PL/SQL procedure successfully completed.

create or replace package rescachetest as
type ret_type is ref cursor;
function getvalues return ret_type;
end;
/

create or replace Package Body Rescachetest As

Function Getvalues Return Ret_Type Is

Ret_Val Ret_Type;
Begin
Open Ret_Val For
Select /*+ result_cache */ * From X Where C In (3,4);

return ret_val;
end;
End;
/
This uses the result cache hint inside the pl/sql function which returns a ref cursor type. But it could be verified for pure sql as well. The java code used to test use be used to run both these cases.

2. Run the java code which will take only 90 rows from the result set and close the result set.
public class ResCacheTest {

public static void main(String[] args) {
try {
OracleDataSource dataSource = new OracleDataSource();
dataSource.setURL("jdbc:oracle:thin:@url");
dataSource.setUser("username");
dataSource.setPassword("password");

Connection con = dataSource.getConnection();


// PL/SQL
CallableStatement clm = con.prepareCall("begin ? := rescachetest.getvalues; end;");
clm.registerOutParameter(1, OracleTypes.CURSOR);
clm.execute();


// SQL
// PreparedStatement pr = con.prepareStatement("select /*+ result_cache */ * from X Where C In (3,4)");

// System.out.println("executed");
// Thread.sleep(10000);

ResultSet rs = ((OracleCallableStatement)clm).getCursor(1);

// ResultSet rs = pr.executeQuery();
int i = 0;
while(rs.next()){

i++;
System.out.println(rs.getInt(1)+" "+rs.getString(2));

// System.out.println("get result");
// Thread.sleep(10000);
if(i == 90){
break;
}
}

// System.out.println("closing");
rs.close();
clm.close();
// pr.close();
con.close();
dataSource.close();


} catch (Exception ex) {
Logger.getLogger(ResCacheTest.class.getName()).log(Level.SEVERE, null, ex);
}
}

}
3. ADMon has been used to query the v$result_cache_objects view.

When the clm.execute(); has been called observed the following
When the first row was taken from the result set
Subsequent row fetches
Once the result set was closed after taking 90 rows
4. If the java code was to run without closing the result set after taking 90 rows results will be published in the result cache.
Subsequent execution of java code where result set is closed after taking 90 rows will not result in creating additional invalid result caches as before, and these execution will use the already publish result cache.

Friday, August 27, 2010

"Cache Fusion" Behavior for Result Cache

With Oracle 11gR2 RAC result cache misses will result in result being retreived from another instances. This behavior was not there on 11gR1.

11gR1 PL/SQL Language Refrence guide's Result Caches in Oracle RAC Environment section "Cached results are stored in the system global area (SGA). In an Oracle RAC environment, each database instance has a private function result cache, available only to sessions on that instance. If a required result is missing from the private cache of the local instance, the body of the function executes to compute the result, which is then added to the local cache. The result is not retrieved from the private cache of another instance."

From 11gR2 PL/SQL Language Refrence guide's Result Caches in Oracle RAC Environment section "Cached results are stored in the system global area (SGA). In an Oracle RAC environment, each database instance manages its own local function result cache. However, the contents of the local result cache are accessible to sessions attached to other Oracle RAC instances. If a required result is missing from the result cache of the local instance, the result might be retrieved from the local cache of another instance, instead of being locally computed."

Other behaviors are same such as result cache invalidations, where invalidation is global.

A new hidden parameter has been introduced in 11gR2 to control this result cache behavior
_result_cache_global TRUE (default) boolean (type) Are results available globally across RAC?
v$result_cache_statistics view has two new statistics
Global Hit Count
Global Miss Count
(Undocumented at the time of writing)

Thursday, August 19, 2010

Result Cache in PL/SQL Packages

To use result cache with any function or procedure in a PL/SQL package result_cache must be defined on the specification.
Create Or Replace Package Result_Cache_Test As
Function Get_Country_City (In_City In Varchar2, In_Country In Varchar2)
Return Varchar2
result_cache;
end;
/
On the package body list the set of tables underlying sql relies on
Create Or Replace Package Body Result_Cache_Test As
Function Get_Country_City(In_City In Varchar2, In_Country In Varchar2)
Return Varchar2
Result_Cache
Relies_On (city,country)
Is
Ret_City Varchar2(200);
ret_country varchar2(200);
Begin
Select Ci.Name,Co.Name Into Ret_City,Ret_Country
From City Ci, Country Co
Where Ci.Country = Co.Code
And Ci.Code = In_City
And Co.Code = In_Country;

return ret_city || ':'||ret_country;
end;
end;
/
Test with PL/SQL Code
set serveroutput on
Declare
val varchar2(400);
Begin
Val := Result_Cache_Test.Get_Country_City('SIN','SG');
dbms_output.put_line(val);
end;
/
Or to know the effects of Result Cache Latch on concurrent access simulate with java code. Main class
public class Main {

public static void main(String[] args) {

try {

OracleDataSource dataSource = new OracleDataSource();
dataSource.setURL("jdbc:oracle:thin:@url");
dataSource.setUser("username");
dataSource.setPassword("password");

String[][] cities = {{"CMB","LK"},
{"LAX","US"},
{"SIN","SG"},
{"LON","GB"}
};

int loops = 1000;
WorkerThread[] threads = new WorkerThread[400];
String sql1 = "begin ? := result_cache_test.Get_Country_City(?,?); end;";

for (int i = 0 ; i < threads.length ; i++){

threads[i] = new WorkerThread(dataSource.getConnection(), sql1,cities,loops);

}

for(int i = 0 ; i < threads.length; i++){

threads[i].start();
}

} catch (Exception ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Worker Class
public class WorkerThread extends Thread {

private Connection con;
String sql;
String[][] data;
int loops;

public WorkerThread(Connection con, String sql, String[][] data, int loops) {

this.con = con;
this.sql = sql;
this.data = data;
this.loops = loops;
}

@Override
public void run() {
try {
CallableStatement clm;

for (int i = 0; i < loops; i++) {

clm = con.prepareCall(sql);
clm.registerOutParameter(1, Types.VARCHAR);
clm.setString(2, data[i%4][0]);
clm.setString(3, data[i%4][1]);
clm.execute();
String out = clm.getString(1);
Logger.getLogger(WorkerThread.class.getName()).log(Level.INFO,getName() + " "+out);
clm.close();
}

con.close();

} catch (SQLException ex) {
Logger.getLogger(WorkerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
View latch misses, sleeps with
select name,gets, misses, sleeps, wait_time 
from V$latch where Name like '%Result%';

NAME GETS MISSES SLEEPS WAIT_TIME
---------------------- ---------- ---------- ---------- ----------
Result Cache: Latch 1576450 13 3 681
Result Cache: SO Latch 2439 5 2 787
This test was done on a 4 cpu server on 11gR1 with PSU 11.1.0.7.4 applied.

As of 11gR2 'relies_on' is deprecated. From PL/SQL Language Ref Guide "Release 11.2, the database detects all data sources that are queried while a result-cached function is running, and relies_on_clause does nothing. This clause is deprecated."

Wednesday, December 2, 2009

Result Cache for Ref Cursor returning PL/SQL codes

According to Oracle documentation if a PL/SQL SP is returning a ref cursor then result cache is not supported. But there's a way to circumvent with somewhat beneficial results.

Below is a package written for the HR sample schema

create or replace package emps_pkg as

type detail is ref cursor;

function getempdetails (options in INTEGER, departname in VARCHAR2, jobtitle in VARCHAR2) return detail;

end;
/


create or replace package body emps_pkg as

function getempdetails(options in INTEGER,departname in VARCHAR2, jobtitle in VARCHAR2) return detail is

employees detail;
main_query VARCHAR2(2000) := 'select /*+ result_cache */ e.* from employees e,departments d,jobs j
where e.department_id = d.department_id and j.job_id = e.job_id ';
begin
if options = 1 then
main_query := main_query ||'and d.department_name=:1';
open employees for main_query using departname;

return employees;

else
main_query := main_query ||'and j.job_title=:1';

open employees for main_query using jobtitle;

return employees;
end IF ;
end;
end;
/


Package body contains some dynamic sql (there's no real logic behind this package only to demonstrate the use of result cache) which is constructed with the result_cache hint.

execute the package code and observe the plan


select emps_pkg.getempdetails(2,'Purchasing','Purchasing Manager') from dual;
select * from table(dbms_xplan.display_cursor(null,null,'ALL'));

Plan hash value: 980169617

------------------------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
------------------------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | | | 4 (100)| |
| 1 | RESULT CACHE | a68hth9dfygb5ddg0hr8hnty9b | | | | |
| 2 | NESTED LOOPS | | | | | |
| 3 | NESTED LOOPS | | 6 | 570 | 4 (0)| 00:00:01 |
|* 4 | TABLE ACCESS FULL | JOBS | 1 | 27 | 3 (0)| 00:00:01 |
|* 5 | INDEX RANGE SCAN | EMP_JOB_IX | 6 | | 0 (0)| |
|* 6 | TABLE ACCESS BY INDEX ROWID| EMPLOYEES | 6 | 408 | 1 (0)| 00:00:01 |
------------------------------------------------------------------------------------------------------------


Recompile the package body without the result cache hint and observe the plan and it would be

Plan hash value: 980169617

-------------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
-------------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | | | 4 (100)| |
| 1 | NESTED LOOPS | | | | | |
| 2 | NESTED LOOPS | | 6 | 570 | 4 (0)| 00:00:01 |
|* 3 | TABLE ACCESS FULL | JOBS | 1 | 27 | 3 (0)| 00:00:01 |
|* 4 | INDEX RANGE SCAN | EMP_JOB_IX | 6 | | 0 (0)| |
|* 5 | TABLE ACCESS BY INDEX ROWID| EMPLOYEES | 6 | 408 | 1 (0)| 00:00:01 |
-------------------------------------------------------------------------------------------


The benefit comes from the fact the sql query inside the SP could use the result cache. But the overhead of executing the PL/SQL code is still there which I believe won't be present in "proper" result cached SPs.

Any changes to depending tables will make the cache invalid just like the expected behavior.