<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Query Processor | Tag Archives: bug</title>
	<atom:link href="/tag/bug/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.queryprocessor.com</link>
	<description>Dmitry Pilugin&#039;s Notes</description>
	<lastBuildDate>Fri, 22 Jul 2016 20:53:05 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	
	<item>
		<title>Partitioned clustered index and FORCESCAN bug</title>
		<link>http://www.queryprocessor.com/partitioned-clustered-index-and-forcescan-bug/</link>
		<comments>http://www.queryprocessor.com/partitioned-clustered-index-and-forcescan-bug/#comments</comments>
		<pubDate>Mon, 16 Feb 2015 20:51:19 +0000</pubDate>
		<dc:creator><![CDATA[SomewhereSomehow]]></dc:creator>
				<category><![CDATA[bug]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[partitioning]]></category>

		<guid isPermaLink="false">http://www.queryprocessor.com/?p=349</guid>
		<description><![CDATA[I would like to share one curios case that I recently came across. Long story short: This bug may lead to incorrect results if you use a partitioned table and the FORCESCAN hint. Connect Item Bug Consider the following example, lets keep it simple. The following script creates partition function that has 4 ranges Range [...]]]></description>
				<content:encoded><![CDATA[<p>I would like to share one curios case that I recently came across.</p>
<p>Long story short:<br />
<em>This bug may lead to incorrect results if you use a partitioned table and the FORCESCAN hint.</em><br />
<a href="https://connect.microsoft.com/SQLServer/feedback/details/1134053/incorrect-results-with-forcescan-and-partitioned-table">Connect Item</a></p>
<p><span id="more-349"></span></p>
<h2>Bug</h2>
<p>Consider the following example, lets keep it simple.</p>
<p>The following script creates partition function that has 4 ranges</p>
<ul>
<li>Range 1 &#8211; (…,0]</li>
<li>Range 2 &#8211; (0,10]</li>
<li>Range 3 &#8211; (10,100]</li>
<li>Range 4 &#8211; (100,…)</li>
</ul>
<p>Then the partition scheme on that function and the table partitioned by the clustered primary key. The table contains 4 values: 1, 10, 50, 100</p>
<p>Now lets run the script, creating the following test data and the queries (I added (select 1) to avoid simple parameterization, to keep it simple):</p>
<pre class="brush: sql; gutter: false">use tempdb;
go
create partition function pf(int) as range for values (0, 10, 100)
create partition scheme ps as partition pf all to ([primary]);
go
if object_id(&#039;t&#039;) is not null drop table t;
create table t (a int primary key) on ps(a);
insert t(a) values (1),(10),(50),(100);
go
select a,b=(select 1) from t where a &lt; 100;
select a,b=(select 1) from t with(forcescan) where a &lt; 100;
go</pre>
<p>Results</p>
<p><img class="alignnone size-full wp-image-361" src="/wp-content/uploads/2015/02/001.png" alt="00" width="118" height="207" /></p>
<p>The first query returned results according to the specified predicate a &lt; 100, among 1, 10, 50, 100 those are 1, 10, 50.</p>
<p>The second one is missing value 50! That is not what we expected.</p>
<h2>Exploration</h2>
<p>Before we are going to deep dive into details, I’d like to advise to refresh some background if needed. Here is a remarkable resource of information about how does the optimizer treats partitioned tables starting from the 2008 version: <a href="http://blogs.msdn.com/b/craigfr/archive/2008/07/15/partitioned-tables-in-sql-server-2008.aspx">Partitioned Tables in SQL Server 2008</a><br />
Long story short with the quote:<br />
<em>“SQL Server 2005 treats partitioned tables specially and creates special plans, such as the above one, for partitioned tables. SQL Server 2008, on the other hand, for the most part treats partitioned tables as regular tables that just happen to be logically indexed on the partition id column. For example, for the purposes or query optimization and query execution, SQL Server 2008 treats the above table not as a heap but as an index on [PtnId]. If we create a partitioned index (clustered or non-clustered), SQL Server 2008 logically adds the partition id column as the first column of the index.”</em><br />
Let us examine the query plans from the very right Clustered Index Seek operator of the first plan, that produces correct results, the Seek Predicates property.</p>
<p><a href="/wp-content/uploads/2015/02/011.png"><img class="alignnone size-full wp-image-362" src="/wp-content/uploads/2015/02/011.png" alt="01" width="947" height="69" /></a></p>
<p>You may observe two seek keys (not two seek predicates), the second one is what we specified in the query, and the query optimizer adds the first one automatically. The purpose for that is a Partition Elimination technique.</p>
<p>This is an optimization trick to avoid accessing partitions, which the query would not touch to speed up execution. For example if we ask for “<em>a &lt; 100</em>”, and the table is partitioned by <em>a</em> – why would we access partitions that do not contain the data and we know it beforehand. The partition range is determined, to eliminate useless.</p>
<p>There are two types of partition elimination static (our case, because we know the value 100 in “<em>a &lt; 100</em>” predicate), and dynamic (if we use a parameter or а variable).</p>
<p><strong>Both static and dynamic are vulnerable to the bug. </strong></p>
<p>However, I’m not going to delve much into this, I’d rather provide some great links for more detailed description:<br />
<a href="http://blogs.msdn.com/b/craigfr/archive/tags/partitioned+tables/">Craig Freedman &#8211; Partitioning</a><br />
<a href="http://sqlblog.com/blogs/paul_white/archive/2012/09/12/why-doesn-t-partition-elimination-work.aspx">Why Doesn’t Partition Elimination Work?</a></p>
<p>Back to our query plan, with that knowledge we may see that a partition elimination was involved by adding a predicate: <em>Start: PtnId1000 &gt;= Scalar Operator((1)); End: PtnId1000 &lt;= Scalar Operator((3))</em> This means that the optimizer, considering the partition function specification, determined to scan Partitons 1 to 3. We may determine it by exploring the Actual Plan property Actual Partition Accessed:</p>
<p><a href="/wp-content/uploads/2015/02/021.png"><img class="alignnone size-full wp-image-364" src="/wp-content/uploads/2015/02/021.png" alt="02" width="236" height="176" /></a></p>
<p>Now let’s examine the second query plan.</p>
<p><a href="/wp-content/uploads/2015/02/031.png"><img class="alignnone size-full wp-image-365" src="/wp-content/uploads/2015/02/031.png" alt="03" width="890" height="124" /></a></p>
<p>What we see is (from up to bottom):</p>
<ul>
<li>Residual predicate (what we specified in the query predicate)</li>
<li>Static partition elimination, but, with a complex key, you see those delimiter “;” in the End property. We start seek from the partition 1 – <em>PtnId1000&gt;=Scalar Operator(1)</em>, and end up with: <em>PtnId1000; [tempdb].[dbo].[t].a &lt;= Scalar Operator((3)-(1)); Scalar Operator((100))</em>.</li>
<li>Notice the bright red square – the partitions we are going to end with are <strong>(3)-(1)</strong>!</li>
</ul>
<p>Indeed if we examine the plan property:<br />
<a href="/wp-content/uploads/2015/02/041.png"><img class="alignnone size-full wp-image-366" src="/wp-content/uploads/2015/02/041.png" alt="04" width="203" height="123" /></a></p>
<p>If we do a simple query to examine which partition each value belongs, we see that we obviously missed partition 3 for the value 50 that demands our predicate “a &lt; 100”:</p>
<pre class="brush: sql; gutter: false">select a, PtnId = $partition.pf(a) from t</pre>
<p><a href="/wp-content/uploads/2015/02/02-11.png"><img class="alignnone size-full wp-image-363" src="/wp-content/uploads/2015/02/02-11.png" alt="02 - 1" width="127" height="128" /></a></p>
<p>We should access 3 of them (partitions).</p>
<h2>Explanation</h2>
<p>The Devil is in the detail. First, we should recall some theory of the query optimization process. This one ends up with the tree of physical operators. You may read my very early blog series about the query optimization process: <a href="http://www.somewheresomehow.ru/optimizer-part-1-simplification/">optimizer-part-1-simplification/</a> but it is in Russian =) So I encourage you to read Paul White’s series <a href="http://sqlblog.com/blogs/paul_white/archive/2012/04/28/query-optimizer-deep-dive-part-1.aspx">query-optimizer-deep-dive-part-1</a></p>
<p>Long story short:<br />
<em>Before the query execution plan will be build the query optimizer builds a physical operator tree, a tree of the C++ objects, that reflects the query demands. Next the three is extracted and transformed to what we used to call a query plan. This process is known as post optimization rewrite.</em></p>
<p>One of those – is merging “filter and a scan operator” to “scan with residual”. Fortunately (for the optimizer curious people), there is one trace flag that disables this transformation, I’ve discovered it while doing some weird things =). It is quite helpful for debugging SQL Server plans, and it would be helpful here also – TF 9130.</p>
<p>When we enforce FORCESCAN hint we enforce the scan with residual predicate, but then it is rewritten during the post optimization rewrite phase to the Seek on partitioned index.</p>
<p>Now, what if we disable this “filter merging” thing and rewriting, and run the query with the magic TF</p>
<pre class="brush: sql; gutter: false">select a,b=(select 1) from t with(forcescan) where a &lt; 100;
select a,b=(select 1) from t with(forcescan) where a &lt; 100 option(querytraceon 9130);</pre>
<p>Plans:<br />
<a href="/wp-content/uploads/2015/02/051.png"><img class="alignnone size-full wp-image-367" src="/wp-content/uploads/2015/02/051.png" alt="05" width="706" height="253" /></a><br />
Results:<br />
<a href="/wp-content/uploads/2015/02/061.png"><img class="alignnone size-full wp-image-368" src="/wp-content/uploads/2015/02/061.png" alt="06" width="134" height="188" /></a></p>
<p>We observe that when the filter is not combined with the scan for the partition table. We have an extra Filter operator and expected results. When it <strong>is</strong> combined – we have a Seek and wrong results.</p>
<p>Now we obviously see that this issue is not about the optimization of the query, but rewriting it to the query plan.</p>
<p>The question is – what it is done during that rewrite?</p>
<p>The optimizer tries the last chance to push down a predicate closer to the scan and succeeds. It calculates partition range for elimination – and that is where the error sits. It is doing the wrong math. It tries to consider both predicates – residual and seek, and combine them to determine the right range for partition elimination.</p>
<p>Lets run the following and examine the query plan Seek Predicate property:</p>
<pre class="brush: sql; gutter: false">select a,b=(select 1) from t where a &lt; 100 and a &gt; 10;
select a,b=(select 1) from t with(forcescan) where a &lt; 100 and a &gt; 10;</pre>
<p>Results:</p>
<p><a href="/wp-content/uploads/2015/02/071.png"><img class="alignnone size-full wp-image-369" src="/wp-content/uploads/2015/02/071.png" alt="07" width="135" height="114" /></a></p>
<p>The second one has no rows at all!</p>
<p>Now the plans.</p>
<p>The first one has:</p>
<p><a href="/wp-content/uploads/2015/02/081.png"><img class="alignnone size-full wp-image-370" src="/wp-content/uploads/2015/02/081.png" alt="08" width="667" height="72" /></a></p>
<p>As you see, It has combined the start of the seek with “a &gt; 10” predicate and calculated that for this condition it should start with <em>Partition ID = 2 + 1</em>. 1 – the first one partition, 2 –partition for the value 10. Totally 1+2 = 3 which value 50 corresponds to. The end of the scan is calculated correctly also because there is no RESIDUAL predicate – and it is 3. So we scan only one partition with PtnID = 3. You may see it if you examine “Actual Partition Accessed” property.</p>
<p>The second one, does the same math for the start predicate, but unfortunately, add the residual one for the calculation and ends up with the following:</p>
<p><a href="/wp-content/uploads/2015/02/091.png"><img class="alignnone size-full wp-image-371" src="/wp-content/uploads/2015/02/091.png" alt="09" width="577" height="104" /></a></p>
<p>The condition for the partition elimination is</p>
<p>PtnID &lt;= 3-1 and PtnID &gt;=2+1, i.e &#8211; PtnID &lt;= 2 and PtnID &gt;=3 – obviously – no partitions and no rows for that.</p>
<p>Also, you may see that this plan has <strong>one</strong> Seek Key, but the first <strong>one</strong> has two Seek Keys. Combining into the one seek key and applying the same logic as there where two of them – leads to the wrong specification. It is not about the residual itself though, it is about how the predicates get combinated to calculate the partition range.  That is how I see it for now. I may be wrong in subtle details, because I do not have a source code, but I think I’m right in general.</p>
<p>For the Heap it is a table scan (having seek property though, but this is expected and unoficially documented in Craig Freedman&#8217;s blog, mentioned above) and the bug is not reproducable.</p>
<h2>Solution</h2>
<p>This is a bug and the only appropriate solution is to update the SQL Server. However I don’t know if it is a known bug or not, it is not removed by 4199 TF (generally, I think “Uncorrected results” bugs are fixed without any TF), so I’ve file a <a href="https://connect.microsoft.com/SQLServer/feedback/details/1134053/incorrect-results-with-forcescan-and-partitioned-table">Connect Item</a>, feel free to vote – more votes, more attention – quicker fix.</p>
<p>As an immediate fix, if you do suffer from an appropriate results – remove the hint FORCEPLAN, or add WITH(INDEX(0)) – that would remove the error, but may lead to inefficient plan.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.queryprocessor.com/partitioned-clustered-index-and-forcescan-bug/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

 Served from: www.queryprocessor.com @ 2016-08-02 20:44:04 by W3 Total Cache -->