<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kaisen Kang on Medium]]></title>
        <description><![CDATA[Stories by Kaisen Kang on Medium]]></description>
        <link>https://medium.com/@kangkaisen?source=rss-8553df50b43f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-llXBvAGHMOSKyJYjB-C6A.jpeg</url>
            <title>Stories by Kaisen Kang on Medium</title>
            <link>https://medium.com/@kangkaisen?source=rss-8553df50b43f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 03:45:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kangkaisen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[MPP Pipeline VS Grouped Execution VS Stage By Stage]]></title>
            <link>https://medium.com/starrocks-engineering/mpp-pipeline-vs-grouped-execution-vs-stage-by-stage-f4616052474a?source=rss-8553df50b43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4616052474a</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[tech-deep-dive]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[pipeline]]></category>
            <dc:creator><![CDATA[Kaisen Kang]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 22:45:41 GMT</pubDate>
            <atom:updated>2023-07-11T16:37:00.293Z</atom:updated>
            <content:encoded><![CDATA[<p>Presto recently published a new paper, <a href="https://research.facebook.com/publications/presto-a-decade-of-sql-analytics-at-meta/">Presto: A Decade of SQL Analytics at Meta</a> . It just so happens that Presto supports three distributed execution modes: <strong>MPP Pipeline, Grouped Execution, and Stage By Stage</strong>. I want to compare these three execution modes.</p><h3>What Is In MPP Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pOl4vgnMBAApu8Tg0fEfNg.jpeg" /><figcaption>Mpp pipeline VS Map Reduce</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*T-2ysrvrXP8naOY6.jpg" /></figure><p>As shown in the figure, this article specifically refers to the MPP query engine represented by StarRocks and Presto, which has the following characteristics:</p><ul><li>The entire distributed execution is all In Memory</li><li>The entire distributed execution is Pipeline, and each Fragment will stream the transmission data to the next Fragment. It is not necessary for a Fragment to process all the data and then transmit it to the next Fragment.</li><li>Support Shuffle, Shuffle is In Memory and Streaming</li></ul><h4>What Is Grouped Execution</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K4aB_y4bIgzTq7-O.png" /><figcaption>Colocate join</figcaption></figure><p>Grouped Execution is actually easy to understand. You can understand it from the Colocate join. As shown in the above figure, the data of the two tables T1 and T2 have been bucketed according to the Id column when imported, so the data with the same Id is on one node. Join There is no need to re-shuffle, but there is another important point: <strong>after the execution of each bucketed Join, the final result of the Join can be returned directly</strong>, so when we run out of memory, we don’t need all nodes or buckets The above Join starts at the same time. <strong>We can execute the Join operation one by one bucket by bucket</strong>, so that the memory resources we need will be reduced by dozens of times. At the same time, <strong>retry and fault tolerance can be carried out according to the granularity of buckets.</strong> This is Grouped Execution core principles.</p><p>What if the data of the two tables is not bucketed according to the Join Column in advance? The answer is simple, as shown in the figure below, it is the same as processing Shuffle Join when we query, <strong>just add an additional Shuffle, and persist the result of Shuffle, and then the process is the same as the Colocate processing process described above.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1fGa6OqYixx7DJ2W.png" /></figure><h4>What Is Stage By Stage</h4><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*pOl4vgnMBAApu8Tg0fEfNg.jpeg" /><figcaption>Mpp pipeline VS Map Reduce</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/0*Ve-ODqbhE8IUzOJ2.jpg" /></figure><p>As shown in the figure, this article specifically refers to batch processing engines represented by MapReduce and Spark, which have the following characteristics:</p><ul><li>The entire distributed execution is Stage By Stage, and each Stage will be placed on the disk</li><li>Shuffle needs to persist the result to disk</li></ul><h4>MPP Pipeline VS Stage By Stage</h4><p><strong>1 End-to-end latency:</strong></p><p>The MPP query engine represented by StarRocks and Presto has lower end-to-end latency, because each Fragment will immediately send the data to the downstream, and the time for the user to receive the first piece of data is shorter.</p><p><strong>2 Fault tolerance or batch processing capability:</strong></p><p>The execution mode of Stage By Stage represented by Spark has better fault tolerance, because at the end of each Stage execution is a materialization point or Checkpoint point, it can be recovered from the previous Stage after failure, but once the MPP Pipeline execution mode fails, it will The entire query needs to be re-executed, so it is not suitable for executing SQL that takes a long time to execute in the ETL class.</p><p><strong>3 Memory usage:</strong></p><p>MPP Pipeline may require more memory for complex queries, because the Stage By Stage mode can release the memory immediately after each Stage is executed, but the MPP Pipeline mode may need to keep multiple Hash tables in multiple Fragments (Hash Join and Hash Aggregate), these Hash tables can be released together only after the execution of the entire query is completed.</p><p><strong>4 Scheduling methods:</strong></p><p>StarRocks and Presto are All At Once scheduling, and all Fragments of the entire query need to be ready, but Spark is Stage By Stage, and tasks are started batch by stage. (Note: Presto also supports phased scheduling, which optimizes this)</p><p><strong>5 Scalability:</strong></p><p>StarRocks and Presto In Memory Shuffle may be limited by resources such as memory and number of connections when there are hundreds or thousands of nodes</p><p><strong>6 Adaptive execution:</strong></p><p>The execution method of Spark Stage By Stage is easier to collect statistical information after each Stage, re-plan the Plan, and the MPP pipeline mode is more difficult to adapt</p><p><strong>7 Slow node problem:</strong></p><p>Relying on speculative execution and fault tolerance, Spark’s Stage By Stage execution method can handle slow node problems relatively better.</p><h4>Grouped Execution VS Stage By Stage</h4><p>Because both Grouped Execution and Stage By Stage want to solve the problem of ETL execution, our comparison mainly focuses on ETL-related points.</p><p><strong>1 Fault tolerance granularity:</strong></p><p>The granularity of Grouped Execution fault tolerance is relatively coarse, and Shuffle must be used as the fault tolerance point, while Spark can use any Mapper and Reducer as the fault tolerance point, and the granularity of query retry is finer, and Mapper and Reducer can be independently scheduled and retried</p><p>Grouped Execution cannot tolerate node-granularity Crash, but Spark can</p><p><strong>2 Isolation levels:</strong></p><p>The isolation granularity of Grouped Execution is at the node level, while Spark is at the Container level, with finer granularity</p><p><strong>3 Scalability and stability:</strong></p><p>Grouped Execution is still In Memory’s Shuffle, and its stability is not as good as Spark’s Shuffle Service.</p><p>Due to the above defects of Grouped Execution, Presto initiated the Presto on Spark project and gradually replaced Grouped Execution, which also declared the failure of the Grouped Execution project.</p><h4>References</h4><p>1. Presto 2018 Paper: <a href="https://trino.io/Presto_SQL_on_Everything.pdf">Presto: SQL on Everything</a></p><p>2. Presto 2023 paper: <a href="https://research.facebook.com/publications/presto-a-decade-of-sql-analytics-at-meta/">Presto: A Decade of SQL Analytics at Meta</a></p><p>3. <a href="https://prestodb.io/blog/2019/08/05/presto-unlimited-mpp-database-at-scale">Presto Unlimited: MPP SQL Engine at Scale</a></p><p>4. <a href="https://prestodb.io/blog/2021/10/26/Scaling-with-Presto-on-Spark">Scaling with Presto on Spark</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4616052474a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/starrocks-engineering/mpp-pipeline-vs-grouped-execution-vs-stage-by-stage-f4616052474a">MPP Pipeline VS Grouped Execution VS Stage By Stage</a> was originally published in <a href="https://medium.com/starrocks-engineering">StarRocks Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The only database mentioned by the CEO of Databricks: StarRocks]]></title>
            <link>https://medium.com/@kangkaisen/the-only-database-mentioned-by-the-ceo-of-databricks-starrocks-5e34bfeea05c?source=rss-8553df50b43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e34bfeea05c</guid>
            <category><![CDATA[data-lakehouse]]></category>
            <category><![CDATA[data-lake]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[starrocks]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Kaisen Kang]]></dc:creator>
            <pubDate>Fri, 30 Jun 2023 23:53:29 GMT</pubDate>
            <atom:updated>2023-07-01T00:11:49.848Z</atom:updated>
            <content:encoded><![CDATA[<h3>Databricks CEO Only Mentioned StarRocks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rqIwflYUXecYC9LR.jpg" /></figure><p>At the recently concluded Databricks Data + AI Summit, StarRocks was the only database mentioned by the Databricks CEO during his speech. Why?</p><p>Can you guess…?</p><p>It is a growing trend to have a unified metadata layer for data lakes. Both Delta Lake 3.0 and Onetable are aiming to achieve the same goal of unifying the metadata layer for data lakes. For more information on Onetable, you can refer to <a href="https://www.onehouse.ai/blog/onetable-hudi-delta-iceberg">onetable-hudi-delta-iceberg</a>.</p><p>The Databricks CEO claimed that StarRocks can only query Hudi and cannot query Delta Lake and IceBerg. In fact, StarRocks can query Hudi, Delta Lake, and IceBerg simultaneously. Not only can StarRocks perform these queries, but it can also <strong>provide the ultimate data lake analysis experience and is absolutely open, without any locking mechanisms.</strong></p><p>Regardless of whether the metadata of various table formats on the data lake is unified, you can use StarRocks as your query engine on the data lake. Why? Because StarRocks is extremely powerful!</p><h3>StarRocks Powerful DateLake Analysis</h3><h4>StarRocks Extreme Query Performance</h4><p>There have been a lot of information about the extreme performance of StarRocks, so I won’t go into details here</p><ol><li>MPP distributed execution</li><li>Pipeline parallel execution framework</li><li>Vectorized execution</li><li>CBO optimizer</li><li>Global Runtime Filter</li><li>Metadata Cache</li><li>Local Data Cache</li><li>Materialized View</li></ol><h4>Take advantage of StarRocks’ House ability to further improve performance</h4><p>StarRocks is not only a query engine, but also has a powerful storage engine. If you want to further improve query performance or query concurrency, you can import data into StarRocks. StarRocks’ local storage will have rich indexing capabilities, real-time Update ability, multi-table Colocate ability.</p><p>There are two ways to import data into StarRocks: manually import data and MV automatically import data.</p><p>StarRocks supports the creation of materialized views on tables on the data lake, and supports automatic data synchronization and automatic query rewriting</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i8zQAuazH7hqkMaN.png" /></figure><h4>Hot and cold separation + Automatic query rewriting</h4><p>In most cases, we want the hot data of the last week or month to have better query performance. In StarRocks, MV can help you achieve this very conveniently and efficiently:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sQDq0ccFYpe0hufi.png" /></figure><p>As shown in the figure above, the StarRocks MV can only save the data of the last month. When you query the data on DataLake, StarRocks will automatically rewrite it for you. The latest data is queried from StarRocks, and the historical data is queried from DataLake, and then automatically Union.</p><h4>StarRocks is a LakeHouse that supports real-time updates</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BxUceRMwC-UgmQoL.png" /></figure><p>Because StarRocks supports both real-time efficient updates and writing to Iceberg, we can build a real-time updated LakeHouse based on StarRocks. <strong>When you need real-time updates, extreme query performance, and open Table Format, StarRocks is your only choice.</strong></p><h4>StarRocks’ easy-to-use Catalog metadata management</h4><p>StarRocks can synchronize all table metadata under the external DB with one click, and quickly synchronize various DateLake data sources</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*vfSygNIdW9Lhduha.jpg" /></figure><h4>StarRocks Elastic Scaling</h4><p>The computing nodes used by StarRocks for data lake analysis are stateless and can be combined with K8S for rapid elastic scaling</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*39GT7D8UEXf1EyZY.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e34bfeea05c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[StarRocks millisecond-level point queries on hundreds of billions of data]]></title>
            <link>https://medium.com/@kangkaisen/beat-singlestore-starrocks-millisecond-level-point-queries-on-hundreds-of-billions-of-data-b3ccd25abd35?source=rss-8553df50b43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3ccd25abd35</guid>
            <category><![CDATA[index]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[bitmap]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[singlestore]]></category>
            <dc:creator><![CDATA[Kaisen Kang]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 00:08:21 GMT</pubDate>
            <atom:updated>2023-06-26T16:48:23.126Z</atom:updated>
            <content:encoded><![CDATA[<p>Supporting point queries with arbitrary field filtering is a common requirement for TP databases, and a common solution is the use of secondary indexes. In recent user scenario tests, we found that StarRocks, in a cluster consisting of 3 servers with 8-core CPUs, 32GB of memory, and 4TB AWS EBS disks, <strong>can provide sub-millisecond performance for hot queries on hundreds of billions of data and around 1-second performance for cold queries.</strong></p><p>This article briefly analyzes how StarRocks achieves millisecond-level query of tens of billions of data. The main method of StarRocks to accelerate the query of prefix columns is the prefix index, and the main method of accelerating the query of the following non-primary key columns is Bitmap index:</p><pre>select * from table where A = 1<br>select * from table where A = 1 and B = 2<br>select * from table where A = 1 or  B = 2</pre><h3>1 How does StarRocks Bitmap index speed up point queries</h3><h4>1.1 StarRocks supports indexed Bitmap indexes</h4><p><strong>StarRocks Segment File</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HKGBMWthEkOqbt2VbhvVA.png" /></figure><p>The segment file of StarRocks is divided into three parts: data, index, and metadata. Data and index are organized according to Page, and the default size of a Page is 1M.</p><p><strong>StarRocks Bitmap Index Rationale</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pu1uFoABz5HscpW2kqidgg.png" /></figure><p>The Bitmap Index of StarRocks mainly includes two parts: the dictionary and the Bitmap index itself. The dictionary saves the mapping from the original value to the encoding Id, and the Bitmap index records the mapping from each encoding ID to the Bitmap.</p><p><strong>StarRocks Bitmap Index Storage Format</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xpHk_xDk3Ooduh6OWPzPUg.png" /></figure><p>As shown in the figure above, both the dictionary part and the Bitmap index part of StarRocks are stored in the format of Page. In order to reduce memory usage and speed up indexing, <strong>StarRocks indexes both the dictionary and Bitmap Page.</strong></p><p>Of course, if the cardinality of the Bitmap index column is very low and there is only one Dict Data Page and Bitmap Data Page, we don’t need Dict Index Page and Bitmap Index Page.</p><h4>1.2 Operation On Encode Data</h4><p>When StarRocks uses Bitmap Index for filtering, it only needs to load the Dict Index Page and some Dict Data Pages first, and quickly filter according to the dictionary values, <strong>without decoding data, and without loading all Bitmap Data Pages at once.</strong></p><p>To sum up, since StarRocks supports Bitmap index indexing and supports quick filtering according to dictionary values, even if the cardinality of the Bitmap Index column is high, the overall disk storage of the Bitmap Index is large,<strong> the memory usage is still small</strong>.</p><h4>1.3 Or predicate supports Bitmap index</h4><p>Due to historical reasons, the predicate pushdown of the StarRocks storage layer only supports the CNF conjunctive paradigm, which requires the predicate to be connected by And. For example for the following SQL:</p><pre>select * from table where A = 1 and B = 2</pre><p>StarRocks will push down the predicates A = 1 and B = 2 respectively, and the final result is the filtered intersection of the two predicates. A = 1 and B = 2 can use various indexes on column A and column B respectively.</p><p>But for the following Or predicate:</p><pre>select * from table where A = 1 or B = 2</pre><p>The old version of the StarRocks storage layer cannot push down the OR predicate, so it needs to scan the entire table and then use the A = 1 or B =2 predicate to filter data. In order for the Or predicate to use the Bitmap index, the most ideal way is that the storage layer supports the Or predicate. A = 1 and B = 2 respectively apply the Bitmap index, and then the row numbers can be union, but the code modification is a little complicated, so it is implemented two steps, the first step is to rewrite SQL on the FE side so that the OR predicate can use the Bitmap index, and then the second step will directly support the OR predicate in the storage layer.</p><p>The SQL rewrite is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3VcSD9ZaPWeffKxJETNpA.png" /><figcaption>scan or to union</figcaption></figure><h4>1.4 Bitmap index memory cache</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ZabnoCJwarZ1GhYCwkBeg.png" /></figure><p>StarRocks will <strong>ensure that all Dict Index Pages and Bitmap Index Pages must be in memory</strong>, and keep as many Dict Data Pages and Bitmap Data Pages in memory as possible, and ensure that the Page Cache related to Bitmap Index is not flushed by Column data.</p><p>In this way, in the case of a small query result set, even if it is the first Cold Query, <strong>StarRocks can achieve only one Disk Seek.</strong></p><h4>1.5 Adaptive Bitmap Indexing</h4><p>When StarRocks found that the selectivity of the Bitmap index was not high and needed to seek a lot of data pages, we would give up using the Bitmap index and directly scan in order.</p><h3>2 StarRocks prefix index speeds up point queries</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xuLP2JHr1VPswM2lhigLtA.png" /></figure><p>As shown in the figure above, if the cardinality of a table’s filter condition is very high, in StarRocks, there is no need to use the Bitmap index, set the column as the Sort Key, and use the prefix index to filter. For high-cardinality columns, <strong>the prefix index has better point lookup performance and can save a lot of storage space.</strong></p><h3>3 StarRocks RollUp || Materialized View speeds up point queries</h3><p>When the filtering degree of the Bitmap index is not large and many data pages need to be Seek, you can consider further exchanging space for time, using RollUp and Materialized View of StarRocks to set different filter columns as Sort Key, and using the prefix index to speed up point queries.</p><h3>4 StarRocks Generated Column speeds up point queries</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9nqILxXjl14kpPGklk6NA.png" /></figure><p>As shown in the figure above, when the filtered column is a Key column of type Json or Map, in StarRocks, we can add a Generated Column for the Key column, and then create a Bitmap index for the Key column to speed up the point queries through the Bitmap index.</p><p>Of course, when StarRocks supports the direct build the Bitmap indexes for Json or Map type Key columns, there is no need to rely on Generated Column.</p><h3>5 StarRocks Two-Level Partition &amp; Bucket</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57w-TlUhvfrt2AqK6oW_uA.png" /></figure><p>StarRocks supports two-level partitioning and bucketing. You can first partition according to columns with time attributes, and then partition according to high-cardinality columns. <strong>This ensures good data locality and avoids data skew</strong>.</p><ul><li>The better the data locality, the better the data compression ratio in the columnar storage, and the lower the IO cost of the query.</li><li>Without data skew, StarRocks can give full play to the capabilities of multi-machine and multi-core.</li></ul><h4>5.1 StarRocks Partition Pruning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7NxGw03IipP1nmiEd-FeA.png" /></figure><p>As shown in the figure, if the filter condition of the query contains partition columns, StarRocks can trigger <strong>partition pruning</strong>, and the amount of Scan data will be greatly reduced.</p><h4>5.2 StarRocks Bucket Pruning</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DQkZG1usDpfoZvvmn2PXZw.png" /></figure><p>As shown in the figure, if the filter condition of the query contains bucket columns, StarRocks can trigger <strong>bucket pruning</strong>, and the amount of Scan data will be greatly reduced.</p><h3>6 Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TtkgJqcoJr6c-9va.png" /><figcaption>SSB Benchmark</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HvRWyZJ9lVsoxDv7.png" /><figcaption>TPC-H Benchmark</figcaption></figure><p><strong>When you need high-performance point query, high-performance OLAP query, high-performance AdHoc query and high-performance data lake analysis at the same time, StarRocks is your best choice.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3ccd25abd35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build an extremely fast analytical database -Part4]]></title>
            <link>https://medium.com/starrocks-engineering/how-to-build-an-extremely-fast-analytical-database-part4-306d610cc01a?source=rss-8553df50b43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/306d610cc01a</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[tuning]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Kaisen Kang]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 22:30:28 GMT</pubDate>
            <atom:updated>2023-06-29T21:31:23.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dUtzxYiZuXFDLpSk.png" /></figure><p>In the realm of databases, there are primarily two categories: transactional databases that focus on handling transactions and analytical databases that prioritize analysis. For an analytical database, performance is of utmost importance. In this article, I will share insights on how to create an exceptionally fast analytical database based on CPU technology. (Note: this article does not discuss heterogeneous computing such as GPU or FPGA, nor does it delve into new hardware accelerators like RDMA or NVM.)</p><p>This article will explore nine perspectives: precomputation vs. on-the-fly computation, scalability, data streaming, resource utilization, optimization, resilience, architecture vs. details, approximation vs. precision, and performance testing. Through these angles, we will delve into the process of building a lightning-fast analytical database.</p><ul><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part1-b409836f5a7f">How to build an extremely fast analytical database -Part1</a></li><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part2-a74d45d6188d">How to build an extremely fast analytical database -Part2</a></li><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part3-78c5a06b88ed">How to build an extremely fast analytical database -Part3</a></li></ul><h3>Part4：Resource Utilization</h3><p><strong>The essence of performance optimization is to optimize the utilization of various system resources</strong>. When we review the various methods for query optimization discussed in Part Three, they are essentially focused on optimizing the usage of CPU, memory, I/O, and network resources:</p><ul><li>“Read Data Less And Fast” at the storage layer is essentially optimizing I/O resources.</li><li>“Transfer Data Less And Fast” at the computing layer is essentially optimizing network resources.</li><li>“Process Data Less And Fast” at the computing layer is essentially optimizing CPU and memory resources.</li></ul><p>If two implementations of solving a problem have the same algorithmic complexity, <strong>the one that is considered more optimal is the one that minimizes unnecessary work and utilizes fewer system resources.</strong></p><h3>Part5：Manual Tuning vs. Adaptive Tuning vs. AI Tuning</h3><p>Due to the diverse hardware conditions, modeling approaches, usage scenarios, and query patterns of users, as well as the varying characteristics of user data, <strong>optimizing a database can have different outcomes in different scenarios.</strong> What may be beneficial for scenario A could be detrimental for scenario B. Therefore, database developers often introduce various configurations and variables to provide tuning flexibility to DBAs or users. The same query can exhibit several times or even dozens of times difference in performance under different configurations.</p><p>However, manual tuning not only incurs high labor costs but also poses significant challenges. It requires the tuner to have a profound understanding of both the database principles and the business scenarios to identify the possible optimal configurations. To address this challenge, databases adopt two main strategies. <strong>One approach is for the database kernel to adapt autonomously by minimizing the exposure of configurations or variables to users</strong>. Adaptive algorithms or strategies can automatically select the most suitable algorithms or strategies for different contexts. <strong>Another approach is to introduce machine learning</strong>, leveraging large amounts of historical data to automatically determine the most appropriate configurations or variables. For instance, aspects such as indexes, execution algorithms, scheduling policies, cardinality estimation in optimizers, cost models, partitioning strategies, and sorting key selection can theoretically be automatically optimized and continuously improved based on historical data. Professor Andy Pavlo from CMU has even founded a startup called OtterTune specifically to address this challenge.</p><p><strong>Both internal adaptive strategies and external machine learning-based tuning can be employed simultaneously</strong>. In essence, they both aim to gather more information based on users’ real data and queries to narrow down the context and achieve more accurate and targeted optimization. StarRocks has made various attempts in adaptive strategies and will consider leveraging machine learning for tuning in the future.</p><h3>Part6：Extreme Elasticity in Serverless</h3><p>The various optimization approaches mentioned earlier have a common assumption: <strong>that physical resources remain relatively fixed over a short period</strong>. However, with the gradual popularity and development of Serverless databases, we can now rapidly scale up and scale out computing resources in a short time, increasing them several times or even dozens of times. In a scenario where the query cost remains constant, <strong>we can accelerate queries by quickly provisioning additional resources.</strong> This is because Cost(10 computing nodes, each taking 100 seconds) = Cost(100 computing nodes, each taking 10 seconds).</p><p>To achieve this, a database needs to have certain characteristics. These include being cloud-native, separating storage and compute, providing sub-second elasticity, possessing robust multi-core and multi-node scalability, offering resource isolation capabilities, enabling workload prediction, and automatically resolving data skew.</p><p>In my opinion, <strong>optimizing extreme elasticity will be crucial in the future.</strong> The ability to rapidly scale resources up or out to meet demand can significantly enhance query performance and overall system efficiency.</p><h3>Part7：Architecture vs. Details</h3><p>If we truly want to build an ultra-high-performance system or database, it is crucial to <strong>have both a well-designed architecture and impeccable engineering implementation</strong>. Exceptional performance comes from a combination of excellent architecture and meticulous engineering details. As mentioned earlier in the article, the importance lies not only in the vectorized execution architecture but also in the engineering details. The MPP (Massively Parallel Processing) distributed computing mechanism primarily focuses on the architectural aspect, while the CBO (Cost-Based Optimizer) and the Pipeline single-node parallel execution framework require both a reasonable architecture and meticulous engineering details.</p><p>Some may argue that this is an obvious answer, but it is not always apparent to everyone. If you agree with this viewpoint, then when building an OLAP database, you would not choose languages like Java to implement the query execution layer and storage layer. You would also not design the entire system from the bottom-up, focusing on details and algorithms like ClickHouse does.</p><h3>Part8：Approximate vs. Exact</h3><p>As an analytical database, there is another commonly used acceleration technique known as approximate computation. Approximate computation can satisfy user requirements based on two main points:</p><ol><li><strong>Exploratory Analysis</strong>: When analysts are conducting exploratory analysis, they may only need a general understanding of data scale, characteristics, and trends. They do not necessarily require precise data.</li><li><strong>Large Data Volume</strong>: When dealing with large datasets, the cost of performing exact computations can be prohibitively high. For example, calculating exact distinct counts or percentiles can be computationally expensive.</li></ol><p>In OLAP databases, there are generally two implementation approaches for approximate computation:</p><ol><li><strong>Using Approximate Data Structures</strong>: This approach involves leveraging approximate data structures to perform calculations. For example, HyperLogLog can be used to estimate approximate distinct counts, and TDigest can be used to estimate approximate percentiles. (Link: <a href="https://blog.bcmeng.com/post/tdigest.html">https://blog.bcmeng.com/post/tdigest.html</a>)</li><li><strong>Sampling-based Statistical Estimation</strong>: In this approach, a subset of the original data is sampled and used to estimate metrics for the entire dataset. For example, if the original dataset has 100 million rows, a sample of 1 million rows can be used to estimate metrics such as maximum values or cardinality for the entire 100 million rows. One drawback of this approach is that different data distributions have different statistical characteristics, leading to potential estimation errors.</li></ol><h3>Part9：Performance testing</h3><p>For a large-scale open-source database, given the collaborative nature of development and the varying knowledge backgrounds of each developer, it is inevitable that code leading to performance regressions may occur. Therefore, to maintain a continuous performance advantage, it is essential to conduct thorough performance testing to prevent performance regressions. StarRocks has encountered numerous cases of performance regressions during its development process. Database performance testing can be divided into two major categories:</p><ol><li><strong>Self-performance regression testing or benchmark testing</strong>:</li></ol><ul><li>On one hand, this type of testing helps prevent performance degradation between versions, ensuring that each new version maintains or improves performance.</li><li>On the other hand, it can help identify new optimization opportunities by analyzing the causes of each performance regression that occurs</li></ul><p>2. <strong>Competitor performance comparison testing</strong>:</p><ul><li>This type of testing aims to assess the performance of the database in comparison to its competitors.</li><li>By comparing the performance with competitor databases, it is possible to identify areas where the database excels and achieves world-leading performance in certain query types.</li><li>Additionally, it can highlight query types that require further improvement and uncover potential performance optimization opportunities.</li></ul><ul><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part1-b409836f5a7f">How to build an extremely fast analytical database -Part1</a></li><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part2-a74d45d6188d">How to build an extremely fast analytical database -Part2</a></li><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part3-78c5a06b88ed">How to build an extremely fast analytical database -Part3</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=306d610cc01a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/starrocks-engineering/how-to-build-an-extremely-fast-analytical-database-part4-306d610cc01a">How to build an extremely fast analytical database -Part4</a> was originally published in <a href="https://medium.com/starrocks-engineering">StarRocks Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data-Parallel Actors: Building High-Performance OLAP Databases with a Few Thousand Lines of Code]]></title>
            <link>https://medium.com/@kangkaisen/data-parallel-actors-building-high-performance-olap-databases-with-a-few-thousand-lines-of-code-bdbdd418183?source=rss-8553df50b43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdbdd418183</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[druid]]></category>
            <category><![CDATA[solr]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[actors]]></category>
            <dc:creator><![CDATA[Kaisen Kang]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 22:27:40 GMT</pubDate>
            <atom:updated>2023-06-15T22:27:40.424Z</atom:updated>
            <content:encoded><![CDATA[<h3>1 What is Data-Parallel Actors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Dl1kyZmfmmFUGJWe.png" /></figure><p>As depicted in the above diagram, <strong>Data-Parallel Actors (DPA) is a high-level programming model that provides unified and abstracted functionality for distributed query processing.</strong> It encompasses features such as data replication, consistent updates, fault tolerance, query load balancing, elasticity, and persistence.</p><p>With DPA, developers only need to implement single-node data structures and operators, and they can obtain a reliable and high-performance distributed analytical database. By using DPA, developers can<strong> focus on their unique and core logic</strong> while leveraging the benefits of distributed query processing.</p><p>The research paper demonstrates the generality and practical effectiveness of DPA through three systems: Druid, Solr, and MongoDB. Each of these systems was implemented using DPA within a codebase of no more than a few thousand lines. Furthermore, these systems performed on par with their predecessors in standard benchmark tests, and<strong> even achieved three times the performance improvement in scenarios with data skew.</strong></p><p>Developers need to utilize a query optimizer to convert user requests into parallel operators within the DPA framework. This ensures efficient and optimized query processing within the distributed environment provided by DPA.</p><h3>2 Why need Data-Parallel Actors</h3><ol><li>Each system of distributed functions is similar, and requires a lot of manpower, and it should not and does not need to be implemented repeatedly.</li><li>Current distributed systems (Erlang, Ray, Spark, etc.) cannot meet the needs of analytical databases: data parallel low-latency queries and high-frequency batch data updates.</li></ol><h3>3 How Data-Parallel Actors</h3><h4>3.1 Actors and Data Model Mapping</h4><p>DPA regards a database as a collection of stateful actors. Each actor encapsulates a part of data and is responsible for the state and compute of this part of data.</p><ul><li>In Solr, an Actor encapsulates Solr’s inverted index</li><li>In Druid, an Actor encapsulates a Druid segment, and a group of Actors form a Druid data source</li><li>In MongoDB, a set of Actors encapsulates MongoDB collections</li></ul><h4>3.2 The interface of DPA</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XveFiZQWNZjZMgB8.png" /></figure><p>As shown in the figure above, the interfaces provided by DPA are mainly divided into 4 categories:</p><ol><li>Actor state management related interfaces, DPA relies on these interfaces to manage actors</li><li>Update related interfaces, DPA relies on these interfaces to update Actor data, DPA supports different levels of consistency</li><li>Operator parallelization interface, DPA relies on these interfaces to implement Actor’s parallel query</li><li>Specific Operators, DPA relies on these interfaces to implement the specific query logic of Actors. Operators of different databases can basically be realized through these abstract operators. Each Operator should not modify the state of the Actor, but materialize the input for the next Operator to read. Among them, the Scatter and Gather operator can realize data transmission between actors, and simulate broadcast and shuffle in a distributed database</li></ol><h4>3.3 Overall structure</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vKyYfC_AqfB3SuPr.png" /></figure><p>As shown, Uniserve is a concrete implementation of DPA. There are 3 roles:</p><ol><li><strong>Uniserve Client:</strong> Responsible for sending query and update requests. In the query part, it will assume the responsibility of query optimizer and convert user requests into DPA operators.</li><li><strong>Uniserve Server</strong>: Responsible for serving the query and update requests of each Actor.</li><li><strong>Uniserve Coordinator</strong>: Responsible for implementing the distributed logic of DPA: data replication, update consistency, fault tolerance, query load balancing, elasticity, persistence, etc.</li><li>DPA will store data on distributed storage such as S3.</li></ol><h3>4 Advantages compared to Druid, MongoDB, ClickHouse and other databases</h3><p>Mainly two points:</p><p><strong>1 Query requests based on machine load balance：</strong></p><p>The default strategy is relatively simple: it is to migrate the highest loaded actor from the highest loaded server to the lowest loaded server.</p><p>The advantage is that the scheduling strategy is extensible, allowing developers to customize their own strategies</p><p><strong>2 Elasticity and Auto-Scaling：</strong></p><p>It has the ability of elastic scaling, and the strategy is also scalable. For the elastic scaling strategy, we should refer to the utilization rate of resources such as the CPU, memory, network, and disk of the cluster on the one hand, and also refer to the query request load of the cluster.</p><p>I understand that it is mainly because of these two points that DPA can achieve a 3-fold performance improvement in data skew scenarios.</p><h3>5 Limit</h3><p>1. DPA’s query model is most suitable for data-parallel queries</p><p>2. DPA is not suitable for high-frequency enumeration with transaction requirements in TP scenarios</p><h3>6 Challenge</h3><p><strong>1 How to support multiple queries and data models:</strong></p><ul><li>Relational</li><li>Search</li><li>Timing</li><li>Document</li><li>Vector database</li></ul><p>2 How to <strong>correctly abstract distributed core functions</strong> such as query scheduling, replica balancing, and elastic scaling, allowing different databases and different business requirements to be realized under defined interfaces.</p><h3>7 Thinking</h3><ol><li>A system similar to DPA will inevitably appear in the open source world<br><strong>For any repetitive and valuable functions and modules, in the open source world, there will definitely be a dedicated system for them</strong></li><li><strong>Open source databases will become more and more modular</strong><br>There are more and more open source database modules: DPA, Apache Calcite, Apache Arrow, Velox, gRPC, etc., and more and more are adopted by the industry</li><li><strong>Building a high-performance database prototype will become easier and easier：</strong>Because open source data will become more and more modular, it will become easier for us to build a high-performance database prototype from scratch. I will explain this in detail in the next document</li></ol><h3>8 References</h3><p><a href="https://cs.stanford.edu/~matei/papers/2022/nsdi_uniserve.pdf">https://cs.stanford.edu/~matei/papers/2022/nsdi_uniserve.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdbdd418183" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build an extremely fast analytical database -Part3]]></title>
            <link>https://medium.com/starrocks-engineering/how-to-build-an-extremely-fast-analytical-database-part3-78c5a06b88ed?source=rss-8553df50b43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/78c5a06b88ed</guid>
            <category><![CDATA[tech-deep-dive]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Kaisen Kang]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 18:58:06 GMT</pubDate>
            <atom:updated>2023-06-16T21:07:57.541Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of databases, there are primarily two categories: transactional databases that focus on handling transactions and analytical databases that prioritize analysis. For an analytical database, performance is of utmost importance. In this article, I will share insights on how to create an exceptionally fast analytical database based on CPU technology. (Note: this article does not discuss heterogeneous computing such as GPU or FPGA, nor does it delve into new hardware accelerators like RDMA or NVM.)</p><p>This series of articles will explore nine perspectives: precomputation vs. on-the-fly computation, scalability, data streaming, resource utilization, optimization, resilience, architecture vs. details, approximation vs. precision, and performance testing. Through these angles, we will delve into the process of building a lightning-fast analytical database.</p><ul><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part1-b409836f5a7f">How to build an extremely fast analytical database -Part1</a></li><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part2-a74d45d6188d">How to build an extremely fast analytical database -Part2</a></li><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part4-306d610cc01a">How to build an extremely fast analytical database -Part4</a></li></ul><h3>Part3：<strong>Query data stream processing</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LeDgsDkEHLzJ6QH9.png" /></figure><p>Taking a closer look from the perspective of query data stream processing, let’s discuss how to build an ultra-fast database. As shown in the diagram, when a database receives an SQL query, it goes through four major modules for processing: query optimizer, query scheduler, query executor, and storage layer. Each module addresses a specific aspect:</p><ol><li><strong>Query Optimizer</strong>: This module converts the SQL text into an optimized distributed physical execution plan. It aims to find the “best” execution plan by considering factors like query cost, data distribution, available indexes, and join strategies.</li><li><strong>Query Scheduler</strong>: The execution plan is scheduled and distributed across the compute nodes. The query scheduler assigns tasks to the available resources, considering factors like load balancing, data locality, and resource availability.</li><li><strong>Query Executor</strong>: The compute nodes execute the specific physical execution plan assigned to them. They perform operations like filtering, joining, aggregating, and applying functions based on the execution plan. The query executor efficiently processes the data in parallel and minimizes data movement across nodes.</li><li><strong>Storage Layer</strong>: The compute nodes retrieve data from the storage layer. This involves reading data from disk or memory, applying any necessary data transformations, and providing the queried data to the query executor for processing.</li></ol><h4>3.1 Query Optimizer</h4><p><strong>The core task of the query optimizer is to generate the “best” distributed physical execution plan with the lowest execution cost</strong>. As the data volume and complexity of SQL queries increase, the significance of the query optimizer becomes more prominent. Different physical execution plans can result in execution time differences of thousands or even millions of times. The query optimizer can be likened to the commander-in-chief of an army. If the decision-making is flawed, even the most skilled generals and soldiers will inevitably face defeat. Therefore, for an OLAP database to achieve high performance in complex queries, it must have a mature and efficient optimizer.</p><p>Recognizing the critical importance of the query optimizer, StarRocks has chosen to develop a Cost-Based Optimizer (CBO) from scratch. StarRocks’ optimizer is primarily based on the Cascades and ORCA research papers, but it has undergone extensive customization, optimization, and innovation to integrate seamlessly with the StarRocks executor and scheduler. It fully supports all 99 TPC-DS SQL queries and implements crucial features and optimizations such as common expression reuse, rewriting of correlated subqueries, Lateral Join, CTE (Common Table Expression) reuse, join reordering, selection of distributed join execution strategies, Global Runtime Filter pushdown, low cardinality dictionary optimizations, and more.</p><h4>3.2 Query Scheduler</h4><p>To fully utilize the resources of multiple machines, in addition to the MPP (Massively Parallel Processing) distributed execution framework, the query scheduler must balance the workload across multiple machines and minimize the occurrence of hotspots. Similarly, with the Pipeline parallel execution framework, when scheduling tasks on multiple cores, load balancing across the cores also needs to be considered.</p><p>The query scheduler plays a critical role in ensuring efficient resource utilization and optimizing performance in a distributed and multicore environment. It takes into account factors such as available resources, data locality, current system load, and task dependencies to make intelligent scheduling decisions.</p><h4>3.3 Query Executor</h4><p>To achieve exceptional query performance on a single core, the query executor needs to satisfy two main requirements:</p><ol><li><strong>process as little data as possible and as quickly as possible</strong></li><li><strong>minimize the amount of data transferred over the network and optimize the speed of data transmission.</strong></li></ol><p>The amount of data processed by the query executor is primarily determined by the query optimizer, and the query executor itself has limited influence over this factor. However, the query executor can optimize the processing speed by utilizing a vectorized execution approach, which will be discussed in the next subsection.</p><p>To minimize the amount of data transferred over the network and optimize the speed of data transmission, various strategies can be employed, as depicted in the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UFiG9Xx354p6tW1B.png" /></figure><ul><li><strong>Column Shuffle</strong>: In a vectorized engine, processing data by column is more efficient. It allows for better utilization of CPU cache and SIMD (Single Instruction, Multiple Data) instructions, resulting in faster query execution.</li><li><strong>Column Compression</strong>: Applying compression techniques specifically designed for columnar data storage can reduce the size of data on disk, in memory, and during network transmission. This helps optimize storage and reduce network transfer overhead.</li><li><strong>Join Distributed Execution with Minimal Network Transfer</strong>: The query optimizer and query scheduler work together to minimize network transfer during distributed join execution. By intelligently selecting join strategies and data placement, unnecessary data movement across the network can be avoided, improving query performance.</li><li><strong>Global Runtime Filter</strong>: StarRocks has implemented Global Runtime Filter, a feature that optimizes network transfer. This functionality will be covered in a dedicated sharing session to provide detailed insights on how it reduces network transmission overhead.</li><li><strong>Operations on Encoded Data</strong>: This optimization primarily focuses on low-cardinality strings encoded with dictionary encoding. A unique aspect of StarRocks is its ability to maintain a global dictionary within a distributed architecture that supports automatic data balancing. Combined with the CBO optimizer, StarRocks achieves comprehensive acceleration for queries involving low-cardinality strings. This significant feature will also be explained in a later blog.</li></ul><p>Here is a brief overview of how it accelerates queries involving low-cardinality strings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oLMRMgS_5Od24vNt.png" /></figure><p>As shown in the diagram above, for the SQL query involving a GROUP BY on City and Platform, if both City and Platform are low-cardinality strings, we can optimize the hash aggregation by converting it into hash aggregation on two integer columns. This transformation yields significant performance improvements in multiple critical operations such as Scan, Shuffle, Hash, Equal, and Memcpy. <strong>Through our measurements, we have observed an overall query performance improvement of up to three times.</strong></p><h4>3.4 <strong>Storage Layer</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XdQQ99hCKkLoOx5E.png" /></figure><p>As depicted in the diagram above, to achieve fast query execution, it is crucial for the storage layer to retrieve data quickly. <strong>The key to fast storage lies in reading less data and reading it faster.</strong></p><p>Optimizations to read less data include:</p><ol><li><strong>Partition and Bucket Pruning</strong>: Efficiently prune partitions and buckets based on query predicates, ensuring that only relevant data is read.</li><li><strong>Column Pruning</strong>: Eliminate unnecessary columns from being read, reducing I/O overhead and minimizing the amount of data transferred.</li><li><strong>Columnar Storage</strong>: Store data in a columnar format, which allows for efficient retrieval of specific columns, reducing the amount of data read from disk.</li><li><strong>Columnar Compression</strong>: Apply compression techniques designed for columnar storage to reduce the size of data on disk and memory, leading to faster read operations.</li><li><strong>Necessary Indexing</strong>: Create appropriate indexes to speed up data retrieval, enabling efficient data access based on specific query predicates.</li><li><strong>Early Filtering with Indexes and Metadata</strong>: Utilize indexes and metadata to filter out irrelevant data as early as possible during query execution, reducing the amount of data read from storage.</li><li><strong>Late Materialization</strong>: Materialize data at a later stage in the query processing pipeline, only when necessary, to avoid unnecessary data retrieval.</li></ol><p>Methods to read data faster include:</p><ol><li><strong>Operations on Encoded Data</strong>: Perform operations on encoded data, such as low-cardinality strings, using efficient encoding techniques to minimize data size and improve processing speed.</li><li><strong>Vectorized Processing</strong>: Utilize vectorized processing techniques to perform operations on data in batches, taking advantage of SIMD instructions and optimizing CPU cache utilization.</li><li><strong>Reduce I/O and Seek Operations</strong>: Minimize the number of I/O operations and seek times by organizing data effectively, leveraging memory caching, and optimizing disk access patterns.</li></ol><h4>3.5 Vectorized Executor</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YpSmMQ9geCdohcyi.png" /></figure><p>Vectorization primarily focuses on vectorizing operators and expressions. In the first diagram, an example of operator vectorization is illustrated, while the second diagram demonstrates expression vectorization. The core principle behind vectorized execution of operators and expressions is <strong>batch processing by column.</strong></p><p>Vectorized execution processes data in batches, operating on columns rather than individual rows. This approach offers several advantages over row-by-row execution. It reduces the number of virtual function calls and branch predictions, resulting in improved performance.</p><p>Batch processing allows for efficient execution of multiple records simultaneously. It minimizes function call overhead and enables parallel processing using SIMD instructions. By processing data in batches, vectorized execution maximizes CPU cache utilization and improves memory access patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AyZ99KyiRMajNRfS.png" /></figure><p>As shown in the diagram above, the challenges in implementing vectorized execution include:</p><ol><li><strong>Data Layout</strong>: Disk, memory, and network data need to be organized in a columnar layout, allowing for efficient column-based operations and vectorized processing.</li><li><strong>Vectorization of All Operators</strong>: All operators in the query execution pipeline must be vectorized to process data in batches and take advantage of SIMD instructions.</li><li><strong>Vectorization of All Expressions</strong>: All expressions involved in the query processing, such as filters, aggregations, and transformations, need to be vectorized to operate on columnar data efficiently.</li><li><strong>Utilization of SIMD Instructions</strong>: Whenever possible, SIMD instructions should be used to perform parallel processing on vectors of data, maximizing the efficiency of CPU instructions.</li><li><strong>CPU Cache Optimization</strong>: Optimizing data access patterns and memory utilization is crucial to maximize CPU cache usage, reducing memory latency and improving performance.</li><li><strong>Redesigned Memory Management Mechanism</strong>: An efficient memory management mechanism should be designed to handle columnar data structures and facilitate batch processing.</li><li><strong>Redesigned Algorithms and Data Structures</strong>: Important operators in the execution pipeline may require redesigning their algorithms and data structures to support vectorized processing and efficient data manipulation.</li><li><strong>Achieving 5x Overall Performance Improvement</strong>: To achieve an overall performance improvement of 5 times, every operator and expression in the pipeline must deliver a 5x performance gain. If any operator or expression lags behind, it hinders achieving the desired performance improvement.</li></ol><p>You are correct in stating that the challenges of vectorized execution lie in the<strong> engineering implementation and the intricacies of its details.</strong> The architecture of vectorized execution itself may not pose significant challenges, but the complexity lies in effectively implementing and optimizing the performance of vectorized processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*1eNdADe7UZhYwi0Q.png" /></figure><p>As depicted in the diagram above, StarRocks employs various techniques for performance optimization in vectorized execution, encompassing the seven points mentioned. It is important to note that each of these aspects plays a crucial role, and<strong> any deficiencies in any one of them can hinder the development of a high-performance vectorized execution engine.</strong></p><ul><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part1-b409836f5a7f">How to build an extremely fast analytical database -Part1</a></li><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part2-a74d45d6188d">How to build an extremely fast analytical database -Part2</a></li><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part3-78c5a06b88ed">How to build an extremely fast analytical database -Part3</a></li><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part4-306d610cc01a">How to build an extremely fast analytical database -Part4</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78c5a06b88ed" width="1" height="1" alt=""><hr><p><a href="https://medium.com/starrocks-engineering/how-to-build-an-extremely-fast-analytical-database-part3-78c5a06b88ed">How to build an extremely fast analytical database -Part3</a> was originally published in <a href="https://medium.com/starrocks-engineering">StarRocks Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build an extremely fast analytical database -Part2]]></title>
            <link>https://medium.com/starrocks-engineering/how-to-build-an-extremely-fast-analytical-database-part2-a74d45d6188d?source=rss-8553df50b43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a74d45d6188d</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[olap]]></category>
            <category><![CDATA[tech-deep-dive]]></category>
            <category><![CDATA[scalability]]></category>
            <dc:creator><![CDATA[Kaisen Kang]]></dc:creator>
            <pubDate>Thu, 15 Jun 2023 18:18:46 GMT</pubDate>
            <atom:updated>2023-06-23T22:09:03.282Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of databases, there are primarily two categories: transactional databases that focus on handling transactions and analytical databases that prioritize analysis. For an analytical database, performance is of utmost importance. In this article, I will share insights on how to create an exceptionally fast analytical database based on CPU technology. (Note: this article does not discuss heterogeneous computing such as GPU or FPGA, nor does it delve into new hardware accelerators like RDMA or NVM.)</p><p>This series of articles will explore nine perspectives: precomputation vs. on-the-fly computation, scalability, data streaming, resource utilization, optimization, resilience, architecture vs. details, approximation vs. precision, and performance testing. Through these angles, we will delve into the process of building a lightning-fast analytical database.</p><ul><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part1-b409836f5a7f">How to build an extremely fast analytical database -Part1</a></li><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part2-a74d45d6188d">How to build an extremely fast analytical database -Part2</a></li><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part3-78c5a06b88ed">How to build an extremely fast analytical database -Part3</a></li><li><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part4-306d610cc01a">How to build an extremely fast analytical database -Part4</a></li></ul><h3>Part2: Scalability</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xNp9qm37B7gPbu-4.png" /></figure><p>Modern analytical databases are almost always distributed databases, and we know that the key aspect of a distributed database is its scalability. To achieve exceptional performance, a database must possess three essential capabilities from a scalability perspective:</p><ol><li><strong>Ability to scale across multiple machines or fully utilize the resources of the entire cluster</strong>: In simpler terms, the query performance should scale linearly with the number of machines. The ability to scale across multiple machines depends on whether the distributed execution framework supports linear scalability. For example, StarRocks’ MPP (Massively Parallel Processing) distributed execution framework can scale linearly across multiple machines. On the other hand, frameworks like Apache Kylin, Apache Druid, and ClickHouse’s Scatter-Gather execution framework cannot scale linearly across multiple machines. They have single-point bottlenecks and lack the ability to efficiently perform high-cardinality aggregations or large table joins that require shuffle operations.</li><li><strong>Ability to scale across multiple CPU cores or fully utilize the multicore capabilities of a single machine</strong>: In simpler terms, the query performance should approximately scale linearly with the number of CPU cores. The ability to scale across multiple CPU cores depends on whether the parallel execution framework within a single machine supports multicore scalability. For example, StarRocks’ old parallel framework has limited multicore scalability, whereas its new Pipeline parallel framework exhibits strong multicore scalability. Other factors that affect multicore scalability include the implementation of parallel algorithms for different operators, optimizations for locks, NUMA-friendly designs, CPU affinity scheduling, false sharing prevention, and asynchronous execution.</li><li><strong>Exploration of the maximum potential of single-core CPU performance</strong>: To maximize CPU performance, it is essential to minimize the number of CPU instructions and the cycle per instruction (CPI) used during query execution. Additionally, triggering CPU SIMD (Single Instruction, Multiple Data) instruction optimizations and reducing CPU cache misses are crucial. There are two common approaches: vectorized execution and query compilation. Systems like StarRocks, ClickHouse, and Snowflake adopt vectorized execution, while systems like SingleStore, Hyper, and NoisePage utilize query compilation. The details of vectorized execution will be discussed later, and a separate article will be dedicated to query compilation.</li></ol><p>The following two images depict the conceptual representation of the <strong>StarRocks MPP (Massively Parallel Processing) distributed execution framework.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VkxsNM5nE_-r-CqKg0egAA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DBepG1msBPDJn8ZK.jpg" /></figure><p>The following two images illustrate the conceptual representation of the ClickHouse <strong>Scatter-Gather execution framework</strong>：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BK4uj9wS-RyU2FmR.jpg" /><figcaption>from Clickhouse blog</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6-LS-LNurhbBcPSl.jpg" /><figcaption>from Clickhouse blog</figcaption></figure><p>The image below represents the conceptual diagram of the old version of StarRocks parallel framework, with data parallelism at its core：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5sUSrt5xACPyri-V.png" /></figure><p>The following two images depict the conceptual representation of the StarRocks Pipeline parallel execution framework, where the core concept is the introduction of pipelines between Fragments and Operators. This framework transforms <strong>the kernel-level multi-threaded scheduling into user-level coroutine scheduling</strong>：</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t4UVuPiAgx7qY3b8.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtdIC92fKUezj9dszOhhcQ.png" /></figure><p><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part3-78c5a06b88ed">How to build an extremely fast analytical database -Part3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a74d45d6188d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/starrocks-engineering/how-to-build-an-extremely-fast-analytical-database-part2-a74d45d6188d">How to build an extremely fast analytical database -Part2</a> was originally published in <a href="https://medium.com/starrocks-engineering">StarRocks Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build an extremely fast analytical database -Part1]]></title>
            <link>https://medium.com/starrocks-engineering/how-to-build-an-extremely-fast-analytical-database-part1-b409836f5a7f?source=rss-8553df50b43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b409836f5a7f</guid>
            <category><![CDATA[materializedviews]]></category>
            <category><![CDATA[aggregation]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[tech-deep-dive]]></category>
            <category><![CDATA[data-analytics]]></category>
            <dc:creator><![CDATA[Kaisen Kang]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 23:48:25 GMT</pubDate>
            <atom:updated>2023-06-16T21:11:46.520Z</atom:updated>
            <content:encoded><![CDATA[<p>In the realm of databases, there are primarily two categories: transactional databases that focus on handling transactions and analytical databases that prioritize analysis. For an analytical database, performance is of utmost importance. In this article, I will share insights on how to create an exceptionally fast analytical database based on CPU technology. (Note: this article does not discuss heterogeneous computing such as GPU or FPGA, nor does it delve into new hardware accelerators like RDMA or NVM.)</p><p>This series of articles will explore nine perspectives: precomputation vs. on-the-fly computation, scalability, data streaming, resource utilization, optimization, resilience, architecture vs. details, approximation vs. precision, and performance testing. Through these angles, we will delve into the process of building a lightning-fast analytical database.</p><ul><li><a href="https://medium.com/starrocks-engineering/how-to-build-an-extremely-fast-analytical-database-part2-a74d45d6188d">How to build an extremely fast analytical database -Part2</a></li><li><a href="https://medium.com/starrocks-engineering/how-to-build-an-extremely-fast-analytical-database-part3-78c5a06b88ed">How to build an extremely fast analytical database -Part3</a></li><li><a href="https://medium.com/starrocks-engineering/how-to-build-an-extremely-fast-analytical-database-part3-78c5a06b88ed">How to build an extremely fast analytical database -Part3</a></li></ul><h3>Part1: Precomputation vs on-the-fly computation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aA2rbXU2z7nt51BA.jpg" /></figure><p>In essence, databases are primarily involved in two tasks: storing data and retrieving/querying data. When data is written into a database, it ensures data integrity and prevents data loss. When we need to query or analyze data, the database should be able to efficiently and accurately retrieve the desired information. As depicted in the diagram above, when the on-the-fly computational capacity of the database remains constant, there are two major approaches to enhance query performance:</p><ol><li>Precomputation during the database import process: This involves performing certain preprocessing steps to reduce the cost of on-the-fly computation.</li><li>Space-time trade-off during data storage: This approach aims to reduce the cost of on-the-fly computation by optimizing data storage.</li></ol><p>These approaches can be further categorized into four main techniques:</p><h3>1.1 Materialized View</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zVx_6nevHzjg5EyK.jpg" /></figure><p>As illustrated in the diagram above, materialized views involve precomputing the results of certain SQL queries and storing them in advance, trading off import latency and storage costs for high-performance querying. Materialized views are a common acceleration technique in OLAP databases. Some examples of materialized views in different database systems include:</p><ol><li>Materialized views in StarRocks.</li><li>Rollup in Google Mesa.</li><li>Cubes in Apache Kylin.</li><li>Star-Tree Index in Apache Pinot.</li><li>Lattice in Apache Calcite.</li><li>Reflections in Dremio.</li></ol><p>These techniques aim to optimize query performance by precomputing and storing aggregated or summarized data, reducing the need for on-the-fly computations during query execution.</p><p>The key considerations in materialized view technology are as follows:</p><ol><li><strong>Expressing the materialized view model</strong>: This involves defining the structure and content of the materialized views in a way that captures the desired data and query patterns.</li><li><strong>Determining which views or SQL queries to materialize</strong>: Typically, only a subset of views or queries need to be materialized to accelerate a significant number of queries. The selection process should consider the most frequently executed and time-consuming queries.</li><li><strong>Maintaining materialized views</strong>: When the base tables are updated, the materialized views need to be efficiently updated as well. This involves techniques such as incremental updates, support for multiple table materialized views, and handling updates and deletions to ensure data consistency.</li><li><strong>Finding the optimal materialized views for a given query</strong>: Determining which materialized views can be utilized to improve query performance requires an analysis of the query’s structure and the available materialized views.</li><li><strong>Query plan optimization with materialized views</strong>: Once the potential materialized views are identified, the query optimizer needs to choose the best execution plan by considering the cost and benefit of utilizing each materialized view.</li><li><strong>Balancing query performance, import speed, and storage costs</strong>: Finding the right balance between query performance improvements, import speed for maintaining materialized views, and storage costs is crucial. Google Napa, the successor to Google Mesa, has addressed this challenge effectively.</li></ol><p><strong><em>So when is materialized view technology necessary?</em></strong></p><ol><li>When dealing with extremely large datasets (in the order of billions or trillions) or small-scale clusters (a few nodes or tens of nodes).</li><li>When the query workload involves complex computations, such as joining multiple tables or performing precise deduplication.</li><li>When low query latency is a critical requirement that cannot be achieved solely through on-the-fly CPU-based computations.</li><li>When there is a need to optimize query performance in the face of significant computational challenges.</li><li>When the benefits of materialized views outweigh the associated costs, such as storage and maintenance overhead.</li></ol><p>Both Google Mesa and its successor, Google Napa, heavily rely on materialized views due to the scalability and performance benefits they provide in handling massive datasets and complex query workloads. However, if the dataset is not large, cluster resources are abundant, or the queries are not particularly complex, relying on on-the-fly computations may be sufficient and materialized views may not be necessary.</p><h3>1.2 Aggregation Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kO18EorGMGYJpjts7sQJPA.png" /></figure><p>In OLAP systems, there is a distinction between dimension columns and metric columns. Pre-aggregation, in this context, refers to the process of aggregating data from multiple rows into a single row during the data import phase. The values in dimension columns remain unchanged, while the metric columns are aggregated based on the associated aggregation functions. By performing pre-aggregation, the original dataset, which could have been billions of rows, can be reduced to just a few million rows. Processing a few million rows is significantly faster than processing each individual row separately.</p><p>Pre-aggregation is a common technique used in OLAP databases for performance optimization. Some examples include:</p><ol><li>Aggregation models in StarRocks.</li><li>Aggregation models in Apache Druid.</li></ol><h3>1.3 Index</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1HKGBMWthEkOqbt2VbhvVA.png" /></figure><p>An index, in the context mentioned, refers to metadata or data structures outside the original dataset that are used to accelerate the retrieval of specific values or offsets within the dataset. Indexing is generally categorized into lightweight indexes and heavyweight indexes. Lightweight indexes include ZoneMap indexes (Max, Min, Has null), prefix indexes, while heavyweight indexes include SkipList indexes, B-Tree family indexes, Hash indexes, Bitmap indexes, Bloom Filter indexes, among others. This blog will not delve into the specific technical details of indexing. However, the challenges of indexing can be summarized as follows:</p><ol><li>How to automatically select and build different types of indexes based on data scale, data types, and data cardinality.</li><li>When multiple indexes can be used for a single query, how to adaptively choose the best index.</li><li>Balancing between write speed, storage costs, and query performance.</li></ol><p>In summary, the purpose of indexing is to avoid reading a large amount of irrelevant data from the storage layer, thereby speeding up queries. It is an essential means of acceleration in database storage layers.</p><h3>1.4 Cache</h3><p>Cache is ubiquitous in computing, and if we know that a particular query will be queried multiple times, we can cache the first occurrence of that query. Caches can exist at various levels, such as the operating system’s Page Cache, the database storage layer’s cache for files or pages at the block level, and the database computing layer’s cache for partitions, segments, and result sets. The challenges of caching include avoiding frequent cache evictions and ensuring cache hit rates. There are numerous articles discussing caching in detail, but this blog will not delve into it extensively.</p><h3>1.5 Generated Column</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9nqILxXjl14kpPGklk6NA.png" /></figure><p>As shown in the diagram, when there is a need to accelerate certain computationally intensive expressions or speed up queries on specific columns within complex types (such as Map, Json, Struct), one approach is to materialize the computed results of those expressions or store specific columns of the complex types. This allows for automatic query rewriting during retrieval, achieving transparent query acceleration.</p><p>In the next article, we will discuss how to build an ultra-fast database from the perspective of <strong>scalability</strong>.</p><p><a href="https://medium.com/@kangkaisen/how-to-build-an-extremely-fast-analytical-database-part2-a74d45d6188d">How to build an extremely fast analytical database -Part2</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b409836f5a7f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/starrocks-engineering/how-to-build-an-extremely-fast-analytical-database-part1-b409836f5a7f">How to build an extremely fast analytical database -Part1</a> was originally published in <a href="https://medium.com/starrocks-engineering">StarRocks Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ChatGPT automatically finds bugs for database]]></title>
            <link>https://medium.com/@kangkaisen/chatgpt-automatically-finds-bugs-for-database-804bac1a38f4?source=rss-8553df50b43f------2</link>
            <guid isPermaLink="false">https://medium.com/p/804bac1a38f4</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[test-automation]]></category>
            <dc:creator><![CDATA[Kaisen Kang]]></dc:creator>
            <pubDate>Sun, 26 Feb 2023 02:36:29 GMT</pubDate>
            <atom:updated>2023-02-26T02:36:29.748Z</atom:updated>
            <content:encoded><![CDATA[<h3>1 ChatGPT replaces SQLsmith</h3><p>SQLsmith is a database automation testing tool. The main principle is to generate random SQL according to a fixed table schema and send it to the database to see if the database whether crash.</p><p>This is no challenge for ChatGPT , which can generate arbitrarily complex SQL based on natural language descriptions, so that ChatGPT can replace SQLsmith.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2O_LA4DX39rJk81d" /></figure><h3>2 ChatGPT amazing learning ability</h3><p>The first thing that came to my mind in the next step was whether ChatGPT could solve a big pain point in maintaining automated testing tools such as SQLsmith and SQLancer: every time a function, operator, or data type is added, we need to update the source code of tools such as SQLsmith and SQLancer, and find new bugs in time. So I tried StarRocks Json function, the first ChatGPT reply, by September 2021, StarRocks didn’t support Json function, then I gave StarRocks Json doc, and then let ChatGPT generate SQL with Json function, ChatGPT can be generated, showing amazing learning ability.</p><p>At the beginning, ChatGPT said that StarRocks did not support the Json function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rcnFmzPEDL_Vk3bK" /></figure><p>Here is the picture, I asked ChatGPT to learn the Json function of StarRocks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h1i48Zb5Gz3PcSbD" /></figure><p>The following figure shows that ChatGPT successfully generates a SQL with a Json function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*p18syepvZBA-PFnA" /></figure><h3>3 ChatGPT replaces SQLancer</h3><p>Knowing that ChatGPT can replace SQLsmith, I wanted to try whether ChatGPT can replace SQLancer. Mainly tried SQLancer’s TLP method,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*09rrn3Ygp02K8lO1" /></figure><p>The above figure is a schematic of the principle of TLP. In simple terms, arbitrarily give a SQL Q and a predicate P, and the SQL Q is filtered by P, not P, P is null. The result of Union all is found to be consistent with the original SQL Q. The query result set is consistent.</p><p>After more than a dozen training sessions, ChatGPT initially has the ability to generate equivalent SQL based on the TLP principle:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IHMzXYAShhqmPtO5" /></figure><p>The complete SQLancer TLP test requires two additional steps, randomly creating tables and inserting data at random. This is very simple for ChatGPT . The following figures are a complete process diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SIGyucSq7n4oRIZE" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*w-L2mpHdb_Ce5bEh" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yvMQpOreXVy2ou_S" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YMD52twIInIjAq3t" /></figure><h3>4 ChatGPT generates Query-Aware table create statements</h3><p>Database SQL automated testing mainly includes the following three major points:</p><ol><li>How to automate table creation and data import</li><li>How to automatically generate test SQL</li><li>How to automatically generate tests, predictions (confirm that the results of SQL execution are as expected)</li></ol><p>The challenges of database SQL automated testing are mainly as follows:</p><ol><li>Make sure the automatically generated SQL is syntactically and semantically correct</li><li>Automatically generate legitimate Schame and datasets</li><li>Automatically generated SQL code coverage is high enough</li><li>Have an efficient way to verify that SQL execution results are correct</li></ol><p>So I specifically tested whether ChatGPT can generate Query-Aware table create statements. Query-Aware means that the table create and import data are SQL reference queries, which can ensure that the corresponding SQL will have query results. This point poses little challenge to ChatGPT:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mOi2ANLFPw5uzo4j" /></figure><p>You can see that the generated three create table statements can meet the requirements of the corresponding SQL Schema.</p><h3>Summary</h3><p>From the preliminary test point of view, the use of ChatGPT for database SQL automated testing has great potential. The difficulty lies in that ChatGPT must fully understand the basic logic of some automated testing, such as the basic rewriting principle of SQLancer’s TLP testing. After dozens of training sessions, ChatGPT Still not fully understood, the predicates in the rewritten SQL may be wrong, but in theory, after enough training, ChatGPT fully understands this logic without any problem, and ChatGPT’s biggest advantage is its amazing learning ability, which can make ChatGPT writing test cases for new features is far more efficient than humans, and I will continue to try and explore them later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=804bac1a38f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>